blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
sequence | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2040bb71bab9d68e51d7bbaa539f6b9df6820064 | 9,242,769,636,922 | 0d476ca9bfad79739fe2f27eb869a3ef2b04e685 | /prototipoSistemaSpring/src/main/java/com/br/cat/controllers/TipoEmitenteController.java | 5ed4cb239c21ae5b992637c6f478b211ef12bf99 | [] | no_license | tiago-oliveira89/cursospring | https://github.com/tiago-oliveira89/cursospring | d7bcc859c9d4aa2014825565d34823fe83f9448f | 50cc089f61aaa1354b1b7dc0f9297b521523a59b | refs/heads/master | 2020-04-15T22:41:31.010000 | 2019-05-08T02:59:22 | 2019-05-08T02:59:22 | 165,082,536 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.br.cat.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.br.cat.entities.TipoEmitente;
import com.br.cat.services.TipoEmitenteService;
@RestController
public class TipoEmitenteController {
@Autowired
private TipoEmitenteService tipoEmitenteService;
@GetMapping("tipoEmitenteValido")
public List<TipoEmitente> getListaTipoEmitenteValido(){
return tipoEmitenteService.getListaTipoEmitenteValido();
}
}
| UTF-8 | Java | 611 | java | TipoEmitenteController.java | Java | [] | null | [] | package com.br.cat.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.br.cat.entities.TipoEmitente;
import com.br.cat.services.TipoEmitenteService;
@RestController
public class TipoEmitenteController {
@Autowired
private TipoEmitenteService tipoEmitenteService;
@GetMapping("tipoEmitenteValido")
public List<TipoEmitente> getListaTipoEmitenteValido(){
return tipoEmitenteService.getListaTipoEmitenteValido();
}
}
| 611 | 0.831424 | 0.831424 | 23 | 25.565218 | 23.928928 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.826087 | false | false | 4 |
1f52e0cf2394c46446feddf80c742a4e696a17ce | 2,430,951,490,954 | 92ed94a502df0ff73e99a9515744b6c11482bb32 | /src/nl/lxtreme/libtdl/grammar/adv/Term.java | 19bfbed491223a3d5a90f3308ef0949fec7defc4 | [] | no_license | vijayvani/libtdl | https://github.com/vijayvani/libtdl | b4d199474346f8a04ace4120a077eeee3a74bfa9 | a972b1716bdfde15ebc7aa45010668164b8f808d | refs/heads/master | 2020-05-16T08:55:26.106000 | 2014-09-11T10:14:14 | 2014-09-11T10:14:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* LibTDL - Library for parsing/handling the "Trigger Definition Language".
*
* (C) Copyright 2012-2013 - J.W. Janssen, <j.w.janssen@lxtreme.nl>
*
* Licensed under Apache Software License version 2.0, see <http://www.apache.org/licenses/LICENSE-2.0.html>.
*/
package nl.lxtreme.libtdl.grammar.adv;
import java.io.*;
import nl.lxtreme.libtdl.grammar.*;
/**
* Provides a term definition.
*/
class Term extends AbstractDefinition {
// CONSTANTS
private static final int MAX_TERMS = 10;
// VARIABLES
private final int m_index;
private final int m_value;
private final int m_mask;
// CONSTRUCTORS
/**
* Creates a new {@link Term} instance.
*/
public Term(String termName, long value, long mask) {
this(toIndex(termName), value, mask);
}
/**
* Creates a new {@link Term} instance.
*/
public Term(int index, long value, long mask) {
super(Type.TERM);
m_index = index % MAX_TERMS;
m_value = (int) (value & MASK_32BIT);
m_mask = (int) (mask & MASK_32BIT);
}
// METHODS
/**
* Converts the given term name to a numeric index, for example, "termA"
* =>
* 0, "termB" => 1, and so on.
*
* @param termName
* the term name to convert.
* @return the numeric index for the given term name, >= 0.
*/
static int toIndex(String termName) {
if ((termName == null) || "".equals(termName)) {
throw new IllegalArgumentException("Term name cannot be null or empty!");
}
return termName.toLowerCase().charAt(termName.length() - 1) - 'a';
}
/**
* @return the index of this term, >= 0 && < 10.
*/
public int getIndex() {
return m_index;
}
/**
* @return the mask of this term, as 32-bit unsigned value.
*/
public int getMask() {
return m_mask;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return String.format("term%c", ('A' + m_index));
}
/**
* @return the value of this mask, as 32-bit unsigned value.
*/
public int getValue() {
return m_value;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("%s: (%x ^ %x)", getName(), getMask(), getValue());
}
/**
* {@inheritDoc}
*/
@Override
public void write(TdlOutputStream outputStream) throws IOException {
int bitmask = 1;
int lutvalue0 = 0;
int lutvalue1 = 0;
int lutvalue2 = 0;
int lutvalue3 = 0;
for (int i = 0; i < 16; i++) {
if (((i ^ (m_value & 0xF)) & (m_mask & 0xF)) == 0) {
lutvalue0 |= bitmask;
}
if (((i ^ ((m_value >> 4) & 0xF)) & ((m_mask >> 4) & 0xF)) == 0) {
lutvalue0 |= (bitmask << 16);
}
if (((i ^ ((m_value >> 8) & 0xF)) & ((m_mask >> 8) & 0xF)) == 0) {
lutvalue1 |= bitmask;
}
if (((i ^ ((m_value >> 12) & 0xF)) & ((m_mask >> 12) & 0xF)) == 0) {
lutvalue1 |= (bitmask << 16);
}
if (((i ^ ((m_value >> 16) & 0xF)) & ((m_mask >> 16) & 0xF)) == 0) {
lutvalue2 |= bitmask;
}
if (((i ^ ((m_value >> 20) & 0xF)) & ((m_mask >> 20) & 0xF)) == 0) {
lutvalue2 |= (bitmask << 16);
}
if (((i ^ ((m_value >> 24) & 0xF)) & ((m_mask >> 24) & 0xF)) == 0) {
lutvalue3 |= bitmask;
}
if (((i ^ ((m_value >> 28) & 0xF)) & ((m_mask >> 28) & 0xF)) == 0) {
lutvalue3 |= (bitmask << 16);
}
bitmask <<= 1;
}
// Write data into LUT serial chain. MSB must goes in first. Total of
// 128
// bits.
outputStream.writeSelect(0x20 + getIndex());
outputStream.writeData(lutvalue3);
outputStream.writeData(lutvalue2);
outputStream.writeData(lutvalue1);
outputStream.writeData(lutvalue0);
}
}
| UTF-8 | Java | 4,150 | java | Term.java | Java | [
{
"context": "inition Language\".\n *\n * (C) Copyright 2012-2013 - J.W. Janssen, <j.w.janssen@lxtreme.nl>\n *\n * Licensed under Ap",
"end": 123,
"score": 0.9998517632484436,
"start": 111,
"tag": "NAME",
"value": "J.W. Janssen"
},
{
"context": "\".\n *\n * (C) Copyright 2012-2013 - J.W. Janssen, <j.w.janssen@lxtreme.nl>\n *\n * Licensed under Apache Software License ver",
"end": 148,
"score": 0.9999335408210754,
"start": 126,
"tag": "EMAIL",
"value": "j.w.janssen@lxtreme.nl"
}
] | null | [] | /*
* LibTDL - Library for parsing/handling the "Trigger Definition Language".
*
* (C) Copyright 2012-2013 - <NAME>, <<EMAIL>>
*
* Licensed under Apache Software License version 2.0, see <http://www.apache.org/licenses/LICENSE-2.0.html>.
*/
package nl.lxtreme.libtdl.grammar.adv;
import java.io.*;
import nl.lxtreme.libtdl.grammar.*;
/**
* Provides a term definition.
*/
class Term extends AbstractDefinition {
// CONSTANTS
private static final int MAX_TERMS = 10;
// VARIABLES
private final int m_index;
private final int m_value;
private final int m_mask;
// CONSTRUCTORS
/**
* Creates a new {@link Term} instance.
*/
public Term(String termName, long value, long mask) {
this(toIndex(termName), value, mask);
}
/**
* Creates a new {@link Term} instance.
*/
public Term(int index, long value, long mask) {
super(Type.TERM);
m_index = index % MAX_TERMS;
m_value = (int) (value & MASK_32BIT);
m_mask = (int) (mask & MASK_32BIT);
}
// METHODS
/**
* Converts the given term name to a numeric index, for example, "termA"
* =>
* 0, "termB" => 1, and so on.
*
* @param termName
* the term name to convert.
* @return the numeric index for the given term name, >= 0.
*/
static int toIndex(String termName) {
if ((termName == null) || "".equals(termName)) {
throw new IllegalArgumentException("Term name cannot be null or empty!");
}
return termName.toLowerCase().charAt(termName.length() - 1) - 'a';
}
/**
* @return the index of this term, >= 0 && < 10.
*/
public int getIndex() {
return m_index;
}
/**
* @return the mask of this term, as 32-bit unsigned value.
*/
public int getMask() {
return m_mask;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return String.format("term%c", ('A' + m_index));
}
/**
* @return the value of this mask, as 32-bit unsigned value.
*/
public int getValue() {
return m_value;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("%s: (%x ^ %x)", getName(), getMask(), getValue());
}
/**
* {@inheritDoc}
*/
@Override
public void write(TdlOutputStream outputStream) throws IOException {
int bitmask = 1;
int lutvalue0 = 0;
int lutvalue1 = 0;
int lutvalue2 = 0;
int lutvalue3 = 0;
for (int i = 0; i < 16; i++) {
if (((i ^ (m_value & 0xF)) & (m_mask & 0xF)) == 0) {
lutvalue0 |= bitmask;
}
if (((i ^ ((m_value >> 4) & 0xF)) & ((m_mask >> 4) & 0xF)) == 0) {
lutvalue0 |= (bitmask << 16);
}
if (((i ^ ((m_value >> 8) & 0xF)) & ((m_mask >> 8) & 0xF)) == 0) {
lutvalue1 |= bitmask;
}
if (((i ^ ((m_value >> 12) & 0xF)) & ((m_mask >> 12) & 0xF)) == 0) {
lutvalue1 |= (bitmask << 16);
}
if (((i ^ ((m_value >> 16) & 0xF)) & ((m_mask >> 16) & 0xF)) == 0) {
lutvalue2 |= bitmask;
}
if (((i ^ ((m_value >> 20) & 0xF)) & ((m_mask >> 20) & 0xF)) == 0) {
lutvalue2 |= (bitmask << 16);
}
if (((i ^ ((m_value >> 24) & 0xF)) & ((m_mask >> 24) & 0xF)) == 0) {
lutvalue3 |= bitmask;
}
if (((i ^ ((m_value >> 28) & 0xF)) & ((m_mask >> 28) & 0xF)) == 0) {
lutvalue3 |= (bitmask << 16);
}
bitmask <<= 1;
}
// Write data into LUT serial chain. MSB must goes in first. Total of
// 128
// bits.
outputStream.writeSelect(0x20 + getIndex());
outputStream.writeData(lutvalue3);
outputStream.writeData(lutvalue2);
outputStream.writeData(lutvalue1);
outputStream.writeData(lutvalue0);
}
}
| 4,129 | 0.49494 | 0.466988 | 150 | 26.666666 | 25.12042 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false | 4 |
27067107f3ffb0b7de2552c3ca454aabeeeb2c6b | 7,773,890,827,878 | 034905705528734d4a6896c4e8238a162ceb2f88 | /server/src/main/java/com/riseofcat/RoomsDecorator.java | 562a4df3abfd5fe7a94592f227067b786bc5de14 | [] | no_license | riseofcat/n8cats3 | https://github.com/riseofcat/n8cats3 | 6d7abe99647e9f32a9c5b95c752bead99f29c037 | 0b52aa8503e161a9a8d45e96d75178123ba20808 | refs/heads/master | 2021-01-21T14:43:24.053000 | 2017-09-28T23:35:39 | 2017-09-28T23:35:39 | 95,326,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.riseofcat;
import com.n8cats.lib_gwt.Signal;
import com.n8cats.share.Logic;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class RoomsDecorator<TClientPayload, TServerPayload> extends SesServ<TClientPayload, TServerPayload> {
public final static int MAXIMUM_ROOM_PLAYERS = 5;
public final Signal<Room> onRoomCreated = new Signal<>();
//todo onRoomDestroyed
private final Set<Room> rooms = new HashSet<>();
private final Map<Ses, Room> map = new ConcurrentHashMap<>();
public RoomsDecorator() {
}
public RoomsDecorator(Signal.Listener<Room> roomCreatedListener) {
onRoomCreated.add(roomCreatedListener);
}
public void start(Ses session) {
Room room = null;
synchronized(this) {
for(Room r : rooms) {
if(r.getPlayersCount() < MAXIMUM_ROOM_PLAYERS) {
room = r;
break;
}
}
if(room == null) {
App.log.info("new room created");
room = new Room();
rooms.add(room);
onRoomCreated.dispatch(room);
}
room.add(session);
}
map.put(session, room);
}
public void close(Ses session) {
Room room = map.remove(session);
room.remove(session);
}
public void message(Ses session, TClientPayload payload) {
Room room = map.get(session);
room.message(session, payload);
}
public class Room {
final public Signal<Player> onPlayerAdded = new Signal<>();
final public Signal<Player> onPlayerRemoved = new Signal<>();
final public Signal<PlayerMessage> onMessage = new Signal<>();
private final Map<Ses, Player> players = new ConcurrentHashMap<>();
public int getPlayersCount() {
return players.size();
}
public Collection<Player> getPlayers() {
return players.values();
}
private void add(Ses session) {
Player player = new Player(session);
players.put(session, player);
synchronized(this) {
onPlayerAdded.dispatch(player);
}
}
private void message(Ses session, TClientPayload payload) {
onMessage.dispatch(new PlayerMessage(players.get(session), payload));
}
private void remove(Ses session) {
Player remove = players.remove(session);
synchronized(this) {
onPlayerRemoved.dispatch(remove);
}
}
public class Player extends Logic.Player {
public final Ses session;
public Player(Ses session) {
this.session = session;
}
public Id getId() {
return new Id(session.getId());
}
}
}
public class PlayerMessage {
public final Room.Player player;
public final TClientPayload payload;
public PlayerMessage(Room.Player player, TClientPayload payload) {
this.player = player;
this.payload = payload;
}
}
public static class RoomHandler<TClientPayload, TServerPayload, E> {
public void handleRoomCreated(RoomsDecorator<TClientPayload, TServerPayload>.Room room) {
}
}
}
| UTF-8 | Java | 2,769 | java | RoomsDecorator.java | Java | [] | null | [] | package com.riseofcat;
import com.n8cats.lib_gwt.Signal;
import com.n8cats.share.Logic;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class RoomsDecorator<TClientPayload, TServerPayload> extends SesServ<TClientPayload, TServerPayload> {
public final static int MAXIMUM_ROOM_PLAYERS = 5;
public final Signal<Room> onRoomCreated = new Signal<>();
//todo onRoomDestroyed
private final Set<Room> rooms = new HashSet<>();
private final Map<Ses, Room> map = new ConcurrentHashMap<>();
public RoomsDecorator() {
}
public RoomsDecorator(Signal.Listener<Room> roomCreatedListener) {
onRoomCreated.add(roomCreatedListener);
}
public void start(Ses session) {
Room room = null;
synchronized(this) {
for(Room r : rooms) {
if(r.getPlayersCount() < MAXIMUM_ROOM_PLAYERS) {
room = r;
break;
}
}
if(room == null) {
App.log.info("new room created");
room = new Room();
rooms.add(room);
onRoomCreated.dispatch(room);
}
room.add(session);
}
map.put(session, room);
}
public void close(Ses session) {
Room room = map.remove(session);
room.remove(session);
}
public void message(Ses session, TClientPayload payload) {
Room room = map.get(session);
room.message(session, payload);
}
public class Room {
final public Signal<Player> onPlayerAdded = new Signal<>();
final public Signal<Player> onPlayerRemoved = new Signal<>();
final public Signal<PlayerMessage> onMessage = new Signal<>();
private final Map<Ses, Player> players = new ConcurrentHashMap<>();
public int getPlayersCount() {
return players.size();
}
public Collection<Player> getPlayers() {
return players.values();
}
private void add(Ses session) {
Player player = new Player(session);
players.put(session, player);
synchronized(this) {
onPlayerAdded.dispatch(player);
}
}
private void message(Ses session, TClientPayload payload) {
onMessage.dispatch(new PlayerMessage(players.get(session), payload));
}
private void remove(Ses session) {
Player remove = players.remove(session);
synchronized(this) {
onPlayerRemoved.dispatch(remove);
}
}
public class Player extends Logic.Player {
public final Ses session;
public Player(Ses session) {
this.session = session;
}
public Id getId() {
return new Id(session.getId());
}
}
}
public class PlayerMessage {
public final Room.Player player;
public final TClientPayload payload;
public PlayerMessage(Room.Player player, TClientPayload payload) {
this.player = player;
this.payload = payload;
}
}
public static class RoomHandler<TClientPayload, TServerPayload, E> {
public void handleRoomCreated(RoomsDecorator<TClientPayload, TServerPayload>.Room room) {
}
}
}
| 2,769 | 0.732394 | 0.731311 | 101 | 26.415842 | 22.435946 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.70297 | false | false | 4 |
00a909dae2c8b1ab3be9d07973016c2590f15e06 | 6,416,681,209,468 | e6d81ffba43663363fa53bfa3abead5b115d1446 | /Bank_Account/java/bankaccount/src/main/java/com/example/bankaccount/model/TransactionsModel.java | 55a7d706e6321ff4d9de0fe474fb6e36009b9fba | [] | no_license | kidfrom/archived-learn-java | https://github.com/kidfrom/archived-learn-java | 661835d5c647e14ec13407a3c3aa21201413fb63 | 8bb738d3700df60b6241bbf7f621ab8a8de95f65 | refs/heads/main | 2023-03-11T20:53:25.480000 | 2021-02-27T16:55:26 | 2021-02-27T16:55:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bankaccount.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
public class TransactionsModel implements Serializable {
private LocalDate Date;
private String Source;
@Pattern(regexp = "[0-9]{17}", message = "Destination length must be 17")
private String Destination;
@Range(min = 1, max = 10, message = "Destination_Type is unknown")
private int Destination_Type;
@NotNull(message = "Transaction_Value must not be null")
@DecimalMin(value = "1.0", message = "Transaction_Value must not be null")
private BigDecimal Transaction_Value;
private String Progress_ID; // this attribute is for TransactionsControllerv2, this is not stored in transactions table.
public TransactionsModel(String destination, int destination_Type, BigDecimal transaction_Value) {
Destination = destination;
Destination_Type = destination_Type;
Transaction_Value = transaction_Value;
}
public TransactionsModel(@JsonProperty("Date") LocalDate date, @JsonProperty("Source") String source, @JsonProperty("Destination") String destination, @JsonProperty("Destination_Type") int destination_type, @JsonProperty("Transaction_Value") BigDecimal transaction_value) {
Date = date;
Source = source;
Destination = destination;
Destination_Type = destination_type;
Transaction_Value = transaction_value;
}
public LocalDate getDate() {
return Date;
}
public void setDate() {
Date = LocalDate.now();
}
public String getSource() {
return Source;
}
public void setSource(String source) {
Source = source;
}
public String getDestination() {
return Destination;
}
public int getDestination_Type() {
return Destination_Type;
}
public BigDecimal getTransaction_Value() {
return Transaction_Value;
}
public String getProgress_ID() {
return Progress_ID;
}
public void setProgress_ID(String progress_ID) {
Progress_ID = progress_ID;
}
}
| UTF-8 | Java | 2,141 | java | TransactionsModel.java | Java | [] | null | [] | package com.example.bankaccount.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
public class TransactionsModel implements Serializable {
private LocalDate Date;
private String Source;
@Pattern(regexp = "[0-9]{17}", message = "Destination length must be 17")
private String Destination;
@Range(min = 1, max = 10, message = "Destination_Type is unknown")
private int Destination_Type;
@NotNull(message = "Transaction_Value must not be null")
@DecimalMin(value = "1.0", message = "Transaction_Value must not be null")
private BigDecimal Transaction_Value;
private String Progress_ID; // this attribute is for TransactionsControllerv2, this is not stored in transactions table.
public TransactionsModel(String destination, int destination_Type, BigDecimal transaction_Value) {
Destination = destination;
Destination_Type = destination_Type;
Transaction_Value = transaction_Value;
}
public TransactionsModel(@JsonProperty("Date") LocalDate date, @JsonProperty("Source") String source, @JsonProperty("Destination") String destination, @JsonProperty("Destination_Type") int destination_type, @JsonProperty("Transaction_Value") BigDecimal transaction_value) {
Date = date;
Source = source;
Destination = destination;
Destination_Type = destination_type;
Transaction_Value = transaction_value;
}
public LocalDate getDate() {
return Date;
}
public void setDate() {
Date = LocalDate.now();
}
public String getSource() {
return Source;
}
public void setSource(String source) {
Source = source;
}
public String getDestination() {
return Destination;
}
public int getDestination_Type() {
return Destination_Type;
}
public BigDecimal getTransaction_Value() {
return Transaction_Value;
}
public String getProgress_ID() {
return Progress_ID;
}
public void setProgress_ID(String progress_ID) {
Progress_ID = progress_ID;
}
}
| 2,141 | 0.732368 | 0.726763 | 72 | 28.736111 | 38.2034 | 275 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569444 | false | false | 4 |
786b8dd8fca4e97766c97579cd638b34bb7b43ab | 3,478,923,549,648 | dda453de30c2fac119f62dd77e49e724b4a915f4 | /springboot/edu_web/seata_web/src/main/java/com/study/seata/model/TargetBean.java | 082479c375dad22e66aa57e37c3184cc1e910866 | [] | no_license | luoshangcai/springboot | https://github.com/luoshangcai/springboot | 645806448ab601c410a91d5fd8057f06f6871f1e | 4150d5af7498de0973d405e3ccdd10a11ff897ca | refs/heads/master | 2023-08-15T04:09:54.937000 | 2021-09-18T03:39:14 | 2021-09-18T03:39:14 | 258,728,953 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.study.seata.model;
import lombok.Data;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* @Description:
* @Author: luoshangcai
* @Date 2020-08-18 17:53
**/
@Data
public class TargetBean {
private Integer intProperty;
private boolean booleanProperty;
private float floatProperty;
private double doubleProperty;
private long longProperty;
private char charProperty;
private byte byteProperty;
private short shortProperty;
private Integer integerProperty;
private Boolean booleanObjProperty;
private Float floatObjProperty;
private Double doubleObjProperty;
private Long longObjProperty;
private Short shortObjProperty;
private Byte byteObjProperty;
private BigInteger bigIntegerProperty;
private BigDecimal bigDecimalProperty;
private String stringProperty;
}
| UTF-8 | Java | 862 | java | TargetBean.java | Java | [
{
"context": "math.BigInteger;\n\n/**\n * @Description:\n * @Author: luoshangcai\n * @Date 2020-08-18 17:53\n **/\n@Data\npublic class",
"end": 156,
"score": 0.9985494613647461,
"start": 145,
"tag": "USERNAME",
"value": "luoshangcai"
}
] | null | [] | package com.study.seata.model;
import lombok.Data;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* @Description:
* @Author: luoshangcai
* @Date 2020-08-18 17:53
**/
@Data
public class TargetBean {
private Integer intProperty;
private boolean booleanProperty;
private float floatProperty;
private double doubleProperty;
private long longProperty;
private char charProperty;
private byte byteProperty;
private short shortProperty;
private Integer integerProperty;
private Boolean booleanObjProperty;
private Float floatObjProperty;
private Double doubleObjProperty;
private Long longObjProperty;
private Short shortObjProperty;
private Byte byteObjProperty;
private BigInteger bigIntegerProperty;
private BigDecimal bigDecimalProperty;
private String stringProperty;
}
| 862 | 0.758701 | 0.74478 | 33 | 25.121212 | 13.270514 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 4 |
f2c5e3a9865d420ac18bb4a2adb901e7521add0d | 3,478,923,551,871 | 9fc7c9a87b98539851ccf3236ed0ff53cb3a5c7f | /app/src/main/java/tutorial/root/ui/activity/mainActivity/adapter/BusListAdapter.java | 806f5ce832a427310e381eca4baa79bb32a1f127 | [] | no_license | aykhan-dev/BakuBus | https://github.com/aykhan-dev/BakuBus | 0a617e306cb97c30b84ab97e83b75552f8db6947 | e69d876bb34f3d3646130bd7af3c7d187ad84946 | refs/heads/master | 2022-02-25T00:39:52.991000 | 2019-10-08T10:08:20 | 2019-10-08T10:08:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tutorial.root.ui.activity.mainActivity.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import tutorial.root.R;
import tutorial.root.pojo.response.Attributes;
import tutorial.root.pojo.response.Bus;
public class BusListAdapter extends RecyclerView.Adapter<BusListAdapter.VH> {
private Context context;
private List<Bus> busList = new ArrayList<>();
private BusListAdapterCallback callbackListener;
public BusListAdapter(Context context) {
this.context = context;
if(context instanceof BusListAdapterCallback) callbackListener = (BusListAdapterCallback) context;
}
public interface BusListAdapterCallback {
void showRoute(String busCode, String route);
}
@NonNull
@Override
public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_bus_list, parent, false);
return new VH(view);
}
@Override
public void onBindViewHolder(@NonNull VH holder, int position) {
holder.bind(busList.get(position).getAttributes());
}
@Override
public int getItemCount() {
return busList.size();
}
public void updateBusList (List<Bus> updatedBusList) {
busList.clear();
busList.addAll(updatedBusList);
notifyDataSetChanged();
}
class VH extends RecyclerView.ViewHolder {
private View root;
private TextView busNumber;
VH(@NonNull View itemView) {
super(itemView);
this.root = itemView;
}
@SuppressLint("SetTextI18n")
private void bind(final Attributes attribute) {
initializeUI();
busNumber.setText(attribute.getDisplayRouteCode() + "\n\n" + attribute.getRouteName());
root.setOnClickListener(view -> callbackListener.showRoute(attribute.getDisplayRouteCode(), attribute.getRouteName()));
}
private void initializeUI() {
busNumber = root.findViewById(R.id.text_view_number_of_bus);
}
}
}
| UTF-8 | Java | 2,372 | java | BusListAdapter.java | Java | [] | null | [] | package tutorial.root.ui.activity.mainActivity.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import tutorial.root.R;
import tutorial.root.pojo.response.Attributes;
import tutorial.root.pojo.response.Bus;
public class BusListAdapter extends RecyclerView.Adapter<BusListAdapter.VH> {
private Context context;
private List<Bus> busList = new ArrayList<>();
private BusListAdapterCallback callbackListener;
public BusListAdapter(Context context) {
this.context = context;
if(context instanceof BusListAdapterCallback) callbackListener = (BusListAdapterCallback) context;
}
public interface BusListAdapterCallback {
void showRoute(String busCode, String route);
}
@NonNull
@Override
public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_bus_list, parent, false);
return new VH(view);
}
@Override
public void onBindViewHolder(@NonNull VH holder, int position) {
holder.bind(busList.get(position).getAttributes());
}
@Override
public int getItemCount() {
return busList.size();
}
public void updateBusList (List<Bus> updatedBusList) {
busList.clear();
busList.addAll(updatedBusList);
notifyDataSetChanged();
}
class VH extends RecyclerView.ViewHolder {
private View root;
private TextView busNumber;
VH(@NonNull View itemView) {
super(itemView);
this.root = itemView;
}
@SuppressLint("SetTextI18n")
private void bind(final Attributes attribute) {
initializeUI();
busNumber.setText(attribute.getDisplayRouteCode() + "\n\n" + attribute.getRouteName());
root.setOnClickListener(view -> callbackListener.showRoute(attribute.getDisplayRouteCode(), attribute.getRouteName()));
}
private void initializeUI() {
busNumber = root.findViewById(R.id.text_view_number_of_bus);
}
}
}
| 2,372 | 0.693508 | 0.692664 | 85 | 26.905882 | 27.951059 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482353 | false | false | 4 |
06dc5b732990c20a39a561570441b0a4c8d3f69e | 16,389,595,201,656 | b33989456324cfd552d88b3ecca397ee9c2c7966 | /CucumberTest/src/test/java/mockito/Book.java | 3816febcfd1cf44107c490b75e409088dd546e83 | [] | no_license | rganga189/CSD_RameshGanga | https://github.com/rganga189/CSD_RameshGanga | d6b601b667289a582740ba7929aa6fcdce2f59c8 | cde0a2cee741c89e66c93a733d25e69a22134818 | refs/heads/master | 2021-01-12T09:30:03.994000 | 2016-12-11T06:23:00 | 2016-12-11T06:23:00 | 76,169,170 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mockito;
import java.util.List;
public class Book {
private String title;
private String author;
private String publication;
private Integer yearOfPublication;
private Integer numberOfPages;
public Book(String title,
String author,
String publication,
Integer yearOfPublication,
Integer numberOfPages){
this.title = title;
this.author = author;
this.publication = publication;
this.yearOfPublication = yearOfPublication;
this.numberOfPages = numberOfPages;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublication() {
return publication;
}
public Integer getYearOfPublication() {
return yearOfPublication;
}
public Integer getNumberOfPages() {
return numberOfPages;
}
}
| UTF-8 | Java | 935 | java | Book.java | Java | [] | null | [] | package mockito;
import java.util.List;
public class Book {
private String title;
private String author;
private String publication;
private Integer yearOfPublication;
private Integer numberOfPages;
public Book(String title,
String author,
String publication,
Integer yearOfPublication,
Integer numberOfPages){
this.title = title;
this.author = author;
this.publication = publication;
this.yearOfPublication = yearOfPublication;
this.numberOfPages = numberOfPages;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublication() {
return publication;
}
public Integer getYearOfPublication() {
return yearOfPublication;
}
public Integer getNumberOfPages() {
return numberOfPages;
}
}
| 935 | 0.636364 | 0.636364 | 47 | 17.893618 | 14.955585 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446809 | false | false | 4 |
8a2cf865a3e4a7836da9f9c2eef12b90f55ed65c | 26,336,739,471,680 | 47bee068ddb9dacfff94d08341f604ebe97f9fef | /src/main/java/com/smlsnnshn/Lessons/day44_OOP_review_project/IScreenSharable.java | 36c823533cc69181701f691e290f694aa8f31e4f | [] | no_license | ismailsinansahin/JavaLessons | https://github.com/ismailsinansahin/JavaLessons | 55686229d946390a52383f5d80e1053f411286e7 | 768cb63e22462e7c2eef709102df5d19d9c98568 | refs/heads/master | 2023-07-18T23:10:31.302000 | 2021-09-14T20:56:35 | 2021-09-14T20:56:35 | 360,487,169 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smlsnnshn.Lessons.day44_OOP_review_project;
public interface IScreenSharable {
void shareScreen();
}
| UTF-8 | Java | 118 | java | IScreenSharable.java | Java | [] | null | [] | package com.smlsnnshn.Lessons.day44_OOP_review_project;
public interface IScreenSharable {
void shareScreen();
}
| 118 | 0.779661 | 0.762712 | 7 | 15.857142 | 20.081467 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 4 |
e5dfa62dc19d6f0dedac47b9cf34983bb73c1b0f | 17,918,603,562,935 | bda15181fad031db7151f45547f3646260430770 | /SERVICES/appservice/src/main/java/com/cloud/paas/appservice/util/yaml/pod/PodStatus.java | c165a445eab3ebfead7f1dd0d23e48717a8165f7 | [
"MIT"
] | permissive | jybjobs/IPaas | https://github.com/jybjobs/IPaas | 05c63969db57f505388360e887922145946bfd84 | 932a8708edc504ecc312d50005d01e4ec5d4809f | refs/heads/master | 2020-03-19T18:14:47.353000 | 2018-06-18T13:29:54 | 2018-06-18T13:29:54 | 136,800,979 | 2 | 1 | null | false | 2018-06-11T09:44:56 | 2018-06-10T10:56:23 | 2018-06-10T14:20:22 | 2018-06-11T09:44:55 | 0 | 1 | 0 | 0 | null | false | null | package com.cloud.paas.appservice.util.yaml.pod;
/**
* @Author: srf
* @desc: PodStatus对象
* @Date: Created in 2018-04-15 11-50
* @Modified By:
*/
public class PodStatus {
private String hostIP;
private String podIP;
public String getHostIP() {
return hostIP;
}
public void setHostIP(String hostIP) {
this.hostIP = hostIP;
}
public String getPodIP() {
return podIP;
}
public void setPodIP(String podIP) {
this.podIP = podIP;
}
}
| UTF-8 | Java | 513 | java | PodStatus.java | Java | [
{
"context": "ud.paas.appservice.util.yaml.pod;\n\n/**\n * @Author: srf\n * @desc: PodStatus对象\n * @Date: Created in 2018-0",
"end": 69,
"score": 0.999655544757843,
"start": 66,
"tag": "USERNAME",
"value": "srf"
}
] | null | [] | package com.cloud.paas.appservice.util.yaml.pod;
/**
* @Author: srf
* @desc: PodStatus对象
* @Date: Created in 2018-04-15 11-50
* @Modified By:
*/
public class PodStatus {
private String hostIP;
private String podIP;
public String getHostIP() {
return hostIP;
}
public void setHostIP(String hostIP) {
this.hostIP = hostIP;
}
public String getPodIP() {
return podIP;
}
public void setPodIP(String podIP) {
this.podIP = podIP;
}
}
| 513 | 0.609037 | 0.585462 | 28 | 17.178572 | 14.697068 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
5124c5ba7232aa8df377d137625aebd31b6baa8d | 20,864,951,191,631 | 2fd9d77d529e9b90fd077d0aa5ed2889525129e3 | /DecompiledViberSrc/app/src/main/java/com/viber/voip/camera/c/a.java | 2cf167aedca72ba044cf0636ac0f3084358f3977 | [] | no_license | cga2351/code | https://github.com/cga2351/code | 703f5d49dc3be45eafc4521e931f8d9d270e8a92 | 4e35fb567d359c252c2feca1e21b3a2a386f2bdb | refs/heads/master | 2021-07-08T15:11:06.299000 | 2021-05-06T13:22:21 | 2021-05-06T13:22:21 | 60,314,071 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.viber.voip.camera.c;
import android.content.Context;
import android.graphics.Canvas;
import android.media.CamcorderProfile;
import android.net.Uri;
import android.util.Pair;
import android.view.MotionEvent;
import java.io.File;
import java.io.IOException;
public abstract interface a
{
public abstract String A();
public abstract String B();
public abstract String C();
public abstract boolean D();
public abstract boolean E();
public abstract boolean F();
public abstract boolean G();
public abstract long H();
public abstract String I();
public abstract long J();
public abstract boolean K();
public abstract String L();
public abstract String M();
public abstract int N();
public abstract long O();
public abstract float P();
public abstract void Q();
public abstract void R();
public abstract void S();
public abstract void T();
public abstract void U();
public abstract void V();
public abstract void W();
public abstract void X();
public abstract void Y();
public abstract void Z();
public abstract String a(boolean paramBoolean);
public abstract void a(float paramFloat);
public abstract void a(int paramInt);
public abstract void a(int paramInt1, int paramInt2);
public abstract void a(int paramInt, Uri paramUri, String paramString);
public abstract void a(long paramLong);
public abstract void a(Canvas paramCanvas);
public abstract void a(CamcorderProfile paramCamcorderProfile);
public abstract void a(MotionEvent paramMotionEvent);
public abstract void a(String paramString);
public abstract void a(String paramString, boolean paramBoolean);
public abstract boolean a(byte[] paramArrayOfByte);
public abstract void aa();
public abstract void ab();
public abstract void ac();
public abstract void ad();
public abstract void ae();
public abstract Context b();
public abstract void b(int paramInt);
public abstract void b(int paramInt1, int paramInt2);
public abstract void b(long paramLong);
public abstract void b(CamcorderProfile paramCamcorderProfile);
public abstract void b(String paramString);
public abstract void b(boolean paramBoolean);
public abstract int c();
public abstract void c(int paramInt);
public abstract void c(int paramInt1, int paramInt2);
public abstract void c(String paramString);
public abstract void c(boolean paramBoolean);
public abstract File d()
throws IOException;
public abstract void d(int paramInt);
public abstract void d(String paramString);
public abstract void d(boolean paramBoolean);
public abstract Uri e()
throws IOException;
public abstract void e(String paramString);
public abstract Uri f()
throws IOException;
public abstract void f(String paramString);
public abstract int g();
public abstract String h();
public abstract boolean i();
public abstract String j();
public abstract String k();
public abstract String l();
public abstract String m();
public abstract int n();
public abstract Pair<Integer, Integer> o();
public abstract int p();
public abstract boolean q();
public abstract String r();
public abstract boolean s();
public abstract boolean t();
public abstract String u();
public abstract String v();
public abstract long w();
public abstract long x();
public abstract int y();
public abstract boolean z();
}
/* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_3_dex2jar.jar
* Qualified Name: com.viber.voip.camera.c.a
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 3,816 | java | a.java | Java | [] | null | [] | package com.viber.voip.camera.c;
import android.content.Context;
import android.graphics.Canvas;
import android.media.CamcorderProfile;
import android.net.Uri;
import android.util.Pair;
import android.view.MotionEvent;
import java.io.File;
import java.io.IOException;
public abstract interface a
{
public abstract String A();
public abstract String B();
public abstract String C();
public abstract boolean D();
public abstract boolean E();
public abstract boolean F();
public abstract boolean G();
public abstract long H();
public abstract String I();
public abstract long J();
public abstract boolean K();
public abstract String L();
public abstract String M();
public abstract int N();
public abstract long O();
public abstract float P();
public abstract void Q();
public abstract void R();
public abstract void S();
public abstract void T();
public abstract void U();
public abstract void V();
public abstract void W();
public abstract void X();
public abstract void Y();
public abstract void Z();
public abstract String a(boolean paramBoolean);
public abstract void a(float paramFloat);
public abstract void a(int paramInt);
public abstract void a(int paramInt1, int paramInt2);
public abstract void a(int paramInt, Uri paramUri, String paramString);
public abstract void a(long paramLong);
public abstract void a(Canvas paramCanvas);
public abstract void a(CamcorderProfile paramCamcorderProfile);
public abstract void a(MotionEvent paramMotionEvent);
public abstract void a(String paramString);
public abstract void a(String paramString, boolean paramBoolean);
public abstract boolean a(byte[] paramArrayOfByte);
public abstract void aa();
public abstract void ab();
public abstract void ac();
public abstract void ad();
public abstract void ae();
public abstract Context b();
public abstract void b(int paramInt);
public abstract void b(int paramInt1, int paramInt2);
public abstract void b(long paramLong);
public abstract void b(CamcorderProfile paramCamcorderProfile);
public abstract void b(String paramString);
public abstract void b(boolean paramBoolean);
public abstract int c();
public abstract void c(int paramInt);
public abstract void c(int paramInt1, int paramInt2);
public abstract void c(String paramString);
public abstract void c(boolean paramBoolean);
public abstract File d()
throws IOException;
public abstract void d(int paramInt);
public abstract void d(String paramString);
public abstract void d(boolean paramBoolean);
public abstract Uri e()
throws IOException;
public abstract void e(String paramString);
public abstract Uri f()
throws IOException;
public abstract void f(String paramString);
public abstract int g();
public abstract String h();
public abstract boolean i();
public abstract String j();
public abstract String k();
public abstract String l();
public abstract String m();
public abstract int n();
public abstract Pair<Integer, Integer> o();
public abstract int p();
public abstract boolean q();
public abstract String r();
public abstract boolean s();
public abstract boolean t();
public abstract String u();
public abstract String v();
public abstract long w();
public abstract long x();
public abstract int y();
public abstract boolean z();
}
/* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_3_dex2jar.jar
* Qualified Name: com.viber.voip.camera.c.a
* JD-Core Version: 0.6.2
*/ | 3,816 | 0.684224 | 0.679245 | 187 | 18.417112 | 19.530241 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 4 |
2a20d32187e50160923f525eb6fc6ebb80757823 | 24,790,551,257,689 | a88740d44cbd2d558bd9453b0d1093def0f51f5a | /src/VikasAssignments/Question1.java | 1fb9559f1a4c7a8733d0ba88e0f0083248bf056c | [] | no_license | jcritch/MyGitCode | https://github.com/jcritch/MyGitCode | 3d872531b2a334a9b049732b1a0f47fcbdf0b3fc | 164e5ae4a7aaeef288834025da8e6fb749bf4963 | refs/heads/master | 2020-06-20T18:43:38.771000 | 2019-07-17T11:48:20 | 2019-07-17T11:48:20 | 197,211,466 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package VikasAssignments;
public class Question1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Write a program to separate alphabets and numbers form the given String
String s[] = new String[] {"a,1,b,2,c,d,3,4,e"};
String letters = s[];
}
}
| UTF-8 | Java | 296 | java | Question1.java | Java | [] | null | [] | package VikasAssignments;
public class Question1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Write a program to separate alphabets and numbers form the given String
String s[] = new String[] {"a,1,b,2,c,d,3,4,e"};
String letters = s[];
}
}
| 296 | 0.672297 | 0.655405 | 15 | 18.733334 | 22.481005 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 4 |
e4c8b6509004e019dca456396fab69603b601cff | 25,898,652,818,947 | cd2cfee90819afff245dd6f130412f398e4dbdc5 | /MyForm/src/MyForm.java | 32b8386527f3a105d67195b4d7e96e4ba0eb6957 | [] | no_license | JMT2003/Mat2GGitDemo2 | https://github.com/JMT2003/Mat2GGitDemo2 | 67ed85ba7997edb91e269f481c7ef7261725f3f6 | 5b39699eccf549a315500615b6f9457fad92063e | refs/heads/master | 2021-01-17T17:40:54.142000 | 2017-03-06T23:19:49 | 2017-03-06T23:19:49 | 84,130,829 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JSlider;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class MyForm {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyForm window = new MyForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
JComboBox <String>comboBox;
JComboBox <String>comboBox_1;
JRadioButton rb1;
JRadioButton rb2;
JRadioButton rb3;
ButtonGroup radioGroup;
JCheckBox chckbxNewCheckBox;
JSlider slider;
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 493, 451);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
comboBox = new JComboBox<>();
String[][] Cities= {{"Detroit","Dearborn","Royal Oak"},{"Milwaukee","Adams","Loyal"},{"Chicago","Urbana", "Washington"}};
comboBox.setBounds(65, 84, 82, 22);
frame.getContentPane().add(comboBox);
comboBox_1 = new JComboBox<>();
comboBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int index = comboBox.getSelectedIndex();
comboBox_1.removeAllItems();
for(int j=0;j<Cities[index].length;j++)
{
comboBox_1.addItem(Cities[index][j]);
}
}
});
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"MI\t", "WI", "IL"}));
comboBox_1.setBounds(65, 49, 82, 22);
frame.getContentPane().add(comboBox_1);
JLabel lblState = new JLabel("State:");
lblState.setBounds(10, 49, 56, 16);
frame.getContentPane().add(lblState);
JLabel lblCity = new JLabel("City:");
lblCity.setBounds(10, 81, 56, 16);
frame.getContentPane().add(lblCity);
JPanel panel = new JPanel();
panel.setBounds(336, 26, 127, 114);
frame.getContentPane().add(panel);
panel.setLayout(null);
rb1 = new JRadioButton("Visa");
rb1.setBounds(17, 9, 93, 25);
panel.add(rb1);
rb2 = new JRadioButton("Mastercard");
rb2.setBounds(17, 39, 93, 25);
panel.add(rb2);
rb3 = new JRadioButton("PayPal");
rb3.setBounds(17, 65, 93, 25);
panel.add(rb3);
radioGroup = new ButtonGroup();
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
JButton btnShowSelected = new JButton("Show Selected");
btnShowSelected.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rb1.isSelected())
JOptionPane.showMessageDialog(null, "Visa");
if (rb2.isSelected())
JOptionPane.showMessageDialog(null, "Mastercard");
if (rb3.isSelected())
JOptionPane.showMessageDialog(null, "PayPal");
}
});
btnShowSelected.setBounds(336, 153, 127, 25);
frame.getContentPane().add(btnShowSelected);
chckbxNewCheckBox = new JCheckBox("New check box");
chckbxNewCheckBox.setBounds(67, 153, 113, 25);
frame.getContentPane().add(chckbxNewCheckBox);
slider = new JSlider();
slider.setPaintLabels(true);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setBounds(45, 214, 226, 60);
frame.getContentPane().add(slider);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 119, 26);
frame.getContentPane().add(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNewMenuItem = new JMenuItem("New");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You Clicked On New!");
}
});
mnFile.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Close");
mnFile.add(mntmNewMenuItem_1);
}
}
| UTF-8 | Java | 4,334 | java | MyForm.java | Java | [] | null | [] | import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JSlider;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class MyForm {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyForm window = new MyForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
JComboBox <String>comboBox;
JComboBox <String>comboBox_1;
JRadioButton rb1;
JRadioButton rb2;
JRadioButton rb3;
ButtonGroup radioGroup;
JCheckBox chckbxNewCheckBox;
JSlider slider;
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 493, 451);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
comboBox = new JComboBox<>();
String[][] Cities= {{"Detroit","Dearborn","Royal Oak"},{"Milwaukee","Adams","Loyal"},{"Chicago","Urbana", "Washington"}};
comboBox.setBounds(65, 84, 82, 22);
frame.getContentPane().add(comboBox);
comboBox_1 = new JComboBox<>();
comboBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int index = comboBox.getSelectedIndex();
comboBox_1.removeAllItems();
for(int j=0;j<Cities[index].length;j++)
{
comboBox_1.addItem(Cities[index][j]);
}
}
});
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"MI\t", "WI", "IL"}));
comboBox_1.setBounds(65, 49, 82, 22);
frame.getContentPane().add(comboBox_1);
JLabel lblState = new JLabel("State:");
lblState.setBounds(10, 49, 56, 16);
frame.getContentPane().add(lblState);
JLabel lblCity = new JLabel("City:");
lblCity.setBounds(10, 81, 56, 16);
frame.getContentPane().add(lblCity);
JPanel panel = new JPanel();
panel.setBounds(336, 26, 127, 114);
frame.getContentPane().add(panel);
panel.setLayout(null);
rb1 = new JRadioButton("Visa");
rb1.setBounds(17, 9, 93, 25);
panel.add(rb1);
rb2 = new JRadioButton("Mastercard");
rb2.setBounds(17, 39, 93, 25);
panel.add(rb2);
rb3 = new JRadioButton("PayPal");
rb3.setBounds(17, 65, 93, 25);
panel.add(rb3);
radioGroup = new ButtonGroup();
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
JButton btnShowSelected = new JButton("Show Selected");
btnShowSelected.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (rb1.isSelected())
JOptionPane.showMessageDialog(null, "Visa");
if (rb2.isSelected())
JOptionPane.showMessageDialog(null, "Mastercard");
if (rb3.isSelected())
JOptionPane.showMessageDialog(null, "PayPal");
}
});
btnShowSelected.setBounds(336, 153, 127, 25);
frame.getContentPane().add(btnShowSelected);
chckbxNewCheckBox = new JCheckBox("New check box");
chckbxNewCheckBox.setBounds(67, 153, 113, 25);
frame.getContentPane().add(chckbxNewCheckBox);
slider = new JSlider();
slider.setPaintLabels(true);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setBounds(45, 214, 226, 60);
frame.getContentPane().add(slider);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 119, 26);
frame.getContentPane().add(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNewMenuItem = new JMenuItem("New");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You Clicked On New!");
}
});
mnFile.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Close");
mnFile.add(mntmNewMenuItem_1);
}
}
| 4,334 | 0.687125 | 0.652976 | 172 | 24.197674 | 19.292919 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.843023 | false | false | 4 |
c61fe0527d6949bb5bbbf44c56e51a8917d53af5 | 11,948,599,021,073 | a9dabf5127dabb8e97d5bf96eb2df23f1c242115 | /espresso/web/java/androidx/test/espresso/web/bridge/AndroidJavaScriptBridgeInstaller.java | 46436f92294f8824788c9f59199744eb20336269 | [
"Apache-2.0"
] | permissive | android/android-test | https://github.com/android/android-test | 0e0af555ab54a8eb58693edc5cf4cb2c486ba12f | 698e592fbd00e554d7b0b2b824151c6146097b15 | refs/heads/main | 2023-08-18T11:46:39.969000 | 2023-08-17T20:27:37 | 2023-08-17T20:28:13 | 41,148,494 | 981 | 294 | Apache-2.0 | false | 2023-09-12T20:13:29 | 2015-08-21T09:47:39 | 2023-09-08T17:00:49 | 2023-09-12T20:13:25 | 75,604 | 1,106 | 312 | 300 | Java | false | false | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 androidx.test.espresso.web.bridge;
import static androidx.test.internal.util.Checks.checkNotNull;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* {@link JavaScriptBridgeInstaller} for aosp-browser based WebViews (default on API level 18 and
* lower).
*/
final class AndroidJavaScriptBridgeInstaller {
private static final JavaScriptBoundBridge boundBridge = new JavaScriptBoundBridge();
private static final String WEB_CORE_CLAZZ = "android.webkit.WebViewCore";
private static final String WEB_CORE_HANDLER = "sWebCoreHandler";
private static final String JAVASCRIPT_INTERFACES = "mJavascriptInterfaces";
private static final String CALLBACK_PROXY_CLAZZ = "android.webkit.CallbackProxy";
private static final String SET_WEB_CHROME_CLIENT_METHOD = "setWebChromeClient";
private static final String CALLBACK_PROXY_FIELD = "mCallbackProxy";
public JavaScriptBoundBridge install()
throws JavaScriptBridgeInstallException {
try {
Class<?> webCoreClazz = Class.forName(WEB_CORE_CLAZZ);
Field webCoreHandlerField = webCoreClazz.getDeclaredField(WEB_CORE_HANDLER);
Field javascriptInterfacesField = webCoreClazz.getDeclaredField(JAVASCRIPT_INTERFACES);
Field callbackProxyField = null;
Method setWebChromeClientMethod = null;
if (Build.VERSION.SDK_INT < 13) {
callbackProxyField = webCoreClazz.getDeclaredField(CALLBACK_PROXY_FIELD);
Class<?> callbackProxyClazz = Class.forName(CALLBACK_PROXY_CLAZZ);
setWebChromeClientMethod = callbackProxyClazz.getDeclaredMethod(
SET_WEB_CHROME_CLIENT_METHOD, WebChromeClient.class);
callbackProxyField.setAccessible(true);
setWebChromeClientMethod.setAccessible(true);
}
webCoreHandlerField.setAccessible(true);
javascriptInterfacesField.setAccessible(true);
Handler webCoreHandler = null;
synchronized (webCoreClazz) {
webCoreHandler = (Handler) webCoreHandlerField.get(null);
if (null != webCoreHandler) {
Log.w(JavaScriptBridge.TAG, "Initializing late - some webviews may be unbridged.");
}
}
if (null == webCoreHandler) {
// TODO(b/227119444): should the constructed instance be used?
WebView unused = new WebView(getInstrumentation().getTargetContext());
while (null == webCoreHandler) {
synchronized (webCoreClazz) {
webCoreHandler = (Handler) webCoreHandlerField.get(null);
}
}
}
Handler instrumentedHandler = new WebCoreHandlerSpy(webCoreHandler,
javascriptInterfacesField, callbackProxyField, setWebChromeClientMethod);
synchronized (webCoreClazz) {
webCoreHandlerField.set(null, instrumentedHandler);
}
} catch (ClassNotFoundException cnfe) {
throw new JavaScriptBridgeInstallException(cnfe);
} catch (NoSuchFieldException nsfe) {
throw new JavaScriptBridgeInstallException(nsfe);
} catch (NoSuchMethodException nsme) {
throw new JavaScriptBridgeInstallException(nsme);
} catch (IllegalAccessException iae) {
throw new JavaScriptBridgeInstallException(iae);
}
Log.i(JavaScriptBridge.TAG, "Initialized web view bridging for android WebView.");
return boundBridge;
}
private static final class WebCoreHandlerSpy extends Handler {
private final Handler realHandler;
private final Field javascriptInterfacesField;
private final Field callbackProxyField;
private final Method setWebViewClientMethod;
private WebCoreHandlerSpy(Handler realHandler, Field javascriptInterfacesField,
Field callbackProxyField, Method setWebViewClientMethod) {
super(realHandler.getLooper());
this.realHandler = checkNotNull(realHandler);
this.javascriptInterfacesField = checkNotNull(javascriptInterfacesField);
// nullables.
this.callbackProxyField = callbackProxyField;
this.setWebViewClientMethod = setWebViewClientMethod;
}
// Override this method to detect when new WebViewCore's are being initialized
// We do the injection of the JavaScriptInterfaces field here to ensure that
// subwindows get our javascript bridge variable.
@Override
public boolean sendMessageAtTime(Message message, long delayMillis) {
// 0 is the initialize message.
if (message.what == 0) {
// and it's sent on main.
try {
@SuppressWarnings("unchecked")
Map<Object, Object> jsInterfaces =
(Map<Object, Object>) javascriptInterfacesField.get(message.obj);
if (null == jsInterfaces) {
jsInterfaces = new HashMap<>();
javascriptInterfacesField.set(message.obj, jsInterfaces);
}
jsInterfaces.put(JavaScriptBridge.JS_BRIDGE_NAME, boundBridge);
if (Build.VERSION.SDK_INT < 13) {
// progress is not reported unless a webchromeclient is installed on the webview.
// Knowing progress helps write code that doesn't run while we're reloading.
// since this code is running in the constructor of WebView - lets install a
// a webchromeclient immedately. It doesn't need to do anything - just its presence
// will propagate progress.
Object callbackProxy = callbackProxyField.get(message.obj);
setWebViewClientMethod.invoke(callbackProxy, new WebChromeClient());
}
} catch (IllegalAccessException iae) {
Log.e(JavaScriptBridge.TAG, "Couldn't initialize js bridge in webview!", iae);
} catch (InvocationTargetException ite) {
Log.e(JavaScriptBridge.TAG, "Couldn't initialize js bridge in webview!", ite);
}
}
return super.sendMessageAtTime(message, delayMillis);
}
@Override
public void handleMessage(Message message) {
realHandler.handleMessage(message);
}
}
}
| UTF-8 | Java | 6,909 | java | AndroidJavaScriptBridgeInstaller.java | Java | [] | null | [] | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 androidx.test.espresso.web.bridge;
import static androidx.test.internal.util.Checks.checkNotNull;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* {@link JavaScriptBridgeInstaller} for aosp-browser based WebViews (default on API level 18 and
* lower).
*/
final class AndroidJavaScriptBridgeInstaller {
private static final JavaScriptBoundBridge boundBridge = new JavaScriptBoundBridge();
private static final String WEB_CORE_CLAZZ = "android.webkit.WebViewCore";
private static final String WEB_CORE_HANDLER = "sWebCoreHandler";
private static final String JAVASCRIPT_INTERFACES = "mJavascriptInterfaces";
private static final String CALLBACK_PROXY_CLAZZ = "android.webkit.CallbackProxy";
private static final String SET_WEB_CHROME_CLIENT_METHOD = "setWebChromeClient";
private static final String CALLBACK_PROXY_FIELD = "mCallbackProxy";
public JavaScriptBoundBridge install()
throws JavaScriptBridgeInstallException {
try {
Class<?> webCoreClazz = Class.forName(WEB_CORE_CLAZZ);
Field webCoreHandlerField = webCoreClazz.getDeclaredField(WEB_CORE_HANDLER);
Field javascriptInterfacesField = webCoreClazz.getDeclaredField(JAVASCRIPT_INTERFACES);
Field callbackProxyField = null;
Method setWebChromeClientMethod = null;
if (Build.VERSION.SDK_INT < 13) {
callbackProxyField = webCoreClazz.getDeclaredField(CALLBACK_PROXY_FIELD);
Class<?> callbackProxyClazz = Class.forName(CALLBACK_PROXY_CLAZZ);
setWebChromeClientMethod = callbackProxyClazz.getDeclaredMethod(
SET_WEB_CHROME_CLIENT_METHOD, WebChromeClient.class);
callbackProxyField.setAccessible(true);
setWebChromeClientMethod.setAccessible(true);
}
webCoreHandlerField.setAccessible(true);
javascriptInterfacesField.setAccessible(true);
Handler webCoreHandler = null;
synchronized (webCoreClazz) {
webCoreHandler = (Handler) webCoreHandlerField.get(null);
if (null != webCoreHandler) {
Log.w(JavaScriptBridge.TAG, "Initializing late - some webviews may be unbridged.");
}
}
if (null == webCoreHandler) {
// TODO(b/227119444): should the constructed instance be used?
WebView unused = new WebView(getInstrumentation().getTargetContext());
while (null == webCoreHandler) {
synchronized (webCoreClazz) {
webCoreHandler = (Handler) webCoreHandlerField.get(null);
}
}
}
Handler instrumentedHandler = new WebCoreHandlerSpy(webCoreHandler,
javascriptInterfacesField, callbackProxyField, setWebChromeClientMethod);
synchronized (webCoreClazz) {
webCoreHandlerField.set(null, instrumentedHandler);
}
} catch (ClassNotFoundException cnfe) {
throw new JavaScriptBridgeInstallException(cnfe);
} catch (NoSuchFieldException nsfe) {
throw new JavaScriptBridgeInstallException(nsfe);
} catch (NoSuchMethodException nsme) {
throw new JavaScriptBridgeInstallException(nsme);
} catch (IllegalAccessException iae) {
throw new JavaScriptBridgeInstallException(iae);
}
Log.i(JavaScriptBridge.TAG, "Initialized web view bridging for android WebView.");
return boundBridge;
}
private static final class WebCoreHandlerSpy extends Handler {
private final Handler realHandler;
private final Field javascriptInterfacesField;
private final Field callbackProxyField;
private final Method setWebViewClientMethod;
private WebCoreHandlerSpy(Handler realHandler, Field javascriptInterfacesField,
Field callbackProxyField, Method setWebViewClientMethod) {
super(realHandler.getLooper());
this.realHandler = checkNotNull(realHandler);
this.javascriptInterfacesField = checkNotNull(javascriptInterfacesField);
// nullables.
this.callbackProxyField = callbackProxyField;
this.setWebViewClientMethod = setWebViewClientMethod;
}
// Override this method to detect when new WebViewCore's are being initialized
// We do the injection of the JavaScriptInterfaces field here to ensure that
// subwindows get our javascript bridge variable.
@Override
public boolean sendMessageAtTime(Message message, long delayMillis) {
// 0 is the initialize message.
if (message.what == 0) {
// and it's sent on main.
try {
@SuppressWarnings("unchecked")
Map<Object, Object> jsInterfaces =
(Map<Object, Object>) javascriptInterfacesField.get(message.obj);
if (null == jsInterfaces) {
jsInterfaces = new HashMap<>();
javascriptInterfacesField.set(message.obj, jsInterfaces);
}
jsInterfaces.put(JavaScriptBridge.JS_BRIDGE_NAME, boundBridge);
if (Build.VERSION.SDK_INT < 13) {
// progress is not reported unless a webchromeclient is installed on the webview.
// Knowing progress helps write code that doesn't run while we're reloading.
// since this code is running in the constructor of WebView - lets install a
// a webchromeclient immedately. It doesn't need to do anything - just its presence
// will propagate progress.
Object callbackProxy = callbackProxyField.get(message.obj);
setWebViewClientMethod.invoke(callbackProxy, new WebChromeClient());
}
} catch (IllegalAccessException iae) {
Log.e(JavaScriptBridge.TAG, "Couldn't initialize js bridge in webview!", iae);
} catch (InvocationTargetException ite) {
Log.e(JavaScriptBridge.TAG, "Couldn't initialize js bridge in webview!", ite);
}
}
return super.sendMessageAtTime(message, delayMillis);
}
@Override
public void handleMessage(Message message) {
realHandler.handleMessage(message);
}
}
}
| 6,909 | 0.71747 | 0.713852 | 160 | 42.174999 | 28.993221 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.56875 | false | false | 4 |
8d500949ee56e7b390673e8fd82349457ac6a80d | 8,022,998,968,651 | fc4f56b1793efa818670a7aa63ab37b3c2c30b62 | /Flatten_2D_Vector/solution_using_iterator.java | a20bc840a0fc7edac9aa7b4c1cfd4965fd0422b4 | [] | no_license | liang90925/brainwork | https://github.com/liang90925/brainwork | 63391d8a4a7db2dfbc30ad000da3dd647a14e529 | fdf33c7f0f2968951cfccce2d315d3480cf685f2 | refs/heads/master | 2021-07-05T17:54:38.416000 | 2020-08-18T22:29:25 | 2020-08-18T22:29:25 | 63,660,018 | 0 | 0 | null | false | 2020-05-30T23:15:36 | 2016-07-19T04:18:23 | 2020-05-03T23:39:16 | 2020-05-30T23:15:35 | 413 | 0 | 0 | 0 | Java | false | false | public class Vector2D implements Iterator<Integer> {
private Iterator<Integer> intItr = null;
private Iterator<List<Integer>> intListItr = null;
public Vector2D(List<List<Integer>> vec2D) {
intListItr = vec2D.iterator();
// to check whether the input vec2D is an empty list;
if (intListItr.hasNext()) {
intItr = intListItr.next().iterator();
}
}
@Override
public Integer next() {
if (hasNext()) {
return intItr.next();
}
return -1;
}
@Override
public boolean hasNext() {
// check the empty input vec2D list first
if (intItr == null ) {
return false;
}
if (intItr.hasNext()) {
return true;
}
while (intListItr.hasNext()) {
intItr = intListItr.next().iterator();
if (intItr.hasNext()) {
return true;
}
}
return false;
}
public void remove() {
intItr.remove();
}
public static void main(String[] args) {
List<Integer> row0 = new ArrayList<>();
List<Integer> row01 = new ArrayList<>();
List<Integer> row1 = new ArrayList<>();
row1.add(1);
row1.add(2);
row1.add(3);
List<Integer> row2 = new ArrayList<>();
row2.add(4);
row2.add(5);
List<Integer> row21 = new ArrayList<>();
List<Integer> row3 = new ArrayList<>();
row3.add(6);
List<Integer> row4 = new ArrayList<>();
List<Integer> row5 = new ArrayList<>();
List<List<Integer>> vec2D = new ArrayList<>();
vec2D.add(row0);
vec2D.add(row01);
vec2D.add(row1);
vec2D.add(row2);
vec2D.add(row21);
vec2D.add(row3);
vec2D.add(row4);
vec2D.add(row5);
Vector2D v2d = new Vector2D(vec2D);
while (v2d.hasNext()) {
int result = v2d.next();
System.out.println(result);
v2d.remove();
}
}
}
| UTF-8 | Java | 1,793 | java | solution_using_iterator.java | Java | [] | null | [] | public class Vector2D implements Iterator<Integer> {
private Iterator<Integer> intItr = null;
private Iterator<List<Integer>> intListItr = null;
public Vector2D(List<List<Integer>> vec2D) {
intListItr = vec2D.iterator();
// to check whether the input vec2D is an empty list;
if (intListItr.hasNext()) {
intItr = intListItr.next().iterator();
}
}
@Override
public Integer next() {
if (hasNext()) {
return intItr.next();
}
return -1;
}
@Override
public boolean hasNext() {
// check the empty input vec2D list first
if (intItr == null ) {
return false;
}
if (intItr.hasNext()) {
return true;
}
while (intListItr.hasNext()) {
intItr = intListItr.next().iterator();
if (intItr.hasNext()) {
return true;
}
}
return false;
}
public void remove() {
intItr.remove();
}
public static void main(String[] args) {
List<Integer> row0 = new ArrayList<>();
List<Integer> row01 = new ArrayList<>();
List<Integer> row1 = new ArrayList<>();
row1.add(1);
row1.add(2);
row1.add(3);
List<Integer> row2 = new ArrayList<>();
row2.add(4);
row2.add(5);
List<Integer> row21 = new ArrayList<>();
List<Integer> row3 = new ArrayList<>();
row3.add(6);
List<Integer> row4 = new ArrayList<>();
List<Integer> row5 = new ArrayList<>();
List<List<Integer>> vec2D = new ArrayList<>();
vec2D.add(row0);
vec2D.add(row01);
vec2D.add(row1);
vec2D.add(row2);
vec2D.add(row21);
vec2D.add(row3);
vec2D.add(row4);
vec2D.add(row5);
Vector2D v2d = new Vector2D(vec2D);
while (v2d.hasNext()) {
int result = v2d.next();
System.out.println(result);
v2d.remove();
}
}
}
| 1,793 | 0.587842 | 0.557167 | 77 | 22.285715 | 16.120373 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.519481 | false | false | 4 |
01d3bbcd04c721481b343e89fc614bdc1658493e | 26,594,437,551,883 | de43c168422aed393826895aa5d491668cdd3e6f | /src/main/java/de/jservice/kidsgard/data/Status.java | bba9d05f95684f316562e63fe069b8232bef18d0 | [] | no_license | amreng2107/JavaUSB_Mobile | https://github.com/amreng2107/JavaUSB_Mobile | 442f8cc8336e64610f4de85e8bf4f7f151a8b9d8 | 67098ea65eaabc66eb8760bff9fc7137049a280b | refs/heads/master | 2020-04-27T16:44:35.695000 | 2019-03-08T08:13:15 | 2019-03-08T08:13:15 | 174,491,993 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.jservice.kidsgard.data;
/**
*
* @author AmrReda
*/
public enum Status {
ONLINE,OFFLINE;
}
| UTF-8 | Java | 114 | java | Status.java | Java | [
{
"context": "kage de.jservice.kidsgard.data;\n\n/**\n *\n * @author AmrReda\n */\npublic enum Status {\n ONLINE,OFFLINE;\n ",
"end": 61,
"score": 0.9334692358970642,
"start": 54,
"tag": "NAME",
"value": "AmrReda"
}
] | null | [] | package de.jservice.kidsgard.data;
/**
*
* @author AmrReda
*/
public enum Status {
ONLINE,OFFLINE;
}
| 114 | 0.622807 | 0.622807 | 10 | 10.4 | 10.947145 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 4 |
f78d1c3d57e340cbdfdd094771ecc33265b2cc00 | 34,522,947,126,497 | ee8e2d4d85eaec3b8b2cc0bfd40711f2328d683d | /cloudstorage/src/test/java/com/udacity/jwdnd/course1/cloudstorage/NotesPage.java | 7d58124be322ff7a49fe119e864d9348cc248028 | [] | no_license | Bo-R1sR/udacity-nd-jwd-lesson01-spring-boot-basics | https://github.com/Bo-R1sR/udacity-nd-jwd-lesson01-spring-boot-basics | de02e28ae7e917f9fa00184a6d4745aff03fdb61 | bcb70f401cf9983570d4650bd76164c33ca448b4 | refs/heads/master | 2023-01-02T08:35:22.098000 | 2020-10-07T15:19:24 | 2020-10-07T15:19:24 | 296,359,121 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.udacity.jwdnd.course1.cloudstorage;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class NotesPage {
private final JavascriptExecutor js;
@FindBy(id = "nav-notes-tab")
private WebElement notesTab;
@FindBy(id = "addNewNote")
private WebElement addNoteButton;
@FindBy(id = "note-title")
private WebElement noteTitleField;
@FindBy(id = "note-description")
private WebElement noteDescriptionField;
@FindBy(id = "noteSubmitModal")
private WebElement submitNoteModalButton;
@FindBy(id = "successMsg")
private WebElement successMsg;
@FindBy(className = "notetitle")
private WebElement noteTitle;
@FindBy(className = "notedescription")
private WebElement noteDescription;
@FindBy(css = "#userTable .btn-success")
private WebElement editButton;
@FindBy(css = "#userTable .btn-danger")
private WebElement deleteButton;
@FindBy(id = "returnHome")
private WebElement returnHome;
public NotesPage(WebDriver webDriver) {
PageFactory.initElements(webDriver, this);
js = (JavascriptExecutor) webDriver;
}
public void insertNewNote(String noteTitle, String noteDescription) {
js.executeScript("arguments[0].click();", notesTab);
js.executeScript("arguments[0].click();", addNoteButton);
js.executeScript("arguments[0].value='" + noteTitle + "';", noteTitleField);
js.executeScript("arguments[0].value='" + noteDescription + "';", noteDescriptionField);
js.executeScript("arguments[0].click();", submitNoteModalButton);
}
public void editNote(String noteTitle, String noteDescription) {
js.executeScript("arguments[0].click();", notesTab);
js.executeScript("arguments[0].click();", editButton);
js.executeScript("arguments[0].value='" + noteTitle + "';", noteTitleField);
js.executeScript("arguments[0].value='" + noteDescription + "';", noteDescriptionField);
js.executeScript("arguments[0].click();", submitNoteModalButton);
}
public void deleteNote() {
js.executeScript("arguments[0].click();", notesTab);
js.executeScript("arguments[0].click();", deleteButton);
}
public String returnSuccessMsg() {
return successMsg.getText();
}
public String getNoteTitle() {
js.executeScript("arguments[0].click();", notesTab);
return noteTitle.getText();
}
public String getNoteDescription() {
js.executeScript("arguments[0].click();", notesTab);
return noteDescription.getText();
}
public void returnHome() {
js.executeScript("arguments[0].click();", returnHome);
}
}
| UTF-8 | Java | 2,869 | java | NotesPage.java | Java | [] | null | [] | package com.udacity.jwdnd.course1.cloudstorage;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class NotesPage {
private final JavascriptExecutor js;
@FindBy(id = "nav-notes-tab")
private WebElement notesTab;
@FindBy(id = "addNewNote")
private WebElement addNoteButton;
@FindBy(id = "note-title")
private WebElement noteTitleField;
@FindBy(id = "note-description")
private WebElement noteDescriptionField;
@FindBy(id = "noteSubmitModal")
private WebElement submitNoteModalButton;
@FindBy(id = "successMsg")
private WebElement successMsg;
@FindBy(className = "notetitle")
private WebElement noteTitle;
@FindBy(className = "notedescription")
private WebElement noteDescription;
@FindBy(css = "#userTable .btn-success")
private WebElement editButton;
@FindBy(css = "#userTable .btn-danger")
private WebElement deleteButton;
@FindBy(id = "returnHome")
private WebElement returnHome;
public NotesPage(WebDriver webDriver) {
PageFactory.initElements(webDriver, this);
js = (JavascriptExecutor) webDriver;
}
public void insertNewNote(String noteTitle, String noteDescription) {
js.executeScript("arguments[0].click();", notesTab);
js.executeScript("arguments[0].click();", addNoteButton);
js.executeScript("arguments[0].value='" + noteTitle + "';", noteTitleField);
js.executeScript("arguments[0].value='" + noteDescription + "';", noteDescriptionField);
js.executeScript("arguments[0].click();", submitNoteModalButton);
}
public void editNote(String noteTitle, String noteDescription) {
js.executeScript("arguments[0].click();", notesTab);
js.executeScript("arguments[0].click();", editButton);
js.executeScript("arguments[0].value='" + noteTitle + "';", noteTitleField);
js.executeScript("arguments[0].value='" + noteDescription + "';", noteDescriptionField);
js.executeScript("arguments[0].click();", submitNoteModalButton);
}
public void deleteNote() {
js.executeScript("arguments[0].click();", notesTab);
js.executeScript("arguments[0].click();", deleteButton);
}
public String returnSuccessMsg() {
return successMsg.getText();
}
public String getNoteTitle() {
js.executeScript("arguments[0].click();", notesTab);
return noteTitle.getText();
}
public String getNoteDescription() {
js.executeScript("arguments[0].click();", notesTab);
return noteDescription.getText();
}
public void returnHome() {
js.executeScript("arguments[0].click();", returnHome);
}
}
| 2,869 | 0.679331 | 0.673754 | 91 | 30.527473 | 26.009441 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.78022 | false | false | 4 |
55d86f065cf1b8489c242dfa5ca47886b4adb837 | 27,865,747,883,412 | dbcd522941e804fa574af51fa58f99553b24c7ca | /library/src/main/java/com/example/sunxiaodong/library/base/listener/ViewportChangeListener.java | 8b722a19879f965c1571ee3e1b4c11e0da0e73e2 | [] | no_license | sunxiaodongme/EasyChart | https://github.com/sunxiaodongme/EasyChart | fbadb8521e024766687608fe78e17d8696e4fe4d | 4eac75810bb630da4f606cb07ced7c0d092af17c | refs/heads/master | 2021-01-17T07:29:27.306000 | 2016-06-28T08:57:32 | 2016-06-28T08:57:32 | 61,934,415 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.sunxiaodong.library.base.listener;
import com.example.sunxiaodong.library.base.model.Viewport;
/**
* 视窗改变回调
* Created by sunxiaodong on 16/6/27.
*/
public interface ViewportChangeListener {
void onViewportChanged(Viewport viewport);
}
| UTF-8 | Java | 278 | java | ViewportChangeListener.java | Java | [
{
"context": ".base.model.Viewport;\n\n/**\n * 视窗改变回调\n * Created by sunxiaodong on 16/6/27.\n */\npublic interface ViewportChangeLi",
"end": 156,
"score": 0.9996963739395142,
"start": 145,
"tag": "USERNAME",
"value": "sunxiaodong"
}
] | null | [] | package com.example.sunxiaodong.library.base.listener;
import com.example.sunxiaodong.library.base.model.Viewport;
/**
* 视窗改变回调
* Created by sunxiaodong on 16/6/27.
*/
public interface ViewportChangeListener {
void onViewportChanged(Viewport viewport);
}
| 278 | 0.770677 | 0.75188 | 13 | 19.461538 | 22.768452 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 4 |
a51f994faf66addf483c77281a33cc48d1e70c00 | 22,608,707,880,508 | 9a1c04c64071a4c8c55618f44175c75804b9b384 | /code/QuestionReport/src/main/java/com/cnedutech/controller/TestController.java | 79cc38954adb0d8efb6654c8ef61db72a99980c7 | [] | no_license | zlmone/QuestionReport | https://github.com/zlmone/QuestionReport | 8105913b868f5479b965b9555b2f1fcc501c7613 | c3cc90f318a493d16ef04f74c90dfc58273088a3 | refs/heads/master | 2022-11-15T10:00:37.798000 | 2020-01-13T02:30:51 | 2020-01-13T02:30:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cnedutech.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cnedutech.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Controller
public class TestController {
@Autowired
UserMapper userMapper;
@RequestMapping(value="test")
public String test() {
PageHelper.startPage(1, 10);
List<Map<String, Object>> user = userMapper.getUser();
PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(user);
System.err.println(pageInfo);
return "index";
}
}
| UTF-8 | Java | 743 | java | TestController.java | Java | [] | null | [] | package com.cnedutech.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cnedutech.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Controller
public class TestController {
@Autowired
UserMapper userMapper;
@RequestMapping(value="test")
public String test() {
PageHelper.startPage(1, 10);
List<Map<String, Object>> user = userMapper.getUser();
PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(user);
System.err.println(pageInfo);
return "index";
}
}
| 743 | 0.781965 | 0.777927 | 28 | 25.535715 | 22.102816 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 4 |
10c6f5c058b6d638de5335d60b438d1de3a52f23 | 14,946,486,223,001 | 631b1026173433cd3f1c0351b2958b05fa97412b | /src/com.standalone.jshell/com/standalone/jshell/JShellStandalone.java | 71b059357a7866bf1e98c716832575c9809f86bc | [
"MIT"
] | permissive | shathor/JShellStandalone | https://github.com/shathor/JShellStandalone | 41380f59dfea9b18aaba8549b71c48acded0f9b5 | 16de1e1710da640d5c2efd2346a1757a37c29d02 | refs/heads/master | 2023-05-26T13:07:21.242000 | 2023-05-21T14:08:05 | 2023-05-21T14:08:05 | 99,040,773 | 42 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.standalone.jshell;
public class JShellStandalone {
public static void main(String[] args) {
String javaRuntimeVersion = System.getProperty("java.runtime.version");
System.out.println(javaRuntimeVersion);
}
}
| UTF-8 | Java | 230 | java | JShellStandalone.java | Java | [] | null | [] | package com.standalone.jshell;
public class JShellStandalone {
public static void main(String[] args) {
String javaRuntimeVersion = System.getProperty("java.runtime.version");
System.out.println(javaRuntimeVersion);
}
}
| 230 | 0.765217 | 0.765217 | 10 | 22 | 23.91234 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
6be63182d23c2e670b750a01747f2b2161f5f013 | 14,946,486,224,671 | 3920d17adf2315b60bd106818f437a96ac902a08 | /src/dipali/ArthematicOperation.java | c65811a89325793a8e946ef2bcdd3fbefe1481b2 | [] | no_license | gaurav-4uk/JAVATechnoMar2021 | https://github.com/gaurav-4uk/JAVATechnoMar2021 | 882f4925f2a27f11698ef8a5a8c7b9b5e01a792b | 6bb08f38a6212bed883a746be8290c171b40e717 | refs/heads/main | 2023-05-16T22:32:43.176000 | 2021-06-05T17:16:49 | 2021-06-05T17:16:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dipali;
import java.util.Arrays;
public class ArthematicOperation {
int numbers[]=new int[50];
public void findEvenNo(int start , int end) {
int number;
int iCnt=0;
for (number=start;number<=end; number++) {
if(number%2==0) {
numbers[iCnt]=number;
iCnt=iCnt+1;
}
}
//to print values
System.out.println("Even numbers are: ");
int arraySize=numbers.length;
int cnt;
for(cnt=0;cnt<arraySize;cnt++) {
if(numbers[cnt]==0) {
}else {
System.out.println(numbers[cnt]);
}
}
}
public void numDivisiblefive(int start , int end) {
int number;
int no=5;
int iCnt=0;
Arrays.fill(numbers, 0);
for (number=start;number<=end; number++) {
if(number%no==0) {
numbers[iCnt]=number;
iCnt=iCnt+1;
}
}
//to print values
System.out.println("Divisible by 5, numbers are: ");
int arraySize=numbers.length;
int cnt;
for(cnt=0;cnt<arraySize;cnt++) {
if(numbers[cnt]==0) {
}else {
System.out.println(numbers[cnt]);
}
}
}
public void numDivByThreeAndFive(int start , int end) {
int number;
int no1=3;
int no2=5;
int iCnt=0;
Arrays.fill(numbers, 0);
for (number=start;number<=end; number++) {
if(number%no1==0 && number%no2==0 ) {
numbers[iCnt]=number;
iCnt=iCnt+1;
}
}
//to print values
System.out.println("Divisible by 5 & 3, numbers are: ");
int arraySize=numbers.length;
int cnt;
for(cnt=0;cnt<arraySize;cnt++) {
if(numbers[cnt]==0) {
}else {
System.out.println(numbers[cnt]);
}
}
}
public void numDivBySevenOrThirteen(int start , int end) {
int number;
int no1=7;
int no2=13;
int iCnt=0;
Arrays.fill(numbers, 0);
System.out.println("Divisible by 7 or 13, numbers are: ");
for (number=start;number<=end; number++) {
if(number%no1==0 ) {
numbers[iCnt]=number;
if(numbers[iCnt]==0) {
}else {
System.out.println(numbers[iCnt]+" is divisible by "+no1);
}
}else if(number%no2==0){
numbers[iCnt]=number;
if(numbers[iCnt]==0) {
}else {
System.out.println(numbers[iCnt]+" is divisible by "+no2);
}
}
iCnt=iCnt+1;
}
}
public static void main(String[] args) {
ArthematicOperation arthmaticOperation =new ArthematicOperation();
arthmaticOperation.findEvenNo(10, 15);
arthmaticOperation.numDivisiblefive(10,30);
arthmaticOperation.numDivByThreeAndFive(5,18);
arthmaticOperation.numDivBySevenOrThirteen(5, 40);
}
}
| UTF-8 | Java | 2,503 | java | ArthematicOperation.java | Java | [] | null | [] | package dipali;
import java.util.Arrays;
public class ArthematicOperation {
int numbers[]=new int[50];
public void findEvenNo(int start , int end) {
int number;
int iCnt=0;
for (number=start;number<=end; number++) {
if(number%2==0) {
numbers[iCnt]=number;
iCnt=iCnt+1;
}
}
//to print values
System.out.println("Even numbers are: ");
int arraySize=numbers.length;
int cnt;
for(cnt=0;cnt<arraySize;cnt++) {
if(numbers[cnt]==0) {
}else {
System.out.println(numbers[cnt]);
}
}
}
public void numDivisiblefive(int start , int end) {
int number;
int no=5;
int iCnt=0;
Arrays.fill(numbers, 0);
for (number=start;number<=end; number++) {
if(number%no==0) {
numbers[iCnt]=number;
iCnt=iCnt+1;
}
}
//to print values
System.out.println("Divisible by 5, numbers are: ");
int arraySize=numbers.length;
int cnt;
for(cnt=0;cnt<arraySize;cnt++) {
if(numbers[cnt]==0) {
}else {
System.out.println(numbers[cnt]);
}
}
}
public void numDivByThreeAndFive(int start , int end) {
int number;
int no1=3;
int no2=5;
int iCnt=0;
Arrays.fill(numbers, 0);
for (number=start;number<=end; number++) {
if(number%no1==0 && number%no2==0 ) {
numbers[iCnt]=number;
iCnt=iCnt+1;
}
}
//to print values
System.out.println("Divisible by 5 & 3, numbers are: ");
int arraySize=numbers.length;
int cnt;
for(cnt=0;cnt<arraySize;cnt++) {
if(numbers[cnt]==0) {
}else {
System.out.println(numbers[cnt]);
}
}
}
public void numDivBySevenOrThirteen(int start , int end) {
int number;
int no1=7;
int no2=13;
int iCnt=0;
Arrays.fill(numbers, 0);
System.out.println("Divisible by 7 or 13, numbers are: ");
for (number=start;number<=end; number++) {
if(number%no1==0 ) {
numbers[iCnt]=number;
if(numbers[iCnt]==0) {
}else {
System.out.println(numbers[iCnt]+" is divisible by "+no1);
}
}else if(number%no2==0){
numbers[iCnt]=number;
if(numbers[iCnt]==0) {
}else {
System.out.println(numbers[iCnt]+" is divisible by "+no2);
}
}
iCnt=iCnt+1;
}
}
public static void main(String[] args) {
ArthematicOperation arthmaticOperation =new ArthematicOperation();
arthmaticOperation.findEvenNo(10, 15);
arthmaticOperation.numDivisiblefive(10,30);
arthmaticOperation.numDivByThreeAndFive(5,18);
arthmaticOperation.numDivBySevenOrThirteen(5, 40);
}
}
| 2,503 | 0.620455 | 0.594886 | 122 | 19.516394 | 17.670126 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.065574 | false | false | 4 |
ee66c5f92d0200441c2502545493d2410cba7684 | 20,684,562,551,770 | 899e711e6c213baeb11078d61a811f4482a24b0e | /app/src/main/java/org/church/volyn/downloadHelper/ImageDownloadRunnable.java | b1b8ab9bf59ba57fd6c4bc02a384b032523eea2b | [] | no_license | lyao/herald | https://github.com/lyao/herald | c72764018af73603bbe9f9746a8e06900ddb7b63 | 58cd9eb5c0fe908da6626704cacbc6ca44736775 | refs/heads/master | 2020-06-02T13:44:58.775000 | 2017-06-12T12:30:02 | 2017-06-12T12:30:02 | 94,092,991 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.church.volyn.downloadHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.church.volyn.entities.NewsItem;
/**
* Created by Admin on 13.02.2015.
*/
public class ImageDownloadRunnable implements Runnable {
static final int HTTP_STATE_FAILED = -1;
static final int HTTP_STATE_STARTED = 0;
static final int HTTP_STATE_COMPLETED = 1;
final DownloadRunnableMethods mImageTask;
interface DownloadRunnableMethods {
Bitmap getBitmap();
void setBitmap(Bitmap bitmap);
void setByteArray(byte[] imageBytes);
void handleDownloadState(int state);
NewsItem getNewsItem();
}
ImageDownloadRunnable(DownloadRunnableMethods imageTask){
mImageTask = imageTask;
}
@Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
HttpClient httpClient = RetryingHttpClient.getHttpClient();
HttpGet request = new HttpGet(mImageTask.getNewsItem().getImageUrl());
HttpResponse response = null;
try {
response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
byte[] imageBytes = readBytes(is);
Bitmap bm = BitmapFactory.decodeStream(new ByteArrayInputStream(imageBytes));
if (bm != null) {
mImageTask.setBitmap(bm);
mImageTask.handleDownloadState(HTTP_STATE_COMPLETED);
}
} catch (Exception e) {
}
}
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
}
| UTF-8 | Java | 2,504 | java | ImageDownloadRunnable.java | Java | [
{
"context": "church.volyn.entities.NewsItem;\n\n/**\n * Created by Admin on 13.02.2015.\n */\npublic class ImageDownloadRunn",
"end": 440,
"score": 0.9766004085540771,
"start": 435,
"tag": "USERNAME",
"value": "Admin"
}
] | null | [] | package org.church.volyn.downloadHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.church.volyn.entities.NewsItem;
/**
* Created by Admin on 13.02.2015.
*/
public class ImageDownloadRunnable implements Runnable {
static final int HTTP_STATE_FAILED = -1;
static final int HTTP_STATE_STARTED = 0;
static final int HTTP_STATE_COMPLETED = 1;
final DownloadRunnableMethods mImageTask;
interface DownloadRunnableMethods {
Bitmap getBitmap();
void setBitmap(Bitmap bitmap);
void setByteArray(byte[] imageBytes);
void handleDownloadState(int state);
NewsItem getNewsItem();
}
ImageDownloadRunnable(DownloadRunnableMethods imageTask){
mImageTask = imageTask;
}
@Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
HttpClient httpClient = RetryingHttpClient.getHttpClient();
HttpGet request = new HttpGet(mImageTask.getNewsItem().getImageUrl());
HttpResponse response = null;
try {
response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
byte[] imageBytes = readBytes(is);
Bitmap bm = BitmapFactory.decodeStream(new ByteArrayInputStream(imageBytes));
if (bm != null) {
mImageTask.setBitmap(bm);
mImageTask.handleDownloadState(HTTP_STATE_COMPLETED);
}
} catch (Exception e) {
}
}
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
}
| 2,504 | 0.672923 | 0.665735 | 77 | 31.51948 | 25.143024 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.506494 | false | false | 4 |
c0608dc772b242da60d74ac647f422770c6f1118 | 29,703,993,840,825 | bdecf2e326d38b0c0ec670aa935eb8ad48bc9d12 | /src/interfaces/IRepositorioQuestao.java | a0f0d6b60378d665219bf6684adc54ed4788ab6e | [] | no_license | vakstrayed/Enem-Bolseiro | https://github.com/vakstrayed/Enem-Bolseiro | 3576dc628b62ad1e632dc3179da0f1067f1c89be | 978f7e402a313f7530a8800edcd89f8488b04711 | refs/heads/master | 2023-08-03T11:12:37.760000 | 2015-12-09T00:04:08 | 2015-12-09T00:04:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package interfaces;
import java.awt.List;
import java.util.ArrayList;
import negocio.beans.Questao;
/**
* UFRPE 2015.2 IP2
* @author Matt_lackome
*
*/
/**
* Interace IRepositorioQuestao
* define os métodos necessários para um repositório nesse projeto
* cadastrar/remover/alterar/existe questão/tamanho do repositório
*/
public interface IRepositorioQuestao {
public void cadastrar(Questao q);
public void remover(Questao q) ;
public void alterar(Questao q) ;
public ArrayList<Questao> listarQuestoes();
public Questao existe(Long id);
}
| ISO-8859-1 | Java | 603 | java | IRepositorioQuestao.java | Java | [
{
"context": "Questao;\r\n\r\n\r\n/**\r\n * UFRPE 2015.2 IP2\r\n * @author Matt_lackome\r\n *\r\n */\r\n\r\n/**\r\n * Interace IRepositorioQu",
"end": 157,
"score": 0.7451531887054443,
"start": 151,
"tag": "USERNAME",
"value": "Matt_l"
},
{
"context": ";\r\n\r\n\r\n/**\r\n * UFRPE 2015.2 IP2\r\n * @author Matt_lackome\r\n *\r\n */\r\n\r\n/**\r\n * Interace IRepositorioQuestao\r",
"end": 163,
"score": 0.7327630519866943,
"start": 157,
"tag": "NAME",
"value": "ackome"
}
] | null | [] | package interfaces;
import java.awt.List;
import java.util.ArrayList;
import negocio.beans.Questao;
/**
* UFRPE 2015.2 IP2
* @author Matt_lackome
*
*/
/**
* Interace IRepositorioQuestao
* define os métodos necessários para um repositório nesse projeto
* cadastrar/remover/alterar/existe questão/tamanho do repositório
*/
public interface IRepositorioQuestao {
public void cadastrar(Questao q);
public void remover(Questao q) ;
public void alterar(Questao q) ;
public ArrayList<Questao> listarQuestoes();
public Questao existe(Long id);
}
| 603 | 0.705686 | 0.695652 | 31 | 17.290323 | 19.513756 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483871 | false | false | 4 |
e95189187ea3fde4a6d94529a3c8a60432225f5b | 34,746,285,428,490 | ce86783419981c26e6e0dfbf41490b9217d15082 | /src/main/java/com/eduboss/refactor/service/WebPurchaseHistoryService.java | b1db100a25c5fa641ba7f678ebd7b428efa6cae1 | [] | no_license | moutainhigh/work-ms-msBoss | https://github.com/moutainhigh/work-ms-msBoss | 93e481933663501337ae74930e5aabbd0e7bb32d | 4916be9aa1cd5695b93f8d6fbe1f6eeb0010636f | refs/heads/main | 2023-01-24T04:12:51.702000 | 2020-11-20T07:56:28 | 2020-11-20T07:56:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eduboss.refactor.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eduboss.refactor.dao.WebPurchaseHistoryDAO;
import com.eduboss.refactor.dbo.WebPurchaseHistoryDO;
import com.eduboss.refactor.util.TransformBeanUtils;
import com.eduboss.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.sound.midi.Soundbank;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Groot
* @since 2019/10/23 11:34
*/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class WebPurchaseHistoryService {
@Autowired
private WebPurchaseHistoryDAO webPurchaseHistoryDAO;
@Value("${newWeb}")
private String newWebUrl;
public void sync(){
log.info("开始同步 web_purchase_history 数据");
int page = 1;
int size = 100;
boolean isLastPage = false;
String url = newWebUrl + "/apis/network/api-contract/purchase-history?startDate=%s&endDate=%s-18&pageNum=%s&pageSize=%s";
LocalDate now = LocalDate.now();
try {
while (!isLastPage) {
String formatUrl = String.format(url, now.minusDays(1).toString(), now.toString(), page, size);
String s = HttpClientUtil.getInstance().sendHttpsGet(formatUrl);
JSONObject jsonObject = JSONObject.parseObject(s);
JSONArray list = jsonObject.getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
WebPurchaseHistoryDO webPurchaseHistoryDO = list.getObject(i, WebPurchaseHistoryDO.class);
webPurchaseHistoryDAO.save(webPurchaseHistoryDO);
}
isLastPage = jsonObject.getBoolean("isLastPage");
page++;
}
}catch (Exception e) {
log.error("同步 web_purchase_history 失败",e);
throw e;
}
log.info("同步 web_purchase_history 成功");
}
public void syncTest(String startDate, String endDate) {
log.info("开始同步 web_purchase_history 数据");
int page = 1;
int size = 100;
boolean isLastPage = false;
String url = newWebUrl + "/apis/network/api-contract/purchase-history?startDate=%s&endDate=%s-18&pageNum=%s&pageSize=%s";
try {
while (!isLastPage) {
String formatUrl = String.format(url, startDate, endDate, page, size);
String s = HttpClientUtil.getInstance().sendHttpsGet(formatUrl);
JSONObject jsonObject = JSONObject.parseObject(s);
JSONArray list = jsonObject.getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
WebPurchaseHistoryDO webPurchaseHistoryDO = list.getObject(i, WebPurchaseHistoryDO.class);
webPurchaseHistoryDAO.save(webPurchaseHistoryDO);
}
isLastPage = jsonObject.getBoolean("isLastPage");
page++;
}
}catch (Exception e) {
log.error("同步 web_purchase_history 失败",e);
throw e;
}
log.info("同步 web_purchase_history 成功");
}
}
| UTF-8 | Java | 3,513 | java | WebPurchaseHistoryService.java | Java | [
{
"context": ".HashMap;\nimport java.util.Map;\n\n/**\n *\n * @author Groot\n * @since 2019/10/23 11:34\n */\n@Service\n@Transact",
"end": 753,
"score": 0.9996013641357422,
"start": 748,
"tag": "USERNAME",
"value": "Groot"
}
] | null | [] | package com.eduboss.refactor.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eduboss.refactor.dao.WebPurchaseHistoryDAO;
import com.eduboss.refactor.dbo.WebPurchaseHistoryDO;
import com.eduboss.refactor.util.TransformBeanUtils;
import com.eduboss.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.sound.midi.Soundbank;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Groot
* @since 2019/10/23 11:34
*/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class WebPurchaseHistoryService {
@Autowired
private WebPurchaseHistoryDAO webPurchaseHistoryDAO;
@Value("${newWeb}")
private String newWebUrl;
public void sync(){
log.info("开始同步 web_purchase_history 数据");
int page = 1;
int size = 100;
boolean isLastPage = false;
String url = newWebUrl + "/apis/network/api-contract/purchase-history?startDate=%s&endDate=%s-18&pageNum=%s&pageSize=%s";
LocalDate now = LocalDate.now();
try {
while (!isLastPage) {
String formatUrl = String.format(url, now.minusDays(1).toString(), now.toString(), page, size);
String s = HttpClientUtil.getInstance().sendHttpsGet(formatUrl);
JSONObject jsonObject = JSONObject.parseObject(s);
JSONArray list = jsonObject.getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
WebPurchaseHistoryDO webPurchaseHistoryDO = list.getObject(i, WebPurchaseHistoryDO.class);
webPurchaseHistoryDAO.save(webPurchaseHistoryDO);
}
isLastPage = jsonObject.getBoolean("isLastPage");
page++;
}
}catch (Exception e) {
log.error("同步 web_purchase_history 失败",e);
throw e;
}
log.info("同步 web_purchase_history 成功");
}
public void syncTest(String startDate, String endDate) {
log.info("开始同步 web_purchase_history 数据");
int page = 1;
int size = 100;
boolean isLastPage = false;
String url = newWebUrl + "/apis/network/api-contract/purchase-history?startDate=%s&endDate=%s-18&pageNum=%s&pageSize=%s";
try {
while (!isLastPage) {
String formatUrl = String.format(url, startDate, endDate, page, size);
String s = HttpClientUtil.getInstance().sendHttpsGet(formatUrl);
JSONObject jsonObject = JSONObject.parseObject(s);
JSONArray list = jsonObject.getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
WebPurchaseHistoryDO webPurchaseHistoryDO = list.getObject(i, WebPurchaseHistoryDO.class);
webPurchaseHistoryDAO.save(webPurchaseHistoryDO);
}
isLastPage = jsonObject.getBoolean("isLastPage");
page++;
}
}catch (Exception e) {
log.error("同步 web_purchase_history 失败",e);
throw e;
}
log.info("同步 web_purchase_history 成功");
}
}
| 3,513 | 0.635811 | 0.627133 | 91 | 36.98901 | 29.945553 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758242 | false | false | 4 |
71c4a41de7c6fef5a4b576360fb9671c1f5cffab | 9,655,086,525,877 | bfd6cbd8048aa801cc19b43bcfbe55157811229b | /src/day12/exception/TryCatchEx1.java | c34ef7831080cf432fd3d7936589494310b5cd50 | [] | no_license | Claude94/java_basic_study | https://github.com/Claude94/java_basic_study | 0dcc5718a58ef8c465de17ce18b4efe7fc909dd6 | 2562f967a3cf1a38b3d424e2737a2062804e2b96 | refs/heads/master | 2023-03-29T16:56:44.508000 | 2021-04-02T07:23:21 | 2021-04-02T07:23:21 | 346,592,216 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day12.exception;
public class TryCatchEx1 {
public static void main(String[] args) {
int n1 = 10, n2 = 0;
System.out.println("나눗셈 시작");
try {
//에외 발생 가능성이 있는 코드를 에외처리
System.out.printf("%d / %d = %d\n", n1, n2, n1 / n2);
} catch (Exception e) {
//예외 발생시 실행발 코드를 적습니다
System.out.println("0으로 나눌 수 없어요");
}
System.out.println("프로그램 정상 종료");
}
}
| UTF-8 | Java | 558 | java | TryCatchEx1.java | Java | [] | null | [] | package day12.exception;
public class TryCatchEx1 {
public static void main(String[] args) {
int n1 = 10, n2 = 0;
System.out.println("나눗셈 시작");
try {
//에외 발생 가능성이 있는 코드를 에외처리
System.out.printf("%d / %d = %d\n", n1, n2, n1 / n2);
} catch (Exception e) {
//예외 발생시 실행발 코드를 적습니다
System.out.println("0으로 나눌 수 없어요");
}
System.out.println("프로그램 정상 종료");
}
}
| 558 | 0.50885 | 0.480089 | 20 | 21.6 | 18.669226 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
f6b8773808cf0d5bb895556653bc620935ca7631 | 17,222,818,870,237 | 9e75aba7a02d85ad32da378e3dfbdebeddbeb7a2 | /benten-jenkins-bolt/src/main/java/com/intuit/benten/jenkins/actionhandlers/JenkinsBuildJobByJobNameActionHandler.java | faf40dd739e18c1c3f0695b17e6ddc03e91ca83f | [
"MIT"
] | permissive | kritiagrawal112/benten | https://github.com/kritiagrawal112/benten | 9cd197657d386ea4de0f25a476c6bb958c1f661c | 30495e0c781e628689ebfe4f55840c7ab11cbdb5 | refs/heads/master | 2020-08-20T05:10:26.198000 | 2019-10-18T09:52:09 | 2019-10-18T09:52:09 | 215,984,811 | 0 | 0 | MIT | true | 2019-10-18T09:07:16 | 2019-10-18T09:07:13 | 2019-10-18T08:56:09 | 2019-10-18T04:16:53 | 285 | 0 | 0 | 0 | null | false | false | package com.intuit.benten.jenkins.actionhandlers;
import com.intuit.benten.BentenJenkinsClient;
import com.intuit.benten.common.actionhandlers.BentenActionHandler;
import com.intuit.benten.common.actionhandlers.BentenHandlerResponse;
import com.intuit.benten.common.annotations.ActionHandler;
import com.intuit.benten.common.helpers.BentenMessageHelper;
import com.intuit.benten.common.nlp.BentenMessage;
import com.intuit.benten.jenkins.utils.SlackJenkinsMessageRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by sshashidhar on 2/25/18.
*/
@Component
@ActionHandler(action = JenkinsActions.ACTION_JENKINS_BUILDJOB_BY_JOBNAME)
public class JenkinsBuildJobByJobNameActionHandler implements BentenActionHandler {
@Autowired
private BentenJenkinsClient bentenJenkinsClient;
public BentenHandlerResponse handle(BentenMessage bentenMessage) {
String jobName = BentenMessageHelper.getParameterAsString(bentenMessage,JenkinsActionParameters.PARAMETER_JOB_JOBNAME);
String buildJob = bentenJenkinsClient.build(jobName);
BentenHandlerResponse bentenHandlerResponse = new BentenHandlerResponse();
bentenHandlerResponse.setBentenSlackResponse(SlackJenkinsMessageRenderer.renderJobBuildStatus(buildJob));
return bentenHandlerResponse;
}
}
| UTF-8 | Java | 1,380 | java | JenkinsBuildJobByJobNameActionHandler.java | Java | [
{
"context": "framework.stereotype.Component;\n\n/**\n * Created by sshashidhar on 2/25/18.\n */\n@Component\n@ActionHandler(action ",
"end": 616,
"score": 0.9984416365623474,
"start": 605,
"tag": "USERNAME",
"value": "sshashidhar"
}
] | null | [] | package com.intuit.benten.jenkins.actionhandlers;
import com.intuit.benten.BentenJenkinsClient;
import com.intuit.benten.common.actionhandlers.BentenActionHandler;
import com.intuit.benten.common.actionhandlers.BentenHandlerResponse;
import com.intuit.benten.common.annotations.ActionHandler;
import com.intuit.benten.common.helpers.BentenMessageHelper;
import com.intuit.benten.common.nlp.BentenMessage;
import com.intuit.benten.jenkins.utils.SlackJenkinsMessageRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by sshashidhar on 2/25/18.
*/
@Component
@ActionHandler(action = JenkinsActions.ACTION_JENKINS_BUILDJOB_BY_JOBNAME)
public class JenkinsBuildJobByJobNameActionHandler implements BentenActionHandler {
@Autowired
private BentenJenkinsClient bentenJenkinsClient;
public BentenHandlerResponse handle(BentenMessage bentenMessage) {
String jobName = BentenMessageHelper.getParameterAsString(bentenMessage,JenkinsActionParameters.PARAMETER_JOB_JOBNAME);
String buildJob = bentenJenkinsClient.build(jobName);
BentenHandlerResponse bentenHandlerResponse = new BentenHandlerResponse();
bentenHandlerResponse.setBentenSlackResponse(SlackJenkinsMessageRenderer.renderJobBuildStatus(buildJob));
return bentenHandlerResponse;
}
}
| 1,380 | 0.827536 | 0.823913 | 33 | 40.81818 | 35.327435 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 4 |
4361e4224aabe8d3d600e6f81b008c373b2f895f | 34,376,918,244,221 | de0abd9ba13525c118e2c44fbd848d807e2c7ab2 | /src/main/java/com/jiang/service/ProductInfoService.java | 063af2713b667f152404b119705c0fa56c555387 | [] | no_license | 12345ZMTHL/purchase-sale-stock | https://github.com/12345ZMTHL/purchase-sale-stock | d5f8b17f9193faaaa550ec871a5b6c8126d64186 | f6b2159245e2734fba72778b7fcd4d81583bf8b7 | refs/heads/master | 2022-12-10T18:37:30.439000 | 2020-06-21T08:56:34 | 2020-06-21T08:56:34 | 257,257,640 | 0 | 0 | null | false | 2020-09-09T19:49:31 | 2020-04-20T11:19:44 | 2020-06-21T08:56:54 | 2020-09-09T19:49:29 | 29 | 0 | 0 | 1 | Java | false | false | package com.jiang.service;
import com.jiang.entity.ProductInfo;
import com.jiang.vo.QueryVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
/**
* @program: purchase-sale-stock
* @description:
* @author: lvjx
* @create: 2020-04-20 14:21
**/
public interface ProductInfoService {
Page<ProductInfo> listPage(QueryVO vo, PageRequest pageable);
Integer addProductInfo(ProductInfo vo);
Integer updateProductInfo(ProductInfo vo);
Integer deleteProductInfoById(Long id);
}
| UTF-8 | Java | 541 | java | ProductInfoService.java | Java | [
{
"context": ": purchase-sale-stock\n * @description:\n * @author: lvjx\n * @create: 2020-04-20 14:21\n **/\npublic interfac",
"end": 262,
"score": 0.9997014999389648,
"start": 258,
"tag": "USERNAME",
"value": "lvjx"
}
] | null | [] | package com.jiang.service;
import com.jiang.entity.ProductInfo;
import com.jiang.vo.QueryVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
/**
* @program: purchase-sale-stock
* @description:
* @author: lvjx
* @create: 2020-04-20 14:21
**/
public interface ProductInfoService {
Page<ProductInfo> listPage(QueryVO vo, PageRequest pageable);
Integer addProductInfo(ProductInfo vo);
Integer updateProductInfo(ProductInfo vo);
Integer deleteProductInfoById(Long id);
}
| 541 | 0.759704 | 0.737523 | 22 | 23.59091 | 20.003771 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 4 |
51c8c894ca89d1227f2ae1e86c7698d4315ba2a2 | 11,252,814,331,603 | 8cf633414369c27a7cc4a9ac06942922a4b4b4e8 | /src/ANXCamera/sources/com/android/camera/parallel/AlgoConnector.java | 3b12a5e61f9cc5e09de08cbe458002d29be511f3 | [] | no_license | XEonAX/ANXCamera10 | https://github.com/XEonAX/ANXCamera10 | 5158e5bbbfab78f7b513dbde51e2899e6fe3185f | e59c27aa285c72a336914db742c77c55615c49c5 | refs/heads/phoenixin11.0.4.0 | 2021-06-23T10:31:07.167000 | 2020-09-29T15:59:51 | 2020-09-29T15:59:51 | 187,456,293 | 66 | 18 | null | false | 2020-12-29T02:23:56 | 2019-05-19T09:17:35 | 2020-12-21T11:50:04 | 2020-09-29T15:59:52 | 313,539 | 80 | 18 | 17 | Smali | false | false | package com.android.camera.parallel;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.android.camera.LocalParallelService;
import com.android.camera.log.Log;
public class AlgoConnector {
/* access modifiers changed from: private */
public static final String TAG = "AlgoConnector";
/* access modifiers changed from: private */
public static final AlgoConnector ourInstance = new AlgoConnector();
/* access modifiers changed from: private */
public LocalParallelService.LocalBinder mLocalBinder;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
String access$000 = AlgoConnector.TAG;
Log.d(access$000, "onServiceConnected: " + componentName);
synchronized (AlgoConnector.ourInstance) {
LocalParallelService.LocalBinder unused = AlgoConnector.this.mLocalBinder = (LocalParallelService.LocalBinder) iBinder;
AlgoConnector.ourInstance.notify();
}
}
public void onServiceDisconnected(ComponentName componentName) {
Log.d(AlgoConnector.TAG, "onServiceDisconnected");
synchronized (AlgoConnector.ourInstance) {
LocalParallelService.LocalBinder unused = AlgoConnector.this.mLocalBinder = null;
AlgoConnector.ourInstance.notify();
}
}
};
private AlgoConnector() {
}
public static AlgoConnector getInstance() {
return ourInstance;
}
public LocalParallelService.LocalBinder getLocalBinder() {
return getLocalBinder(false);
}
public LocalParallelService.LocalBinder getLocalBinder(boolean z) {
if (z) {
int i = 0;
synchronized (ourInstance) {
while (this.mLocalBinder == null && i < 50) {
try {
ourInstance.wait(100);
i++;
String str = TAG;
Log.w(str, "waiting service..." + i);
} catch (InterruptedException e2) {
Log.e(TAG, e2.getMessage(), (Throwable) e2);
}
}
}
}
return this.mLocalBinder;
}
public void setServiceStatusListener(LocalParallelService.ServiceStatusListener serviceStatusListener) {
if (serviceStatusListener != null) {
LocalParallelService.LocalBinder localBinder = this.mLocalBinder;
if (localBinder != null) {
localBinder.setOnPictureTakenListener(serviceStatusListener);
}
}
}
public void startService(Context context) {
if (this.mLocalBinder == null) {
Log.d(TAG, "startService: bind LocalParallelService start!");
context.bindService(new Intent(context, LocalParallelService.class), this.mServiceConnection, 67108929);
}
}
}
| UTF-8 | Java | 3,143 | java | AlgoConnector.java | Java | [] | null | [] | package com.android.camera.parallel;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.android.camera.LocalParallelService;
import com.android.camera.log.Log;
public class AlgoConnector {
/* access modifiers changed from: private */
public static final String TAG = "AlgoConnector";
/* access modifiers changed from: private */
public static final AlgoConnector ourInstance = new AlgoConnector();
/* access modifiers changed from: private */
public LocalParallelService.LocalBinder mLocalBinder;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
String access$000 = AlgoConnector.TAG;
Log.d(access$000, "onServiceConnected: " + componentName);
synchronized (AlgoConnector.ourInstance) {
LocalParallelService.LocalBinder unused = AlgoConnector.this.mLocalBinder = (LocalParallelService.LocalBinder) iBinder;
AlgoConnector.ourInstance.notify();
}
}
public void onServiceDisconnected(ComponentName componentName) {
Log.d(AlgoConnector.TAG, "onServiceDisconnected");
synchronized (AlgoConnector.ourInstance) {
LocalParallelService.LocalBinder unused = AlgoConnector.this.mLocalBinder = null;
AlgoConnector.ourInstance.notify();
}
}
};
private AlgoConnector() {
}
public static AlgoConnector getInstance() {
return ourInstance;
}
public LocalParallelService.LocalBinder getLocalBinder() {
return getLocalBinder(false);
}
public LocalParallelService.LocalBinder getLocalBinder(boolean z) {
if (z) {
int i = 0;
synchronized (ourInstance) {
while (this.mLocalBinder == null && i < 50) {
try {
ourInstance.wait(100);
i++;
String str = TAG;
Log.w(str, "waiting service..." + i);
} catch (InterruptedException e2) {
Log.e(TAG, e2.getMessage(), (Throwable) e2);
}
}
}
}
return this.mLocalBinder;
}
public void setServiceStatusListener(LocalParallelService.ServiceStatusListener serviceStatusListener) {
if (serviceStatusListener != null) {
LocalParallelService.LocalBinder localBinder = this.mLocalBinder;
if (localBinder != null) {
localBinder.setOnPictureTakenListener(serviceStatusListener);
}
}
}
public void startService(Context context) {
if (this.mLocalBinder == null) {
Log.d(TAG, "startService: bind LocalParallelService start!");
context.bindService(new Intent(context, LocalParallelService.class), this.mServiceConnection, 67108929);
}
}
}
| 3,143 | 0.629971 | 0.622654 | 82 | 37.329269 | 29.916573 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.512195 | false | false | 4 |
502f98ac896093ccf5c50cc5b4671633051d0290 | 24,790,551,272,434 | 3650c30d9bd86ac78715bc0c8dfb965ef1f34c32 | /jxlvudp/src/main/com/kesun/dao/web/impl/DAdvertisement.java | d197c86e8547cc90a242e63b8154cf886084fb56 | [] | no_license | Delete502/test1-1 | https://github.com/Delete502/test1-1 | 5d1a18658433d3dc0223929f88df70f332d48722 | 0f40b8e7d5676710ed188617d1ceb3ee9d7d8ad7 | refs/heads/master | 2020-03-18T11:39:09.998000 | 2018-05-21T12:39:14 | 2018-05-21T12:39:14 | 134,683,714 | 1 | 0 | null | true | 2018-05-24T08:15:48 | 2018-05-24T08:15:48 | 2018-05-21T12:39:38 | 2018-05-21T12:39:36 | 72,134 | 0 | 0 | 0 | null | false | null | package kesun.dao.web.impl;
import kesun.dao.DaoSupport;
import org.springframework.stereotype.Repository;
/**
* Created by wph-pc on 2017/5/30.
*/
@Repository("dAdvertisement")
public class DAdvertisement extends DaoSupport {
public DAdvertisement(){
setMapperName("mapper.AdvertisementMapper");
}
}
| UTF-8 | Java | 321 | java | DAdvertisement.java | Java | [
{
"context": "ramework.stereotype.Repository;\n\n/**\n * Created by wph-pc on 2017/5/30.\n */\n@Repository(\"dAdvertisement\")\np",
"end": 133,
"score": 0.9995839595794678,
"start": 127,
"tag": "USERNAME",
"value": "wph-pc"
}
] | null | [] | package kesun.dao.web.impl;
import kesun.dao.DaoSupport;
import org.springframework.stereotype.Repository;
/**
* Created by wph-pc on 2017/5/30.
*/
@Repository("dAdvertisement")
public class DAdvertisement extends DaoSupport {
public DAdvertisement(){
setMapperName("mapper.AdvertisementMapper");
}
}
| 321 | 0.738318 | 0.716511 | 14 | 21.928572 | 18.926414 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
51e45e78d64ebbbf326432b53b8d11b2c1656a0e | 19,069,654,818,607 | fd3df8a9bd9c253e19a09f6d3335585285668f2e | /src/main/java/com/qupeng/concurrent/day03/lookback/WatchThreadTest.java | b528f14e2165133a9be54325676355c00092d41f | [] | no_license | qupeng7/java-concurrent-03 | https://github.com/qupeng7/java-concurrent-03 | baa10d3a5c6279c559c03142a559f9ee400cbdf8 | 9c11bb28c516357f19f423a432f3093ab36ad8c0 | refs/heads/master | 2020-12-14T20:50:28.337000 | 2020-01-31T07:43:01 | 2020-01-31T07:43:01 | 234,864,224 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qupeng.concurrent.day03.lookback;
/**
* 观察继承Thread类的时候,
* 对run方法加上synchronized是否能达到同步效果
*
* 使用继承Thread类的方式在run方法上加synchronized
* 达不到同步的效果,因为每个线程锁的都是自己,而这
* 每个线程又是不同的对象,所以达不到同步效果。
* @author qupeng
*/
public class WatchThreadTest{
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
MyThread mt = new MyThread("线程"+i);
//设置线程的名称,方便查看在执行哪个对象的run()
mt.start();
}
}
static class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
@Override
public synchronized void run() {
String threadName = Thread.currentThread().getName();
// synchronized (WatchThreadTest.class) {
//循环10次,每1秒钟循环一次
for (int i = 1; i <= 10; i++) {
System.out.println(threadName+":执行第"+i+"次循环……");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//synchronized结束
// }
}
}
} | UTF-8 | Java | 1,197 | java | WatchThreadTest.java | Java | [
{
"context": "每个线程锁的都是自己,而这\n * 每个线程又是不同的对象,所以达不到同步效果。\n * @author qupeng\n */\npublic class WatchThreadTest{\n\n\tpublic static",
"end": 217,
"score": 0.9987666010856628,
"start": 211,
"tag": "USERNAME",
"value": "qupeng"
}
] | null | [] | package com.qupeng.concurrent.day03.lookback;
/**
* 观察继承Thread类的时候,
* 对run方法加上synchronized是否能达到同步效果
*
* 使用继承Thread类的方式在run方法上加synchronized
* 达不到同步的效果,因为每个线程锁的都是自己,而这
* 每个线程又是不同的对象,所以达不到同步效果。
* @author qupeng
*/
public class WatchThreadTest{
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
MyThread mt = new MyThread("线程"+i);
//设置线程的名称,方便查看在执行哪个对象的run()
mt.start();
}
}
static class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
@Override
public synchronized void run() {
String threadName = Thread.currentThread().getName();
// synchronized (WatchThreadTest.class) {
//循环10次,每1秒钟循环一次
for (int i = 1; i <= 10; i++) {
System.out.println(threadName+":执行第"+i+"次循环……");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//synchronized结束
// }
}
}
} | 1,197 | 0.628571 | 0.613757 | 51 | 17.549019 | 16.366289 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.196079 | false | false | 4 |
25ef915fdbb55ccb99f765863d766201b0b75580 | 34,213,709,486,596 | 7548fcdae12994f294d7d05d1086568697fe030f | /src/main/java/unhappy/legendzrpg/plugin/listeners/JoinListener.java | d148624817eb4de2d2b6318545c3e6801f47bc17 | [] | no_license | Xiaoooooooooo/core | https://github.com/Xiaoooooooooo/core | 73b44901403df127a442524d2af0734b1df6f23c | 62a2e6e5cd5663955201d80092471c4c4008c49e | refs/heads/main | 2023-08-15T06:48:57.304000 | 2021-10-06T12:16:33 | 2021-10-06T12:16:33 | 414,198,279 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package unhappy.legendzrpg.plugin.listeners;
import lombok.Getter;
import org.bson.Document;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import unhappy.legendzrpg.plugin.Main;
import unhappy.legendzrpg.plugin.utils.Utils;
@Getter
public class JoinListener implements Listener {
@Getter
private static Main plugin;
public JoinListener(Main plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (!player.hasPlayedBefore()) {
Document document = new Document("uuid", player.getUniqueId().toString())
.append("name", player.getName().toLowerCase())
.append("realName", player.getName())
.append("points", 0);
plugin.getCollection().insertOne(document);
}
String joinMessage = Utils.chat("&a&lJOIN &7[&a+&7] " + " &7" + player.getName());
if (!player.hasPlayedBefore()) {
joinMessage = Utils.chat("&a&lWELCOME&r &7[&a+&7] " + " &7" + player.getName());
}
event.setJoinMessage(joinMessage);
}
}
| UTF-8 | Java | 1,407 | java | JoinListener.java | Java | [] | null | [] | package unhappy.legendzrpg.plugin.listeners;
import lombok.Getter;
import org.bson.Document;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import unhappy.legendzrpg.plugin.Main;
import unhappy.legendzrpg.plugin.utils.Utils;
@Getter
public class JoinListener implements Listener {
@Getter
private static Main plugin;
public JoinListener(Main plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (!player.hasPlayedBefore()) {
Document document = new Document("uuid", player.getUniqueId().toString())
.append("name", player.getName().toLowerCase())
.append("realName", player.getName())
.append("points", 0);
plugin.getCollection().insertOne(document);
}
String joinMessage = Utils.chat("&a&lJOIN &7[&a+&7] " + " &7" + player.getName());
if (!player.hasPlayedBefore()) {
joinMessage = Utils.chat("&a&lWELCOME&r &7[&a+&7] " + " &7" + player.getName());
}
event.setJoinMessage(joinMessage);
}
}
| 1,407 | 0.623312 | 0.618337 | 38 | 34.657894 | 24.283714 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 4 |
04d82e0dde7d4a7b56275bf2a9453deedbc552de | 15,487,652,108,730 | 928d4592f8292c0b68bc2a6aadcfbdefbe88219f | /app/src/main/java/com/puskesmascilandak/e_jiwa/activities/main/Yt.java | b02f3037f6cf4e716abb785db49ae0047ad36a9d | [] | no_license | ubaybj/ejiwa | https://github.com/ubaybj/ejiwa | 95a938001119604a31defa80ae67a80bc4c303e6 | 8e9980ad8925d5a72468b60bb92a3e7fab6d48e9 | refs/heads/master | 2020-07-08T01:41:05.477000 | 2019-08-21T07:39:40 | 2019-08-21T07:39:40 | 203,530,818 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.puskesmascilandak.e_jiwa.activities.main;
import android.webkit.WebView;
import com.puskesmascilandak.e_jiwa.R;
import com.puskesmascilandak.e_jiwa.activities.Activity;
public class Yt extends Activity {
public Yt() {
super(R.layout.activity_yt);
}
@Override
protected void initOnCreate() {
WebView myWebfb = findViewById(R.id.webviewyt);
myWebfb.loadUrl("https://www.youtube.com/channel/UCJdsNCciW3jxXe253XNty2A");
}
}
| UTF-8 | Java | 484 | java | Yt.java | Java | [] | null | [] | package com.puskesmascilandak.e_jiwa.activities.main;
import android.webkit.WebView;
import com.puskesmascilandak.e_jiwa.R;
import com.puskesmascilandak.e_jiwa.activities.Activity;
public class Yt extends Activity {
public Yt() {
super(R.layout.activity_yt);
}
@Override
protected void initOnCreate() {
WebView myWebfb = findViewById(R.id.webviewyt);
myWebfb.loadUrl("https://www.youtube.com/channel/UCJdsNCciW3jxXe253XNty2A");
}
}
| 484 | 0.71281 | 0.702479 | 21 | 22 | 24.291876 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
d0856a9660d0fefe00f4cec24e9fe79fa719ee2b | 12,841,952,273,168 | 7cb5734e11c07ba468bc8e822afc30a8b51204a9 | /src/main/java/top/seraphjack/jielong/JieLong.java | 92d18d13e97ec5a371630c3284f504e3bd530096 | [
"MIT"
] | permissive | SeraphJACK/JieLong | https://github.com/SeraphJACK/JieLong | 1f5e416ddeaa235c4ae34d19f39fb7f1109967aa | 2d8c505bc0e3509161f2b55c4c7e043ccc96eab3 | refs/heads/master | 2020-07-02T10:49:15.915000 | 2019-08-10T03:35:52 | 2019-08-10T03:35:52 | 201,502,594 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package top.seraphjack.jielong;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.seraphjack.jielong.command.CommandJieLong;
import top.seraphjack.jielong.idiom.IdiomProvider;
import top.seraphjack.jielong.idiom.IdiomProviderFile;
@Mod(modid = JieLong.MODID, name = JieLong.NAME, version = JieLong.VERSION, serverSideOnly = true, acceptableRemoteVersions = "*")
public class JieLong {
public static final String MODID = "jielong", NAME = "JieLong", VERSION = "@VERSION_INJECT@";
public static final Logger logger = LogManager.getLogger(MODID);
public static IdiomProvider idiomProvider;
@Mod.EventHandler
public void serverStarting(FMLServerStartingEvent event) {
idiomProvider = new IdiomProviderFile();
event.registerServerCommand(new CommandJieLong());
}
}
| UTF-8 | Java | 959 | java | JieLong.java | Java | [] | null | [] | package top.seraphjack.jielong;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.seraphjack.jielong.command.CommandJieLong;
import top.seraphjack.jielong.idiom.IdiomProvider;
import top.seraphjack.jielong.idiom.IdiomProviderFile;
@Mod(modid = JieLong.MODID, name = JieLong.NAME, version = JieLong.VERSION, serverSideOnly = true, acceptableRemoteVersions = "*")
public class JieLong {
public static final String MODID = "jielong", NAME = "JieLong", VERSION = "@VERSION_INJECT@";
public static final Logger logger = LogManager.getLogger(MODID);
public static IdiomProvider idiomProvider;
@Mod.EventHandler
public void serverStarting(FMLServerStartingEvent event) {
idiomProvider = new IdiomProviderFile();
event.registerServerCommand(new CommandJieLong());
}
}
| 959 | 0.776851 | 0.774765 | 24 | 38.958332 | 32.71019 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.791667 | false | false | 4 |
dddb6664f6b33adad2c3594bc6709b680cc47b04 | 25,769,849,403 | 79554b23d2397e0caff170d45ebb339798cfbf42 | /common-util/src/main/java/com.github.windchopper.common.util/stream/FallibleRunnable.java | b089b84e171a98300420eb9fea320310ccfd5bd6 | [
"Apache-2.0"
] | permissive | windchopper/common | https://github.com/windchopper/common | ad0f5b626eeb8b9fee2bbfa96de4cf93dd4f836d | 299d5ebfaa5e85b84d81edfe2b23e17294c607f7 | refs/heads/master | 2021-11-12T18:11:24.011000 | 2021-05-30T21:19:34 | 2021-05-30T21:19:34 | 59,422,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.windchopper.common.util.stream;
@FunctionalInterface public interface FallibleRunnable extends Fallible {
void run() throws Throwable;
}
| UTF-8 | Java | 163 | java | FallibleRunnable.java | Java | [
{
"context": "package com.github.windchopper.common.util.stream;\n\n@FunctionalInterface publ",
"end": 27,
"score": 0.6599591970443726,
"start": 23,
"tag": "USERNAME",
"value": "chop"
}
] | null | [] | package com.github.windchopper.common.util.stream;
@FunctionalInterface public interface FallibleRunnable extends Fallible {
void run() throws Throwable;
}
| 163 | 0.797546 | 0.797546 | 7 | 22.285715 | 27.716496 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
d3323e2ed3df593ad4ab6c53e35c2dc775e3fc24 | 29,807,073,071,151 | 8a09bf33910c77fcbe835ca172a54d51d3f7d44d | /src/modelo/entidad/BeanGestionarCargaCurricular.java | 6fe7339d3c5f4fd43914541e2c8b6716ab44699b | [] | no_license | JavierMed/ProyectoColegioSanJuandeDios | https://github.com/JavierMed/ProyectoColegioSanJuandeDios | 92999834859fde05b21f35c5ae9760ddffe810af | e835764d90c23477038c0c870745ddab7fbf4014 | refs/heads/master | 2020-03-19T18:55:49.869000 | 2018-06-10T17:50:19 | 2018-06-10T17:50:19 | 136,831,633 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package modelo.entidad;
public class BeanGestionarCargaCurricular {
private String nivel;
private String grado;
private String seccion;
private String tipoCurso;
private String curso;
private String docente;
public BeanGestionarCargaCurricular(String nivel, String grado, String seccion, String tipoCurso, String curso,
String docente) {
super();
this.nivel = nivel;
this.grado = grado;
this.seccion = seccion;
this.tipoCurso = tipoCurso;
this.curso = curso;
this.docente = docente;
}
public String getNivel() {
return nivel;
}
public void setNivel(String nivel) {
this.nivel = nivel;
}
public String getGrado() {
return grado;
}
public void setGrado(String grado) {
this.grado = grado;
}
public String getSeccion() {
return seccion;
}
public void setSeccion(String seccion) {
this.seccion = seccion;
}
public String getTipoCurso() {
return tipoCurso;
}
public void setTipoCurso(String tipoCurso) {
this.tipoCurso = tipoCurso;
}
public String getCurso() {
return curso;
}
public void setCurso(String curso) {
this.curso = curso;
}
public String getDocente() {
return docente;
}
public void setDocente(String docente) {
this.docente = docente;
}
}
| UTF-8 | Java | 1,233 | java | BeanGestionarCargaCurricular.java | Java | [] | null | [] | package modelo.entidad;
public class BeanGestionarCargaCurricular {
private String nivel;
private String grado;
private String seccion;
private String tipoCurso;
private String curso;
private String docente;
public BeanGestionarCargaCurricular(String nivel, String grado, String seccion, String tipoCurso, String curso,
String docente) {
super();
this.nivel = nivel;
this.grado = grado;
this.seccion = seccion;
this.tipoCurso = tipoCurso;
this.curso = curso;
this.docente = docente;
}
public String getNivel() {
return nivel;
}
public void setNivel(String nivel) {
this.nivel = nivel;
}
public String getGrado() {
return grado;
}
public void setGrado(String grado) {
this.grado = grado;
}
public String getSeccion() {
return seccion;
}
public void setSeccion(String seccion) {
this.seccion = seccion;
}
public String getTipoCurso() {
return tipoCurso;
}
public void setTipoCurso(String tipoCurso) {
this.tipoCurso = tipoCurso;
}
public String getCurso() {
return curso;
}
public void setCurso(String curso) {
this.curso = curso;
}
public String getDocente() {
return docente;
}
public void setDocente(String docente) {
this.docente = docente;
}
}
| 1,233 | 0.713706 | 0.713706 | 62 | 18.887096 | 17.693726 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.774194 | false | false | 4 |
2a919ffa7b4aef45b3ff3935924816ded82863da | 35,399,120,455,958 | d16724e97358f301e99af0687f5db82d9ac4ff7e | /rawdata/java/snippets/322.java | a6e7b55d5818960bc14665e27720a0d815788e15 | [] | no_license | kaushik-rohit/code2seq | https://github.com/kaushik-rohit/code2seq | 39b562f79e9555083c18c73c05ffc4f379d1f3b8 | c942b95d7d5997e5b2d45ed8c3161ca9296ddde3 | refs/heads/master | 2022-11-29T11:46:43.105000 | 2020-01-04T02:04:04 | 2020-01-04T02:04:04 | 225,870,854 | 0 | 0 | null | false | 2022-11-16T09:21:10 | 2019-12-04T13:12:59 | 2020-01-04T02:04:42 | 2022-11-16T09:21:07 | 1,033 | 0 | 0 | 2 | C# | false | false | public Environment addAll(@NonNull Map<String, String> map) {
map.forEach((key, value) -> this.props.setProperty(key, value));
return this;
} | UTF-8 | Java | 161 | java | 322.java | Java | [] | null | [] | public Environment addAll(@NonNull Map<String, String> map) {
map.forEach((key, value) -> this.props.setProperty(key, value));
return this;
} | 161 | 0.645963 | 0.645963 | 4 | 39.5 | 27.789387 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 4 |
a6092cbf2a63c4e56cc0c06b15fc7481c48cde51 | 35,038,343,210,941 | a9e9f70ea63ecf468c848f7b0ec5af255c2079b0 | /earthquackes/app/src/main/java/com/example/earthquackes/QuackesAdapter.java | 1aa7c17e8912f29d6800502ea7f74c094503cb37 | [] | no_license | Ellzo/Earthquackes | https://github.com/Ellzo/Earthquackes | 7c1e86a419082b921d5b5b74119c671298b8ec07 | 5f74eb552e519534a4f008921a8737784d43f476 | refs/heads/master | 2022-07-17T02:20:25.869000 | 2020-05-15T10:59:34 | 2020-05-15T10:59:34 | 264,170,240 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.earthquackes;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.icu.text.DecimalFormat;
import android.net.Uri;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.Inflater;
public class QuackesAdapter extends RecyclerView.Adapter<QuackesAdapter.QuackeViewHolder> {
private ArrayList<Earthquake>earthquakes;
private LayoutInflater mInflayer;
private Context context;
public QuackesAdapter(Activity context, List<Earthquake> earthquackes){
mInflayer= LayoutInflater.from(context);
this.context=context;
if(earthquackes != null) {
this.earthquakes = (ArrayList) earthquackes;
}
}
@NonNull
@Override
public QuackesAdapter.QuackeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View mItemView= mInflayer.inflate(R.layout.earthquake_layout,parent,false);
return new QuackeViewHolder(mItemView);
}
@Override
public void onBindViewHolder(@NonNull QuackeViewHolder holder, int position) {
final Earthquake earthquake=earthquakes.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri= Uri.parse(earthquake.getUrl());
Intent intent= new Intent(Intent.ACTION_VIEW,uri);
if(intent.resolveActivity(context.getPackageManager())!= null){
context.startActivity(intent);
}
}
});
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
if (earthquake.getMagnitude()<10){
holder.getMagnitude().setText(new DecimalFormat("0.0").format(earthquake.getMagnitude()));
}else{
holder.getMagnitude().setText(new DecimalFormat("0").format(earthquake.getMagnitude()));
}
}else{
holder.getMagnitude().setText(Double.toString(earthquake.getMagnitude()));
}
if(earthquake.getPlace().contains("km")){
holder.getDistance().setText(earthquake.getPlace().substring(0,earthquake.getPlace().indexOf('f')+1));
holder.getPlace().setText(earthquake.getPlace().substring(earthquake.getPlace().indexOf('f')+2).toUpperCase());
}else{
holder.getDistance().setText(R.string.near);
holder.getPlace().setText(earthquake.getPlace().toUpperCase());
}
/*
// We Can use this code too:
if (originalLocation.contains(LOCATION_SEPARATOR)) {
String[] parts = originalLocation.split(LOCATION_SEPARATOR);
locationOffset = parts[0] + LOCATION_SEPARATOR;
primaryLocation = parts[1];
} else {
locationOffset = getContext().getString(R.string.near_the);
primaryLocation = originalLocation;
}
*/
SimpleDateFormat dateFormat= new SimpleDateFormat("MMM dd, yyyy");
holder.getDate().setText(dateFormat.format(new Date(earthquake.getDate())));
SimpleDateFormat timeFormat= new SimpleDateFormat("HH:mm a");
holder.getTime().setText(timeFormat.format(new Date(earthquake.getDate())));
GradientDrawable magnitudeCircle= (GradientDrawable) holder.getMagnitude().getBackground();
// Get the appropriate background color based on the current earthquake magnitude
int magnitudeColor = getMagnitudeColor(earthquake.getMagnitude());
// Set the color on the magnitude circle
magnitudeCircle.setColor(magnitudeColor);
}
private int getMagnitudeColor(Double mag){
switch ((int) Math.round(mag)){
case 0:
case 1:
return ContextCompat.getColor(context, R.color.magnitude1);
case 2:
return ContextCompat.getColor(context, R.color.magnitude2);
case 3:
return ContextCompat.getColor(context, R.color.magnitude3);
case 4:
return ContextCompat.getColor(context, R.color.magnitude4);
case 5:
return ContextCompat.getColor(context, R.color.magnitude5);
case 6:
return ContextCompat.getColor(context, R.color.magnitude6);
case 7:
return ContextCompat.getColor(context, R.color.magnitude7);
case 8:
return ContextCompat.getColor(context, R.color.magnitude8);
case 9:
return ContextCompat.getColor(context, R.color.magnitude9);
default:
return ContextCompat.getColor(context, R.color.magnitude10plus);
}
}
@Override
public int getItemCount() {
return earthquakes.size();
}
public void clear(){
earthquakes.clear();
mInflayer=null;
context=null;
}
class QuackeViewHolder extends RecyclerView.ViewHolder{
private TextView magnitude;
private TextView distance;
private TextView place;
private TextView date;
private TextView time;
public QuackeViewHolder(@NonNull View itemView) {
super(itemView);
magnitude= itemView.findViewById(R.id.magnitude);
distance= itemView.findViewById(R.id.distance);
place= itemView.findViewById(R.id.place);
date= itemView.findViewById(R.id.date);
time= itemView.findViewById(R.id.time);
}
public TextView getDate() {
return date;
}
public TextView getMagnitude() {
return magnitude;
}
public TextView getPlace() {
return place;
}
public TextView getTime() {
return time;
}
public TextView getDistance(){
return distance;
}
}
}
| UTF-8 | Java | 6,347 | java | QuackesAdapter.java | Java | [] | null | [] | package com.example.earthquackes;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.icu.text.DecimalFormat;
import android.net.Uri;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.Inflater;
public class QuackesAdapter extends RecyclerView.Adapter<QuackesAdapter.QuackeViewHolder> {
private ArrayList<Earthquake>earthquakes;
private LayoutInflater mInflayer;
private Context context;
public QuackesAdapter(Activity context, List<Earthquake> earthquackes){
mInflayer= LayoutInflater.from(context);
this.context=context;
if(earthquackes != null) {
this.earthquakes = (ArrayList) earthquackes;
}
}
@NonNull
@Override
public QuackesAdapter.QuackeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View mItemView= mInflayer.inflate(R.layout.earthquake_layout,parent,false);
return new QuackeViewHolder(mItemView);
}
@Override
public void onBindViewHolder(@NonNull QuackeViewHolder holder, int position) {
final Earthquake earthquake=earthquakes.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri= Uri.parse(earthquake.getUrl());
Intent intent= new Intent(Intent.ACTION_VIEW,uri);
if(intent.resolveActivity(context.getPackageManager())!= null){
context.startActivity(intent);
}
}
});
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
if (earthquake.getMagnitude()<10){
holder.getMagnitude().setText(new DecimalFormat("0.0").format(earthquake.getMagnitude()));
}else{
holder.getMagnitude().setText(new DecimalFormat("0").format(earthquake.getMagnitude()));
}
}else{
holder.getMagnitude().setText(Double.toString(earthquake.getMagnitude()));
}
if(earthquake.getPlace().contains("km")){
holder.getDistance().setText(earthquake.getPlace().substring(0,earthquake.getPlace().indexOf('f')+1));
holder.getPlace().setText(earthquake.getPlace().substring(earthquake.getPlace().indexOf('f')+2).toUpperCase());
}else{
holder.getDistance().setText(R.string.near);
holder.getPlace().setText(earthquake.getPlace().toUpperCase());
}
/*
// We Can use this code too:
if (originalLocation.contains(LOCATION_SEPARATOR)) {
String[] parts = originalLocation.split(LOCATION_SEPARATOR);
locationOffset = parts[0] + LOCATION_SEPARATOR;
primaryLocation = parts[1];
} else {
locationOffset = getContext().getString(R.string.near_the);
primaryLocation = originalLocation;
}
*/
SimpleDateFormat dateFormat= new SimpleDateFormat("MMM dd, yyyy");
holder.getDate().setText(dateFormat.format(new Date(earthquake.getDate())));
SimpleDateFormat timeFormat= new SimpleDateFormat("HH:mm a");
holder.getTime().setText(timeFormat.format(new Date(earthquake.getDate())));
GradientDrawable magnitudeCircle= (GradientDrawable) holder.getMagnitude().getBackground();
// Get the appropriate background color based on the current earthquake magnitude
int magnitudeColor = getMagnitudeColor(earthquake.getMagnitude());
// Set the color on the magnitude circle
magnitudeCircle.setColor(magnitudeColor);
}
private int getMagnitudeColor(Double mag){
switch ((int) Math.round(mag)){
case 0:
case 1:
return ContextCompat.getColor(context, R.color.magnitude1);
case 2:
return ContextCompat.getColor(context, R.color.magnitude2);
case 3:
return ContextCompat.getColor(context, R.color.magnitude3);
case 4:
return ContextCompat.getColor(context, R.color.magnitude4);
case 5:
return ContextCompat.getColor(context, R.color.magnitude5);
case 6:
return ContextCompat.getColor(context, R.color.magnitude6);
case 7:
return ContextCompat.getColor(context, R.color.magnitude7);
case 8:
return ContextCompat.getColor(context, R.color.magnitude8);
case 9:
return ContextCompat.getColor(context, R.color.magnitude9);
default:
return ContextCompat.getColor(context, R.color.magnitude10plus);
}
}
@Override
public int getItemCount() {
return earthquakes.size();
}
public void clear(){
earthquakes.clear();
mInflayer=null;
context=null;
}
class QuackeViewHolder extends RecyclerView.ViewHolder{
private TextView magnitude;
private TextView distance;
private TextView place;
private TextView date;
private TextView time;
public QuackeViewHolder(@NonNull View itemView) {
super(itemView);
magnitude= itemView.findViewById(R.id.magnitude);
distance= itemView.findViewById(R.id.distance);
place= itemView.findViewById(R.id.place);
date= itemView.findViewById(R.id.date);
time= itemView.findViewById(R.id.time);
}
public TextView getDate() {
return date;
}
public TextView getMagnitude() {
return magnitude;
}
public TextView getPlace() {
return place;
}
public TextView getTime() {
return time;
}
public TextView getDistance(){
return distance;
}
}
}
| 6,347 | 0.644556 | 0.639672 | 185 | 33.308109 | 28.826923 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.551351 | false | false | 4 |
86c006f33eba13446ef99ff0922450f2ff6fa9ee | 11,287,174,104,443 | 0394d3f651aea94e908e871d4295b5d4d06e7ad3 | /ds/segment_tree_vector.java | 95185a837a1d786532dbb84fd51063f91ca0cff5 | [] | no_license | anand-20/CPLib | https://github.com/anand-20/CPLib | 238b41503c4ee06fffe27f3d4425ee8c85471437 | 1d50aade3ec113e97d38cae42cf4c1638d98add5 | refs/heads/master | 2021-06-15T13:25:16.386000 | 2021-02-20T09:11:15 | 2021-02-20T09:11:15 | 145,424,948 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.*;
import java.math.*;
import java.util.concurrent.*;
public final class segment_tree_vector
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static int[][] tree;
static void build(int node,int s,int e)
{
if(s>e)
{
return;
}
if(s==e)
{
tree[node]=new int[]{10};
}
else
{
int mid=(s+e)>>1;
build(node<<1,s,mid);build(node<<1|1,mid+1,e);
tree[node]=merge(tree[node<<1],tree[node<<1|1]);
}
}
// merge function goes here...
static int[] merge(int[] left,int[] right)
{
int n=left.length+right.length;int[] ret=new int[n];
int ptr=0,i=0,j=0;
while(i<left.length || j<right.length)
{
if(i==left.length)
{
ret[ptr++]=right[j++];
}
else if(j==right.length)
{
ret[ptr++]=left[i++];
}
else if(left[i]<=right[j])
{
ret[ptr++]=left[i++];
}
else
{
ret[ptr++]=right[j++];
}
}
return ret;
}
// search function goes here...
static int searchLast(int[] arr,int val)
{
int low=0,high=arr.length-1;
while(low<high)
{
int mid=(low+high+1)>>1;
if(arr[mid]<=val)
{
low=mid;
}
else
{
high=mid-1;
}
}
return (arr.length>0 && arr[low]<=val?arr[low]:-1);
}
// query function is here...
static int query(int node,int s,int e,int l,int r,int val)
{
if(s>e || l>e || r<s)
{
return Integer.MAX_VALUE;
}
if(l<=s && r>=e)
{
return searchLast(tree[node],val);
}
else
{
int mid=(s+e)>>1;
return Math.min(query(node<<1,s,mid,l,r,val),query(node<<1|1,mid+1,e,l,r,val));
}
}
public static void main(String args[]) throws Exception
{
int n=sc.nextInt();tree=new int[n][];
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | UTF-8 | Java | 2,637 | java | segment_tree_vector.java | Java | [] | null | [] | import java.io.*;
import java.util.*;
import java.math.*;
import java.util.concurrent.*;
public final class segment_tree_vector
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static int[][] tree;
static void build(int node,int s,int e)
{
if(s>e)
{
return;
}
if(s==e)
{
tree[node]=new int[]{10};
}
else
{
int mid=(s+e)>>1;
build(node<<1,s,mid);build(node<<1|1,mid+1,e);
tree[node]=merge(tree[node<<1],tree[node<<1|1]);
}
}
// merge function goes here...
static int[] merge(int[] left,int[] right)
{
int n=left.length+right.length;int[] ret=new int[n];
int ptr=0,i=0,j=0;
while(i<left.length || j<right.length)
{
if(i==left.length)
{
ret[ptr++]=right[j++];
}
else if(j==right.length)
{
ret[ptr++]=left[i++];
}
else if(left[i]<=right[j])
{
ret[ptr++]=left[i++];
}
else
{
ret[ptr++]=right[j++];
}
}
return ret;
}
// search function goes here...
static int searchLast(int[] arr,int val)
{
int low=0,high=arr.length-1;
while(low<high)
{
int mid=(low+high+1)>>1;
if(arr[mid]<=val)
{
low=mid;
}
else
{
high=mid-1;
}
}
return (arr.length>0 && arr[low]<=val?arr[low]:-1);
}
// query function is here...
static int query(int node,int s,int e,int l,int r,int val)
{
if(s>e || l>e || r<s)
{
return Integer.MAX_VALUE;
}
if(l<=s && r>=e)
{
return searchLast(tree[node],val);
}
else
{
int mid=(s+e)>>1;
return Math.min(query(node<<1,s,mid,l,r,val),query(node<<1|1,mid+1,e,l,r,val));
}
}
public static void main(String args[]) throws Exception
{
int n=sc.nextInt();tree=new int[n][];
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | 2,637 | 0.573758 | 0.564278 | 152 | 16.355263 | 18.496233 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.144737 | false | false | 4 |
0324b0799f036dc26bc38382b1a347cfde368a1d | 18,416,819,819,138 | 08bffbddebf2ac5fbdf57d5dd28567d902576e92 | /module/service/src/main/java/com/jsmscp/dr/service/ApiOperateLogService.java | 40d21f867b5bcd10e43c7be70b82adc62f415c0f | [] | no_license | yangzeyu/drugstore | https://github.com/yangzeyu/drugstore | 14e2d7525237031a9abd1c858dc86274da8329f0 | 56bc2e0c1c2070e4ae1bdf2440c8c5b8fd9c417e | refs/heads/master | 2020-05-07T17:56:02.960000 | 2019-04-11T08:21:04 | 2019-04-11T08:21:04 | 180,746,959 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jsmscp.dr.service;
import java.util.HashMap;
public interface ApiOperateLogService {
HashMap<String, Object> list(String operator, String url, String status, String startTime, String endTime,
Integer pageNo);
}
| UTF-8 | Java | 246 | java | ApiOperateLogService.java | Java | [] | null | [] | package com.jsmscp.dr.service;
import java.util.HashMap;
public interface ApiOperateLogService {
HashMap<String, Object> list(String operator, String url, String status, String startTime, String endTime,
Integer pageNo);
}
| 246 | 0.731707 | 0.731707 | 8 | 29.75 | 33.829536 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 4 |
9a431ea02d07480740d5a332b90fe8b554e6404d | 1,211,180,819,505 | 70b549a945729fb94bc209571a65d0e987f3d984 | /activiti/tags/activiti-5.0.beta1/modules/activiti-cycle/src/main/java/org/activiti/cycle/ContentType.java | bae163ce2c72c933c6d4785d33a2d4de65d9d76e | [] | no_license | tmehre/activiti | https://github.com/tmehre/activiti | b24c10d3d91c21d52d6c2663e8a6a21310073efc | fa3811b06f205e791305c21a5a3544c8f4d30846 | refs/heads/master | 2017-12-11T22:57:47.394000 | 2012-09-20T19:07:04 | 2012-09-20T19:07:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.activiti.cycle;
/**
* Constants for types of content that can be linked.
*
* Do NOT use an enum to keep the types extensible without touching the core
* code.
*
* TODO: Add MimeTypes?
*
* @author bernd.ruecker@camunda.com
*/
public class ContentType {
public static final String PNG = "image/png";
public static final String GIF = "image/gif";
public static final String JPEG = "image/jpeg"; // or use "image/jpeg;charset=ISO-8859-1" ?
public static final String XML = "application/xml";
public static final String HTML = "text/html";
public static final String TEXT = "text/plain";
public static final String PDF = "application/pdf";
public static final String JSON = "application/json;charset=UTF-8";
public static final String MS_WORD = "application/msword";
public static final String MS_POWERPOINT = "application/powerpoint";
public static final String MS_EXCEL = "application/excel";
}
| UTF-8 | Java | 966 | java | ContentType.java | Java | [
{
"context": "de.\r\n * \r\n * TODO: Add MimeTypes?\r\n * \r\n * @author bernd.ruecker@camunda.com\r\n */\r\npublic class ContentType {\r\n\r\n\tpublic stati",
"end": 255,
"score": 0.9999188184738159,
"start": 230,
"tag": "EMAIL",
"value": "bernd.ruecker@camunda.com"
}
] | null | [] | package org.activiti.cycle;
/**
* Constants for types of content that can be linked.
*
* Do NOT use an enum to keep the types extensible without touching the core
* code.
*
* TODO: Add MimeTypes?
*
* @author <EMAIL>
*/
public class ContentType {
public static final String PNG = "image/png";
public static final String GIF = "image/gif";
public static final String JPEG = "image/jpeg"; // or use "image/jpeg;charset=ISO-8859-1" ?
public static final String XML = "application/xml";
public static final String HTML = "text/html";
public static final String TEXT = "text/plain";
public static final String PDF = "application/pdf";
public static final String JSON = "application/json;charset=UTF-8";
public static final String MS_WORD = "application/msword";
public static final String MS_POWERPOINT = "application/powerpoint";
public static final String MS_EXCEL = "application/excel";
}
| 948 | 0.702899 | 0.696687 | 27 | 33.777779 | 28.009699 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 4 |
ae03498b0b189ea47f5aee54e9f18a1398b593ff | 1,211,180,819,873 | f33479b8e4d2113895976b697b83ef7778d42c1f | /longlian-live/src/main/java/com/longlian/live/controller/LlAccountTrackController.java | 7667a41a3f62137cb31237a4cc281bcd83e3a9a4 | [] | no_license | liuhan/longlian | https://github.com/liuhan/longlian | 61f69f7b5b8759414458d65fca24690624ebcec8 | 90a6c31035ef76d3bf148f41a06de9c6c84e59a2 | refs/heads/master | 2020-02-27T13:09:26.298000 | 2017-10-05T15:06:10 | 2017-10-05T15:06:10 | 101,279,517 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.longlian.live.controller;
import com.longlian.util.constant.CecurityConst;
import com.longlian.dto.ActResultDto;
import com.longlian.live.service.LlAccountTrackService;
import com.longlian.token.AppUserIdentity;
import com.longlian.type.ReturnMessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
/**
* Created by admin on 2017/4/29.
*/
@RequestMapping("/llAccountTrack")
@Controller
public class LlAccountTrackController {
private static Logger log = LoggerFactory.getLogger(LlAccountTrackController.class);
@Autowired
LlAccountTrackService llAccountTrackService;
/**
* 我的钱包收支明细 --- llaccount 新版 学币
*
* @param request
* @return
*/
@RequestMapping(value = "/getWalletsPage.user", method = RequestMethod.POST)
@ResponseBody
public ActResultDto getWalletsPageNew(HttpServletRequest request,Integer pageSize , Integer offset) {
ActResultDto result = new ActResultDto();
AppUserIdentity token = (AppUserIdentity) request.getAttribute(CecurityConst.REQUEST_USER_ATTR);
List<Map> list = llAccountTrackService.getWalletsPage(token.getId(), pageSize, offset);
if(list.size()>0){
result.setCode(ReturnMessageType.CODE_MESSAGE_TRUE.getCode());
result.setMessage(ReturnMessageType.CODE_MESSAGE_TRUE.getMessage());
result.setData(list);
}else{
result.setCode(ReturnMessageType.NO_DATA.getCode());
result.setMessage(ReturnMessageType.NO_DATA.getMessage());
}
return result;
}
/**
* 我的课程收益(详情:谁正常购买,谁通过分销购买)
* @param request
* @param courseId 课程ID
* @param pageSize
* @param offset
* @return
*/
@RequestMapping(value = "/findMyCourseProfit.user")
@ResponseBody
public ActResultDto findMyCourseProfit(HttpServletRequest request , Long courseId ,
Integer pageSize , Integer offset){
AppUserIdentity token = (AppUserIdentity) request.getAttribute(CecurityConst.REQUEST_USER_ATTR);
return llAccountTrackService.findMyCourseProfit(courseId,pageSize,offset,token.getId());
}
}
| UTF-8 | Java | 2,639 | java | LlAccountTrackController.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by admin on 2017/4/29.\n */\n@RequestMapping(\"/llAccountTrac",
"end": 741,
"score": 0.9977073669433594,
"start": 736,
"tag": "USERNAME",
"value": "admin"
}
] | null | [] | package com.longlian.live.controller;
import com.longlian.util.constant.CecurityConst;
import com.longlian.dto.ActResultDto;
import com.longlian.live.service.LlAccountTrackService;
import com.longlian.token.AppUserIdentity;
import com.longlian.type.ReturnMessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
/**
* Created by admin on 2017/4/29.
*/
@RequestMapping("/llAccountTrack")
@Controller
public class LlAccountTrackController {
private static Logger log = LoggerFactory.getLogger(LlAccountTrackController.class);
@Autowired
LlAccountTrackService llAccountTrackService;
/**
* 我的钱包收支明细 --- llaccount 新版 学币
*
* @param request
* @return
*/
@RequestMapping(value = "/getWalletsPage.user", method = RequestMethod.POST)
@ResponseBody
public ActResultDto getWalletsPageNew(HttpServletRequest request,Integer pageSize , Integer offset) {
ActResultDto result = new ActResultDto();
AppUserIdentity token = (AppUserIdentity) request.getAttribute(CecurityConst.REQUEST_USER_ATTR);
List<Map> list = llAccountTrackService.getWalletsPage(token.getId(), pageSize, offset);
if(list.size()>0){
result.setCode(ReturnMessageType.CODE_MESSAGE_TRUE.getCode());
result.setMessage(ReturnMessageType.CODE_MESSAGE_TRUE.getMessage());
result.setData(list);
}else{
result.setCode(ReturnMessageType.NO_DATA.getCode());
result.setMessage(ReturnMessageType.NO_DATA.getMessage());
}
return result;
}
/**
* 我的课程收益(详情:谁正常购买,谁通过分销购买)
* @param request
* @param courseId 课程ID
* @param pageSize
* @param offset
* @return
*/
@RequestMapping(value = "/findMyCourseProfit.user")
@ResponseBody
public ActResultDto findMyCourseProfit(HttpServletRequest request , Long courseId ,
Integer pageSize , Integer offset){
AppUserIdentity token = (AppUserIdentity) request.getAttribute(CecurityConst.REQUEST_USER_ATTR);
return llAccountTrackService.findMyCourseProfit(courseId,pageSize,offset,token.getId());
}
}
| 2,639 | 0.721509 | 0.71762 | 70 | 35.728573 | 30.255541 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.585714 | false | false | 4 |
9ffd32d89f0f35c8701ab43cdccdff33ac035bab | 34,119,220,206,367 | 3d8bf6aabf5658a657e73f33103a5c249e5ff7f3 | /app/src/main/java/com/example/roren/auctioncast/activities/activity_faceDetection.java | 3474a9e325f494534583c64795d56309bc3f49bc | [] | no_license | rorents12/AuctionCast | https://github.com/rorents12/AuctionCast | 2461622d429af035a7c2c2245a31cb5bcf36509e | b51942d60b01ac6049b1b74850f7e5c22f754fa5 | refs/heads/master | 2020-03-22T01:08:26.247000 | 2018-09-08T20:36:56 | 2018-09-08T20:36:56 | 139,285,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.roren.auctioncast.activities;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.example.roren.auctioncast.FaceDetection.CameraSourcePreview;
import com.example.roren.auctioncast.FaceDetection.FaceGraphic;
import com.example.roren.auctioncast.FaceDetection.GraphicOverlay;
import com.example.roren.auctioncast.R;
import com.example.roren.auctioncast.utility.utility_global_variable;
import com.example.roren.auctioncast.utility.utility_http_uploadImage;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class activity_faceDetection extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "FaceTracker";
// 카메라 화면을 관리하는 CameraSource 변수
private CameraSource mCameraSource = null;
// 카메라로부터 받아온 화면을 그려 사용자에게 보여주는 CameraSourcePreview 변수
private CameraSourcePreview mPreview;
// CameraSourcePreview 에서 인식한 얼굴 위에 마스크를 그려주는 GraphicOverlay 변수
private GraphicOverlay mGraphicOverlay;
// GMS 코드
private static final int RC_HANDLE_GMS = 9001;
// 사진 촬영 버튼 - 이 버튼을 통해 CameraSourcePreview 의 화면을 비트맵으로 변환한다.
// 확인 버튼 - 이 버튼을 통해 찍은 사진을 서버로 전송하여 프로필 사진을 변경한다.
private Button button_photo, button_confirm;
// 사진을 촬영했을 때 찍힌 사진을 보여주는 ImageView
private ImageView imageView_result;
// 사진 촬영 버튼을 통해 변환된 비트맵을 저장하는 변수
private Bitmap result;
// 사진 촬영 버튼을 눌렀을 때 호출되는 callback method.
// shutterCallback - 셔터 소리를 내주는 콜백메소드
// pictureCallback - 찍힌 사진을 bytes array 로 변환하여 처리하는 콜백메소드
private CameraSource.ShutterCallback shutterCallback;
private CameraSource.PictureCallback pictureCallback;
// 얼굴 인식을 한 후 해당 얼굴에 씌울 마스크를 나타내는 ImageView
// 이들 중 하나를 터치하면 해당 마스크를 선택할 수 있다.
private ImageView imageView_pica, imageView_evee, imageView_naon, imageView_thor, imageView_mask;
// 특정 마스크를 선택하면 해당 마스크의 번호를 저장하는 변수
// 이 변수를 통해 화면에 그릴 마스크를 결정한다.
private int maskIndex;
private String imagePath;
/**--------------------------------------------------------------------------------------------
* 각종 화면 UI의 변수를 초기화 하는 onCreate.
----------------------------------------------------------------------------------------------*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_facedetection);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
button_photo = findViewById(R.id.activity_faceDetection_button_photo);
button_confirm = findViewById(R.id.activity_faceDetection_button_confirm);
button_photo.setOnClickListener(this);
button_confirm.setOnClickListener(this);
imageView_result = findViewById(R.id.facedetect_image);
imageView_pica = findViewById(R.id.activity_faceDetection_imageView_pica);
imageView_evee = findViewById(R.id.activity_faceDetection_imageView_evee);
imageView_naon = findViewById(R.id.activity_faceDetection_imageView_naon);
imageView_thor = findViewById(R.id.activity_faceDetection_imageView_thor);
imageView_mask = findViewById(R.id.activity_faceDetection_imageView_mask);
imageView_pica.setOnClickListener(this);
imageView_evee.setOnClickListener(this);
imageView_naon.setOnClickListener(this);
imageView_thor.setOnClickListener(this);
imageView_mask.setOnClickListener(this);
// ----------------------------------------------------------------------------------------
// maskIndex 의 초기값은 global variable 에 정의되어 있고, 앱이 시작될 때 이 값은
// AR_CAMERA_MASK_INDEX_PICA 와 같다.
// ----------------------------------------------------------------------------------------
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_DEFAULT;
// ----------------------------------------------------------------------------------------
// CameraSource 의 takePicture 함수를 호출하면 호출되는 shutterCallback 메소드
// PictureCallback 메소드가 호출되기 전에 호출되므로, 찍힌 사진을 처리하기 전에 어떠한 행동을
// 할것인지 정의한다. 기본적으로 셔텨 소리가 나도록 구현되어있다.
// ----------------------------------------------------------------------------------------
shutterCallback = new CameraSource.ShutterCallback() {
@Override
public void onShutter() {
}
};
// ----------------------------------------------------------------------------------------
// CameraSource 의 takePicture 함수를 호출하면 호출되는 pictureCallback 메소드
// 내부의 onPictureTaken 이라는 메소드를 통해 byte 배열로 된 사진 이미지를 처리할 수 있다.
//
// 최종적으로 마스크가 씌워진 사진을 나타내려면, CameraSource 에서 가져온 사진과 Overlay 된
// 사진을 겹쳐서 보여줘야 한다.
// 따라서 byte 배열로 된 사진 위에 가면을 그려내어야 한다.
// ----------------------------------------------------------------------------------------
pictureCallback = new CameraSource.PictureCallback() {
@Override
public void onPictureTaken(byte[] bytes) {
// byte 배열을 비트맵으로 변환
result = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// 사진의 회전값을 맞추기 위해 Matrix 변수 선언
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(-90);
// 사진의 좌우반전을 맞추기 위해 Matrix 변수 선언
Matrix sideInversionMatrix = new Matrix();
sideInversionMatrix.setScale(-1,1);
// 사진의 회전값과 좌우반전을 적용하여 새로운 비트맵 생성
result = Bitmap.createBitmap(result, 0,0, result.getWidth(), result.getHeight(), rotateMatrix, false);
result = Bitmap.createBitmap(result, 0,0, result.getWidth(), result.getHeight(), sideInversionMatrix, false);
// 사진을 미리볼 수 있는 imageView 에 결과 비트맵을 삽입
imageView_result.setImageBitmap(result);
// CameraSourcePreView 의 캡쳐를 통해 현재 화면에 나타난 마스크를 비트맵으로 변환
Bitmap mask = Bitmap.createScaledBitmap(mPreview.capture(), result.getWidth(), result.getHeight(), false);
// CameraSource 에서 가져온 사진의 bitmap 위에 마스크를 그려낸다.
Canvas canvas = new Canvas(result);
Rect rect = new Rect(0,0,mask.getWidth(), mask.getHeight());
canvas.drawBitmap(mask,null,rect, null);
// 카메라 화면을 숨기고, 결과 이미지뷰의 Visibility 를 Visible 로 처리한다.
mPreview.setVisibility(View.GONE);
imageView_result.setVisibility(View.VISIBLE);
}
};
// 카메라 화면을 초기화한다.
createCameraSource();
}
/**--------------------------------------------------------------------------------------------
* 촬영과 확인버튼, 그리고 각 마스크들을 나타내는 ImageView 들의 클릭이벤트를 정의한다.
----------------------------------------------------------------------------------------------*/
@Override
public void onClick(View view) {
switch (view.getId()){
// ------------------------------------------------------------------------------------
// 촬영 버튼
//
// 버튼의 text 를 확인하여 '촬영' 일 때는 촬영을, '다시 찍기' 일때는 다시찍기 기능을
// 수행한다.
// ------------------------------------------------------------------------------------
case R.id.activity_faceDetection_button_photo:
// 촬영버튼의 text 확인
String text = button_photo.getText().toString();
if(text.equals("촬영")){
// 버튼의 text 가 '촬영' 일때
button_photo.setText("다시 찍기");
mCameraSource.takePicture(shutterCallback, pictureCallback);
button_confirm.setVisibility(View.VISIBLE);
}else if(text.equals("다시 찍기")){
// 버튼의 text 가 '다시 찍기' 일때
// 현재 사용하고 있는 마스크의 번호를 global variable 에 저장
utility_global_variable.AR_CAMERA_MASK_INDEX_DEFAULT = maskIndex;
// 액티비티 재시작
this.recreate();
}
break;
// ------------------------------------------------------------------------------------
// 확인 버튼
//
// 버튼을 누르면, 찍힌 사진을 서버로 전송한 후 프로필사진을 변경한다.
// ------------------------------------------------------------------------------------
case R.id.activity_faceDetection_button_confirm:
File storage = this.getFilesDir();
String fileName = System.currentTimeMillis() + "tempCapture.jpg";
File tempFile = new File(storage, fileName);
try{
tempFile.createNewFile();
FileOutputStream out = new FileOutputStream(tempFile, false);
result.compress(Bitmap.CompressFormat.JPEG, 50, out);
out.close();
}catch (Exception e){
e.printStackTrace();
}
imagePath = tempFile.getAbsolutePath();
new utility_http_uploadImage(this, imagePath).execute();
break;
// ------------------------------------------------------------------------------------
// 마스크 이미지뷰
//
// 각 마스크 이미지를 누르면 maskIndex 를 해당 마스크의 index 로 변경하고,
// CameraSource 를 새로 시작한다.
// ------------------------------------------------------------------------------------
case R.id.activity_faceDetection_imageView_pica:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_PICA;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_evee:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_EVEE;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_naon:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_NAON;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_thor:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_THOR;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_mask:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_MASK;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
}
}
/**--------------------------------------------------------------------------------------------
* CameraSource 를 만들고 시작한다.
----------------------------------------------------------------------------------------------*/
private void createCameraSource() {
Context context = getApplicationContext();
// 얼굴 인식을 수행할 FaceDetector 생성
FaceDetector detector = new FaceDetector.Builder(context)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.ACCURATE_MODE)
.build();
// FaceDetector 의 Processor 를 정의
detector.setProcessor(
new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory())
.build());
// detector 사용 가능여부 체크
if (!detector.isOperational()) {
// 이 앱이 처음 Face Detector API 를 사용한다면, GMS 가 face detection 에 필요한 native
// library 를 다운로드 할 것이다. 보통은 앱이 실행되기 전에 이 다운로드가 끝날 것이지만,
// 그렇지 않았을 경우에는 detector 가 얼굴 인식 기능을 수행할 수 없다. isOperational()
// 함수를 통해 다운로드 완료 여부를 체크한다.
Log.w(TAG, "Face detector dependencies are not yet available.");
}
// CameraSource 생성
mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(640, 480)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
}
/**--------------------------------------------------------------------------------------------
* onResume 콜백메소드 호출 시, CameraSource 를 재시작한다.
----------------------------------------------------------------------------------------------*/
@Override
protected void onResume() {
super.onResume();
startCameraSource();
}
/**--------------------------------------------------------------------------------------------
* onPause 콜백메소드 호출 시, CameraSource 를 멈춘다.
----------------------------------------------------------------------------------------------*/
@Override
protected void onPause() {
super.onPause();
mPreview.stop();
}
/**--------------------------------------------------------------------------------------------
* onDestroy 콜백메소드 호출 시, CameraSource 를 release 한다.
----------------------------------------------------------------------------------------------*/
@Override
protected void onDestroy() {
super.onDestroy();
if (mCameraSource != null) {
mCameraSource.release();
}
}
/**--------------------------------------------------------------------------------------------
* 생성된 CameraSource 를 시작한다.
* 카메라 화면을 CameraSourcePreview 에 출력한다.
----------------------------------------------------------------------------------------------*/
private void startCameraSource() {
// 디바이스가 google play services 를 사용가능한지 체크
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
mCameraSource.release();
mCameraSource = null;
}
}
}
/**--------------------------------------------------------------------------------------------
* 새로운 얼굴이 화면에 나타났을 때, 새로운 FaceTracker 를 생성해주는 FaceTracker Factory 클래스
----------------------------------------------------------------------------------------------*/
private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
@Override
public Tracker<Face> create(Face face) {
return new GraphicFaceTracker(mGraphicOverlay, maskIndex);
}
}
/**--------------------------------------------------------------------------------------------
* 인식된 얼굴을 추적하는 FaceTracker 클래스
----------------------------------------------------------------------------------------------*/
private class GraphicFaceTracker extends Tracker<Face> {
private GraphicOverlay mOverlay;
private FaceGraphic mFaceGraphic;
GraphicFaceTracker(GraphicOverlay overlay, int maskIndex) {
mOverlay = overlay;
mFaceGraphic = new FaceGraphic(overlay, maskIndex);
}
// ----------------------------------------------------------------------------------------
// 얼굴을 찾아냈을 때, FaceGraphic 객체에 해당 얼굴을 등록한다.
// ----------------------------------------------------------------------------------------
@Override
public void onNewItem(int faceId, Face item) {
mFaceGraphic.setId(faceId);
}
// ----------------------------------------------------------------------------------------
// 얼굴 위치가 변경될 때 해당 변경사항을 FaceGraphic 객체에 업데이트 한다.
// ----------------------------------------------------------------------------------------
@Override
public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
mOverlay.add(mFaceGraphic);
mFaceGraphic.updateFace(face);
}
// ----------------------------------------------------------------------------------------
// Tracking 하던 얼굴이 사라졌을 때, 해당 얼굴 정보를 FaceGraphic 객체에서 삭제한다.
// ----------------------------------------------------------------------------------------
@Override
public void onMissing(FaceDetector.Detections<Face> detectionResults) {
mOverlay.remove(mFaceGraphic);
}
// ----------------------------------------------------------------------------------------
// Tracking 이 종료되면, 해당 얼굴 정보를 FaceGraphic 객체에서 삭제한다.
// ----------------------------------------------------------------------------------------
@Override
public void onDone() {
mOverlay.remove(mFaceGraphic);
}
}
}
| UTF-8 | Java | 20,580 | java | activity_faceDetection.java | Java | [] | null | [] | package com.example.roren.auctioncast.activities;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.example.roren.auctioncast.FaceDetection.CameraSourcePreview;
import com.example.roren.auctioncast.FaceDetection.FaceGraphic;
import com.example.roren.auctioncast.FaceDetection.GraphicOverlay;
import com.example.roren.auctioncast.R;
import com.example.roren.auctioncast.utility.utility_global_variable;
import com.example.roren.auctioncast.utility.utility_http_uploadImage;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class activity_faceDetection extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "FaceTracker";
// 카메라 화면을 관리하는 CameraSource 변수
private CameraSource mCameraSource = null;
// 카메라로부터 받아온 화면을 그려 사용자에게 보여주는 CameraSourcePreview 변수
private CameraSourcePreview mPreview;
// CameraSourcePreview 에서 인식한 얼굴 위에 마스크를 그려주는 GraphicOverlay 변수
private GraphicOverlay mGraphicOverlay;
// GMS 코드
private static final int RC_HANDLE_GMS = 9001;
// 사진 촬영 버튼 - 이 버튼을 통해 CameraSourcePreview 의 화면을 비트맵으로 변환한다.
// 확인 버튼 - 이 버튼을 통해 찍은 사진을 서버로 전송하여 프로필 사진을 변경한다.
private Button button_photo, button_confirm;
// 사진을 촬영했을 때 찍힌 사진을 보여주는 ImageView
private ImageView imageView_result;
// 사진 촬영 버튼을 통해 변환된 비트맵을 저장하는 변수
private Bitmap result;
// 사진 촬영 버튼을 눌렀을 때 호출되는 callback method.
// shutterCallback - 셔터 소리를 내주는 콜백메소드
// pictureCallback - 찍힌 사진을 bytes array 로 변환하여 처리하는 콜백메소드
private CameraSource.ShutterCallback shutterCallback;
private CameraSource.PictureCallback pictureCallback;
// 얼굴 인식을 한 후 해당 얼굴에 씌울 마스크를 나타내는 ImageView
// 이들 중 하나를 터치하면 해당 마스크를 선택할 수 있다.
private ImageView imageView_pica, imageView_evee, imageView_naon, imageView_thor, imageView_mask;
// 특정 마스크를 선택하면 해당 마스크의 번호를 저장하는 변수
// 이 변수를 통해 화면에 그릴 마스크를 결정한다.
private int maskIndex;
private String imagePath;
/**--------------------------------------------------------------------------------------------
* 각종 화면 UI의 변수를 초기화 하는 onCreate.
----------------------------------------------------------------------------------------------*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_facedetection);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
button_photo = findViewById(R.id.activity_faceDetection_button_photo);
button_confirm = findViewById(R.id.activity_faceDetection_button_confirm);
button_photo.setOnClickListener(this);
button_confirm.setOnClickListener(this);
imageView_result = findViewById(R.id.facedetect_image);
imageView_pica = findViewById(R.id.activity_faceDetection_imageView_pica);
imageView_evee = findViewById(R.id.activity_faceDetection_imageView_evee);
imageView_naon = findViewById(R.id.activity_faceDetection_imageView_naon);
imageView_thor = findViewById(R.id.activity_faceDetection_imageView_thor);
imageView_mask = findViewById(R.id.activity_faceDetection_imageView_mask);
imageView_pica.setOnClickListener(this);
imageView_evee.setOnClickListener(this);
imageView_naon.setOnClickListener(this);
imageView_thor.setOnClickListener(this);
imageView_mask.setOnClickListener(this);
// ----------------------------------------------------------------------------------------
// maskIndex 의 초기값은 global variable 에 정의되어 있고, 앱이 시작될 때 이 값은
// AR_CAMERA_MASK_INDEX_PICA 와 같다.
// ----------------------------------------------------------------------------------------
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_DEFAULT;
// ----------------------------------------------------------------------------------------
// CameraSource 의 takePicture 함수를 호출하면 호출되는 shutterCallback 메소드
// PictureCallback 메소드가 호출되기 전에 호출되므로, 찍힌 사진을 처리하기 전에 어떠한 행동을
// 할것인지 정의한다. 기본적으로 셔텨 소리가 나도록 구현되어있다.
// ----------------------------------------------------------------------------------------
shutterCallback = new CameraSource.ShutterCallback() {
@Override
public void onShutter() {
}
};
// ----------------------------------------------------------------------------------------
// CameraSource 의 takePicture 함수를 호출하면 호출되는 pictureCallback 메소드
// 내부의 onPictureTaken 이라는 메소드를 통해 byte 배열로 된 사진 이미지를 처리할 수 있다.
//
// 최종적으로 마스크가 씌워진 사진을 나타내려면, CameraSource 에서 가져온 사진과 Overlay 된
// 사진을 겹쳐서 보여줘야 한다.
// 따라서 byte 배열로 된 사진 위에 가면을 그려내어야 한다.
// ----------------------------------------------------------------------------------------
pictureCallback = new CameraSource.PictureCallback() {
@Override
public void onPictureTaken(byte[] bytes) {
// byte 배열을 비트맵으로 변환
result = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// 사진의 회전값을 맞추기 위해 Matrix 변수 선언
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(-90);
// 사진의 좌우반전을 맞추기 위해 Matrix 변수 선언
Matrix sideInversionMatrix = new Matrix();
sideInversionMatrix.setScale(-1,1);
// 사진의 회전값과 좌우반전을 적용하여 새로운 비트맵 생성
result = Bitmap.createBitmap(result, 0,0, result.getWidth(), result.getHeight(), rotateMatrix, false);
result = Bitmap.createBitmap(result, 0,0, result.getWidth(), result.getHeight(), sideInversionMatrix, false);
// 사진을 미리볼 수 있는 imageView 에 결과 비트맵을 삽입
imageView_result.setImageBitmap(result);
// CameraSourcePreView 의 캡쳐를 통해 현재 화면에 나타난 마스크를 비트맵으로 변환
Bitmap mask = Bitmap.createScaledBitmap(mPreview.capture(), result.getWidth(), result.getHeight(), false);
// CameraSource 에서 가져온 사진의 bitmap 위에 마스크를 그려낸다.
Canvas canvas = new Canvas(result);
Rect rect = new Rect(0,0,mask.getWidth(), mask.getHeight());
canvas.drawBitmap(mask,null,rect, null);
// 카메라 화면을 숨기고, 결과 이미지뷰의 Visibility 를 Visible 로 처리한다.
mPreview.setVisibility(View.GONE);
imageView_result.setVisibility(View.VISIBLE);
}
};
// 카메라 화면을 초기화한다.
createCameraSource();
}
/**--------------------------------------------------------------------------------------------
* 촬영과 확인버튼, 그리고 각 마스크들을 나타내는 ImageView 들의 클릭이벤트를 정의한다.
----------------------------------------------------------------------------------------------*/
@Override
public void onClick(View view) {
switch (view.getId()){
// ------------------------------------------------------------------------------------
// 촬영 버튼
//
// 버튼의 text 를 확인하여 '촬영' 일 때는 촬영을, '다시 찍기' 일때는 다시찍기 기능을
// 수행한다.
// ------------------------------------------------------------------------------------
case R.id.activity_faceDetection_button_photo:
// 촬영버튼의 text 확인
String text = button_photo.getText().toString();
if(text.equals("촬영")){
// 버튼의 text 가 '촬영' 일때
button_photo.setText("다시 찍기");
mCameraSource.takePicture(shutterCallback, pictureCallback);
button_confirm.setVisibility(View.VISIBLE);
}else if(text.equals("다시 찍기")){
// 버튼의 text 가 '다시 찍기' 일때
// 현재 사용하고 있는 마스크의 번호를 global variable 에 저장
utility_global_variable.AR_CAMERA_MASK_INDEX_DEFAULT = maskIndex;
// 액티비티 재시작
this.recreate();
}
break;
// ------------------------------------------------------------------------------------
// 확인 버튼
//
// 버튼을 누르면, 찍힌 사진을 서버로 전송한 후 프로필사진을 변경한다.
// ------------------------------------------------------------------------------------
case R.id.activity_faceDetection_button_confirm:
File storage = this.getFilesDir();
String fileName = System.currentTimeMillis() + "tempCapture.jpg";
File tempFile = new File(storage, fileName);
try{
tempFile.createNewFile();
FileOutputStream out = new FileOutputStream(tempFile, false);
result.compress(Bitmap.CompressFormat.JPEG, 50, out);
out.close();
}catch (Exception e){
e.printStackTrace();
}
imagePath = tempFile.getAbsolutePath();
new utility_http_uploadImage(this, imagePath).execute();
break;
// ------------------------------------------------------------------------------------
// 마스크 이미지뷰
//
// 각 마스크 이미지를 누르면 maskIndex 를 해당 마스크의 index 로 변경하고,
// CameraSource 를 새로 시작한다.
// ------------------------------------------------------------------------------------
case R.id.activity_faceDetection_imageView_pica:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_PICA;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_evee:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_EVEE;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_naon:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_NAON;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_thor:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_THOR;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
case R.id.activity_faceDetection_imageView_mask:
maskIndex = utility_global_variable.AR_CAMERA_MASK_INDEX_MASK;
createCameraSource();
mPreview.stop();
startCameraSource();
break;
}
}
/**--------------------------------------------------------------------------------------------
* CameraSource 를 만들고 시작한다.
----------------------------------------------------------------------------------------------*/
private void createCameraSource() {
Context context = getApplicationContext();
// 얼굴 인식을 수행할 FaceDetector 생성
FaceDetector detector = new FaceDetector.Builder(context)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.ACCURATE_MODE)
.build();
// FaceDetector 의 Processor 를 정의
detector.setProcessor(
new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory())
.build());
// detector 사용 가능여부 체크
if (!detector.isOperational()) {
// 이 앱이 처음 Face Detector API 를 사용한다면, GMS 가 face detection 에 필요한 native
// library 를 다운로드 할 것이다. 보통은 앱이 실행되기 전에 이 다운로드가 끝날 것이지만,
// 그렇지 않았을 경우에는 detector 가 얼굴 인식 기능을 수행할 수 없다. isOperational()
// 함수를 통해 다운로드 완료 여부를 체크한다.
Log.w(TAG, "Face detector dependencies are not yet available.");
}
// CameraSource 생성
mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(640, 480)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
}
/**--------------------------------------------------------------------------------------------
* onResume 콜백메소드 호출 시, CameraSource 를 재시작한다.
----------------------------------------------------------------------------------------------*/
@Override
protected void onResume() {
super.onResume();
startCameraSource();
}
/**--------------------------------------------------------------------------------------------
* onPause 콜백메소드 호출 시, CameraSource 를 멈춘다.
----------------------------------------------------------------------------------------------*/
@Override
protected void onPause() {
super.onPause();
mPreview.stop();
}
/**--------------------------------------------------------------------------------------------
* onDestroy 콜백메소드 호출 시, CameraSource 를 release 한다.
----------------------------------------------------------------------------------------------*/
@Override
protected void onDestroy() {
super.onDestroy();
if (mCameraSource != null) {
mCameraSource.release();
}
}
/**--------------------------------------------------------------------------------------------
* 생성된 CameraSource 를 시작한다.
* 카메라 화면을 CameraSourcePreview 에 출력한다.
----------------------------------------------------------------------------------------------*/
private void startCameraSource() {
// 디바이스가 google play services 를 사용가능한지 체크
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
mCameraSource.release();
mCameraSource = null;
}
}
}
/**--------------------------------------------------------------------------------------------
* 새로운 얼굴이 화면에 나타났을 때, 새로운 FaceTracker 를 생성해주는 FaceTracker Factory 클래스
----------------------------------------------------------------------------------------------*/
private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
@Override
public Tracker<Face> create(Face face) {
return new GraphicFaceTracker(mGraphicOverlay, maskIndex);
}
}
/**--------------------------------------------------------------------------------------------
* 인식된 얼굴을 추적하는 FaceTracker 클래스
----------------------------------------------------------------------------------------------*/
private class GraphicFaceTracker extends Tracker<Face> {
private GraphicOverlay mOverlay;
private FaceGraphic mFaceGraphic;
GraphicFaceTracker(GraphicOverlay overlay, int maskIndex) {
mOverlay = overlay;
mFaceGraphic = new FaceGraphic(overlay, maskIndex);
}
// ----------------------------------------------------------------------------------------
// 얼굴을 찾아냈을 때, FaceGraphic 객체에 해당 얼굴을 등록한다.
// ----------------------------------------------------------------------------------------
@Override
public void onNewItem(int faceId, Face item) {
mFaceGraphic.setId(faceId);
}
// ----------------------------------------------------------------------------------------
// 얼굴 위치가 변경될 때 해당 변경사항을 FaceGraphic 객체에 업데이트 한다.
// ----------------------------------------------------------------------------------------
@Override
public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
mOverlay.add(mFaceGraphic);
mFaceGraphic.updateFace(face);
}
// ----------------------------------------------------------------------------------------
// Tracking 하던 얼굴이 사라졌을 때, 해당 얼굴 정보를 FaceGraphic 객체에서 삭제한다.
// ----------------------------------------------------------------------------------------
@Override
public void onMissing(FaceDetector.Detections<Face> detectionResults) {
mOverlay.remove(mFaceGraphic);
}
// ----------------------------------------------------------------------------------------
// Tracking 이 종료되면, 해당 얼굴 정보를 FaceGraphic 객체에서 삭제한다.
// ----------------------------------------------------------------------------------------
@Override
public void onDone() {
mOverlay.remove(mFaceGraphic);
}
}
}
| 20,580 | 0.490499 | 0.488961 | 424 | 41.943398 | 31.03599 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521226 | false | false | 4 |
aa6f598d9020eb6a61e941b2d9edde3b577367a5 | 34,119,220,206,585 | 76178d6e9c1ab4d8ca54367606d0a1e700fc7b6f | /src/doit/AboutDialog.java | 644c018b38db3e0596eb68cff7cb84549670b29b | [] | no_license | krokola/java_doit | https://github.com/krokola/java_doit | 4876bfdacf478e0562a2ae1c75639c125be67069 | 6664457a74c02c409d702a4239191422eb2fd509 | refs/heads/master | 2016-08-08T14:13:27.572000 | 2015-04-26T20:57:51 | 2015-04-26T20:57:51 | 34,630,547 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package doit;
import java.util.Vector;
import javax.swing.Timer;
import javax.swing.JLabel;
import java.io.*;
public class AboutDialog extends javax.swing.JDialog
{
private Vector<JLabel> credits;
private javax.swing.Timer timer;
private long lastTime;
public AboutDialog(java.awt.Frame parent, boolean modal, java.awt.Point location)
{
super(parent, modal);
initComponents();
setTitle("About");
setSize(321, 300);
setLocation((int)(location.getX() - getWidth() / 2), (int)(location.getY() - getHeight() / 2));
logoLbl.setOpaque(true);
logoLbl.setIcon(new javax.swing.ImageIcon(Library.makeColorTransparent(new javax.swing.ImageIcon(System.getProperty("user.dir") + "/Images/Logo.png").getImage(), java.awt.Color.white)));
credits = new Vector<JLabel>();
setForAbout();
timer = new javax.swing.Timer(25, new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
long now = System.currentTimeMillis() / 1000;
for (int i = 0; i < credits.size(); i++)
credits.get(i).setLocation(credits.get(i).getX(), credits.get(i).getY() - 1);
if (now - lastTime > 25)
timer.setDelay(25 - (int)(now - lastTime - 25));
else
timer.setDelay(25);
lastTime = now;
}
});
lastTime = System.currentTimeMillis() / 1000;
timer.start();
setVisible(true);
}
public void setForChangeLog() throws IOException
{
for (int i = 0; i < credits.size(); i++)
downPanel.remove(credits.get(i));
credits.removeAllElements();
repaint();
File file = new File(System.getProperty("user.dir") + "/ChangeLog.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String str = br.readLine();
while(str != null)
{
credits.add(new JLabel(str));
str = br.readLine();
}
br.close();
java.awt.Graphics g = this.getGraphics();
g.setFont(new java.awt.Font("Times New Roman", 0, 12));
for (int i = 0; i < credits.size(); i++)
{
credits.get(i).setFont(new java.awt.Font("Times New Roman", 0, 12));
credits.get(i).setForeground(new java.awt.Color(232, 232, 232));
credits.get(i).setSize((int)getWidth(), 18);
credits.get(i).setLocation((int)(getWidth() / 2 - g.getFontMetrics().stringWidth(credits.get(i).getText()) / 2), getHeight() + i * 18 - 90);
downPanel.add(credits.get(i));
}
}
public void setForAbout()
{
for (int i = 0; i < credits.size(); i++)
downPanel.remove(credits.get(i));
credits.removeAllElements();
repaint();
credits.add(new JLabel("Version 0.67b"));
credits.add(new JLabel(""));
credits.add(new JLabel("Designed, Inspired & Coded By"));
credits.add(new JLabel("Xatziioannou Konstantinos"));
credits.add(new JLabel(""));
credits.add(new JLabel("Tested By"));
credits.add(new JLabel("Tokalidis Xristos"));
credits.add(new JLabel(""));
credits.add(new JLabel("Special Thanks To"));
credits.add(new JLabel("Xarxalakis Stefanos"));
credits.add(new JLabel(""));
credits.add(new JLabel("Report Any Bugs At"));
credits.add(new JLabel("konxatz@it.teithe.gr"));
credits.add(new JLabel(""));
credits.add(new JLabel("This Program Is A Freeware"));
credits.add(new JLabel("Feel Free To Share With Friends"));
credits.add(new JLabel(""));
credits.add(new JLabel(""));
javax.swing.JLabel changeLogLbl = new JLabel("Click Here To See Changelog");
changeLogLbl.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseEntered(java.awt.event.MouseEvent evt)
{
((JLabel)(evt.getSource())).setForeground(java.awt.Color.blue);
timer.stop();
}
public void mouseExited(java.awt.event.MouseEvent evt)
{
((JLabel)(evt.getSource())).setForeground(java.awt.Color.white);
timer.start();
}
public void mouseClicked(java.awt.event.MouseEvent evt)
{
try
{
setForChangeLog();
timer.start();
}
catch(IOException ioe){}
}
});
credits.add(changeLogLbl);
java.awt.Graphics g = this.getGraphics();
for (int i = 0; i < credits.size(); i++)
{
credits.get(i).setFont(new java.awt.Font("Times New Roman", 0, 12));
credits.get(i).setForeground(new java.awt.Color(232, 232, 232));
credits.get(i).setSize((int)getWidth(), 18);
credits.get(i).setLocation((int)(getWidth() / 2) - (int)(g.getFontMetrics().stringWidth(credits.get(i).getText()) / 2), getHeight() + i * 18 - 90);
downPanel.add(credits.get(i));
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
upPanel = new javax.swing.JPanel();
logoLbl = new javax.swing.JLabel();
mainLbl = new javax.swing.JLabel();
line = new javax.swing.JPanel();
downPanel = new javax.swing.JPanel();
getContentPane().setLayout(null);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About");
setBackground(new java.awt.Color(235, 245, 255));
setMinimumSize(new java.awt.Dimension(385, 342));
setResizable(false);
upPanel.setLayout(null);
upPanel.setBackground(new java.awt.Color(0, 0, 0));
logoLbl.setBackground(new java.awt.Color(0, 0, 0));
logoLbl.setFont(new java.awt.Font("Arial", 0, 24));
upPanel.add(logoLbl);
logoLbl.setBounds(10, 10, 50, 50);
mainLbl.setFont(new java.awt.Font("Verdana", 0, 24));
mainLbl.setForeground(new java.awt.Color(232, 232, 232));
mainLbl.setText(" JAVA DoIT");
upPanel.add(mainLbl);
mainLbl.setBounds(86, 19, 222, 30);
javax.swing.GroupLayout lineLayout = new javax.swing.GroupLayout(line);
line.setLayout(lineLayout);
lineLayout.setHorizontalGroup(
lineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 250, Short.MAX_VALUE)
);
lineLayout.setVerticalGroup(
lineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1, Short.MAX_VALUE)
);
upPanel.add(line);
line.setBounds(70, 50, 250, 1);
getContentPane().add(upPanel);
upPanel.setBounds(0, 0, 385, 70);
downPanel.setLayout(null);
downPanel.setBackground(new java.awt.Color(0, 0, 0));
downPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
downPanelMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
downPanelMouseExited(evt);
}
});
getContentPane().add(downPanel);
downPanel.setBounds(0, 70, 385, 273);
pack();
}// </editor-fold>//GEN-END:initComponents
private void downPanelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_downPanelMouseExited
timer.start();
}//GEN-LAST:event_downPanelMouseExited
private void downPanelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_downPanelMouseEntered
timer.stop();
}//GEN-LAST:event_downPanelMouseEntered
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel downPanel;
private javax.swing.JPanel line;
private javax.swing.JLabel logoLbl;
private javax.swing.JLabel mainLbl;
private javax.swing.JPanel upPanel;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 9,046 | java | AboutDialog.java | Java | [
{
"context": "d & Coded By\"));\r\n credits.add(new JLabel(\"Xatziioannou Konstantinos\"));\r\n credits.add(new JLabel(\"\")); ",
"end": 3360,
"score": 0.9998584985733032,
"start": 3335,
"tag": "NAME",
"value": "Xatziioannou Konstantinos"
},
{
"context": "l(\"Tested By\"));\r\n credits.add(new JLabel(\"Tokalidis Xristos\"));\r\n credits.add(new JLabel(\"\")); ",
"end": 3508,
"score": 0.9998483061790466,
"start": 3491,
"tag": "NAME",
"value": "Tokalidis Xristos"
},
{
"context": "al Thanks To\"));\r\n credits.add(new JLabel(\"Xarxalakis Stefanos\"));\r\n credits.add(new JLabel(\"\"));\r\n ",
"end": 3666,
"score": 0.9998770356178284,
"start": 3647,
"tag": "NAME",
"value": "Xarxalakis Stefanos"
},
{
"context": " Any Bugs At\"));\r\n credits.add(new JLabel(\"konxatz@it.teithe.gr\"));\r\n credits.add(new JLabel(\"\"));\r\n ",
"end": 3818,
"score": 0.9999338388442993,
"start": 3798,
"tag": "EMAIL",
"value": "konxatz@it.teithe.gr"
}
] | null | [] | package doit;
import java.util.Vector;
import javax.swing.Timer;
import javax.swing.JLabel;
import java.io.*;
public class AboutDialog extends javax.swing.JDialog
{
private Vector<JLabel> credits;
private javax.swing.Timer timer;
private long lastTime;
public AboutDialog(java.awt.Frame parent, boolean modal, java.awt.Point location)
{
super(parent, modal);
initComponents();
setTitle("About");
setSize(321, 300);
setLocation((int)(location.getX() - getWidth() / 2), (int)(location.getY() - getHeight() / 2));
logoLbl.setOpaque(true);
logoLbl.setIcon(new javax.swing.ImageIcon(Library.makeColorTransparent(new javax.swing.ImageIcon(System.getProperty("user.dir") + "/Images/Logo.png").getImage(), java.awt.Color.white)));
credits = new Vector<JLabel>();
setForAbout();
timer = new javax.swing.Timer(25, new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
long now = System.currentTimeMillis() / 1000;
for (int i = 0; i < credits.size(); i++)
credits.get(i).setLocation(credits.get(i).getX(), credits.get(i).getY() - 1);
if (now - lastTime > 25)
timer.setDelay(25 - (int)(now - lastTime - 25));
else
timer.setDelay(25);
lastTime = now;
}
});
lastTime = System.currentTimeMillis() / 1000;
timer.start();
setVisible(true);
}
public void setForChangeLog() throws IOException
{
for (int i = 0; i < credits.size(); i++)
downPanel.remove(credits.get(i));
credits.removeAllElements();
repaint();
File file = new File(System.getProperty("user.dir") + "/ChangeLog.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String str = br.readLine();
while(str != null)
{
credits.add(new JLabel(str));
str = br.readLine();
}
br.close();
java.awt.Graphics g = this.getGraphics();
g.setFont(new java.awt.Font("Times New Roman", 0, 12));
for (int i = 0; i < credits.size(); i++)
{
credits.get(i).setFont(new java.awt.Font("Times New Roman", 0, 12));
credits.get(i).setForeground(new java.awt.Color(232, 232, 232));
credits.get(i).setSize((int)getWidth(), 18);
credits.get(i).setLocation((int)(getWidth() / 2 - g.getFontMetrics().stringWidth(credits.get(i).getText()) / 2), getHeight() + i * 18 - 90);
downPanel.add(credits.get(i));
}
}
public void setForAbout()
{
for (int i = 0; i < credits.size(); i++)
downPanel.remove(credits.get(i));
credits.removeAllElements();
repaint();
credits.add(new JLabel("Version 0.67b"));
credits.add(new JLabel(""));
credits.add(new JLabel("Designed, Inspired & Coded By"));
credits.add(new JLabel("<NAME>"));
credits.add(new JLabel(""));
credits.add(new JLabel("Tested By"));
credits.add(new JLabel("<NAME>"));
credits.add(new JLabel(""));
credits.add(new JLabel("Special Thanks To"));
credits.add(new JLabel("<NAME>"));
credits.add(new JLabel(""));
credits.add(new JLabel("Report Any Bugs At"));
credits.add(new JLabel("<EMAIL>"));
credits.add(new JLabel(""));
credits.add(new JLabel("This Program Is A Freeware"));
credits.add(new JLabel("Feel Free To Share With Friends"));
credits.add(new JLabel(""));
credits.add(new JLabel(""));
javax.swing.JLabel changeLogLbl = new JLabel("Click Here To See Changelog");
changeLogLbl.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseEntered(java.awt.event.MouseEvent evt)
{
((JLabel)(evt.getSource())).setForeground(java.awt.Color.blue);
timer.stop();
}
public void mouseExited(java.awt.event.MouseEvent evt)
{
((JLabel)(evt.getSource())).setForeground(java.awt.Color.white);
timer.start();
}
public void mouseClicked(java.awt.event.MouseEvent evt)
{
try
{
setForChangeLog();
timer.start();
}
catch(IOException ioe){}
}
});
credits.add(changeLogLbl);
java.awt.Graphics g = this.getGraphics();
for (int i = 0; i < credits.size(); i++)
{
credits.get(i).setFont(new java.awt.Font("Times New Roman", 0, 12));
credits.get(i).setForeground(new java.awt.Color(232, 232, 232));
credits.get(i).setSize((int)getWidth(), 18);
credits.get(i).setLocation((int)(getWidth() / 2) - (int)(g.getFontMetrics().stringWidth(credits.get(i).getText()) / 2), getHeight() + i * 18 - 90);
downPanel.add(credits.get(i));
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
upPanel = new javax.swing.JPanel();
logoLbl = new javax.swing.JLabel();
mainLbl = new javax.swing.JLabel();
line = new javax.swing.JPanel();
downPanel = new javax.swing.JPanel();
getContentPane().setLayout(null);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About");
setBackground(new java.awt.Color(235, 245, 255));
setMinimumSize(new java.awt.Dimension(385, 342));
setResizable(false);
upPanel.setLayout(null);
upPanel.setBackground(new java.awt.Color(0, 0, 0));
logoLbl.setBackground(new java.awt.Color(0, 0, 0));
logoLbl.setFont(new java.awt.Font("Arial", 0, 24));
upPanel.add(logoLbl);
logoLbl.setBounds(10, 10, 50, 50);
mainLbl.setFont(new java.awt.Font("Verdana", 0, 24));
mainLbl.setForeground(new java.awt.Color(232, 232, 232));
mainLbl.setText(" JAVA DoIT");
upPanel.add(mainLbl);
mainLbl.setBounds(86, 19, 222, 30);
javax.swing.GroupLayout lineLayout = new javax.swing.GroupLayout(line);
line.setLayout(lineLayout);
lineLayout.setHorizontalGroup(
lineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 250, Short.MAX_VALUE)
);
lineLayout.setVerticalGroup(
lineLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1, Short.MAX_VALUE)
);
upPanel.add(line);
line.setBounds(70, 50, 250, 1);
getContentPane().add(upPanel);
upPanel.setBounds(0, 0, 385, 70);
downPanel.setLayout(null);
downPanel.setBackground(new java.awt.Color(0, 0, 0));
downPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
downPanelMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
downPanelMouseExited(evt);
}
});
getContentPane().add(downPanel);
downPanel.setBounds(0, 70, 385, 273);
pack();
}// </editor-fold>//GEN-END:initComponents
private void downPanelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_downPanelMouseExited
timer.start();
}//GEN-LAST:event_downPanelMouseExited
private void downPanelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_downPanelMouseEntered
timer.stop();
}//GEN-LAST:event_downPanelMouseEntered
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel downPanel;
private javax.swing.JPanel line;
private javax.swing.JLabel logoLbl;
private javax.swing.JLabel mainLbl;
private javax.swing.JPanel upPanel;
// End of variables declaration//GEN-END:variables
}
| 8,990 | 0.562016 | 0.543887 | 235 | 36.493618 | 29.302439 | 194 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.817021 | false | false | 4 |
49da71bc95ecd7f2c4298f95b360bced3f5485f5 | 25,185,688,267,033 | 2b7599a4f8560e332e72ecfd24e0e6eaa8c4335c | /client/desktop/socketsJava/Conexion.java | 33ad2d6872c73fe472e6daa4f257f1bc6ab606c5 | [] | no_license | futotta-risu/deuZum | https://github.com/futotta-risu/deuZum | 3dabf92c89b7afce6b7ccf7b6039c95eb91ef7ec | b1edfd73e15a8a9b9984481dc8e0f5ed07839eb2 | refs/heads/master | 2021-07-09T00:29:25.744000 | 2020-01-12T22:42:19 | 2020-01-12T22:42:19 | 202,737,808 | 3 | 0 | null | false | 2020-10-13T18:00:11 | 2019-08-16T14:02:56 | 2020-01-13T00:50:22 | 2020-10-13T18:00:10 | 4,369 | 2 | 0 | 1 | Java | false | false | package socketsJava;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;
public class Conexion {
private final int PUERTO=1234;
private final String HOST="localhost";
protected String mesajeServidor;
protected ServerSocket ss;
protected Socket cs;
protected DataOutputStream salidaServidor;
public Conexion() {
}
/**
*Esto es un metodo que envia un socket al servido con un mensaje
* @param message Aqui va la accion a realizar por el servidor
*/
public void sendSocket() {
try {
cs = new Socket(HOST,PUERTO); // El server por ahora esta en un servidor local y el puerto CREO que es ese
PrintWriter writer = new PrintWriter(cs.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
// Para enviar un mensaje, una vez creado todo esto, nos basta con usar
writer.write("hola que tal");//TODO PREGUNTAR A ERIK
writer.close(); // Esto es para cerrar el escritor
}catch(Exception e) {
System.out.println("Error: "+ e.getMessage());
}
}
} | UTF-8 | Java | 1,275 | java | Conexion.java | Java | [] | null | [] | package socketsJava;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;
public class Conexion {
private final int PUERTO=1234;
private final String HOST="localhost";
protected String mesajeServidor;
protected ServerSocket ss;
protected Socket cs;
protected DataOutputStream salidaServidor;
public Conexion() {
}
/**
*Esto es un metodo que envia un socket al servido con un mensaje
* @param message Aqui va la accion a realizar por el servidor
*/
public void sendSocket() {
try {
cs = new Socket(HOST,PUERTO); // El server por ahora esta en un servidor local y el puerto CREO que es ese
PrintWriter writer = new PrintWriter(cs.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
// Para enviar un mensaje, una vez creado todo esto, nos basta con usar
writer.write("hola que tal");//TODO PREGUNTAR A ERIK
writer.close(); // Esto es para cerrar el escritor
}catch(Exception e) {
System.out.println("Error: "+ e.getMessage());
}
}
} | 1,275 | 0.744314 | 0.741176 | 48 | 25.583334 | 26.312096 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.416667 | false | false | 4 |
798dcbdb23df7912aaffae5a2a88d6183b996d65 | 5,188,320,507,885 | c308b4ff273ea624f4730e463a6b9a2888f6ee22 | /hw3/test.java | 2b78d0738094445c4f1c58967f29278af508aa2e | [] | no_license | alapha23/java | https://github.com/alapha23/java | 59f348ad3807296b46ae4f5c5a6f4602b967313e | 6085cbdfa9a48df26b16628a7704263367393425 | refs/heads/master | 2021-04-15T14:03:05.962000 | 2018-06-15T06:45:10 | 2018-06-15T06:45:10 | 126,258,255 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class test
{
public static void main(String args[])
{
int i=0;
String s = "FAFHBVJLDO";
for(;s.length()!=0;i++, s = s.substring(1, s.length()))
{
System.out.println(s);
}
}
}
| UTF-8 | Java | 194 | java | test.java | Java | [] | null | [] | class test
{
public static void main(String args[])
{
int i=0;
String s = "FAFHBVJLDO";
for(;s.length()!=0;i++, s = s.substring(1, s.length()))
{
System.out.println(s);
}
}
}
| 194 | 0.561856 | 0.546392 | 14 | 12.857142 | 16.872873 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.714286 | false | false | 4 |
3ad05e54dcd95daf98176de9ecdc6e50fb0c51a7 | 28,905,129,965,243 | ae9c45e6869847d21f041169955a6f23a619ae6a | /app/src/main/java/com/sdh/bigcity/Entity/BannerData.java | 8cec8fa5c1b8734196bd73f4ed0d509229caa5da | [] | no_license | Mugamo/BigCity | https://github.com/Mugamo/BigCity | bf52e4f237b3e74208f47f89a7731d02cf485352 | 542a06c24eddad53d45260ff0c96297425f4a0b1 | refs/heads/master | 2020-07-07T11:30:13.954000 | 2019-09-17T06:54:27 | 2019-09-17T06:54:27 | 203,327,218 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sdh.bigcity.Entity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;
public class BannerData implements Serializable {
String id,
image,
banner_type,
bannertitle,
status,
created_at,
updated_at;
String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id1) {
this.id = id1;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBanner_type() {
return banner_type;
}
public void setBanner_type(String banner_type) {
this.banner_type = banner_type;
}
public String getBannertitle() {
return bannertitle;
}
public void setBannertitle(String bannertitle) {
this.bannertitle = bannertitle;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public static List<BannerData> createListFromJson(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<BannerData>>() {
}.getType();
return gson.fromJson(json, type);
}
public static String createJsonFromList(List<BannerData> object) {
Gson gson = new Gson();
Type type = new TypeToken<BannerData>() {
}.getType();
return gson.toJson(object, type);
}
public static BannerData createobjectFromJson(String json) {
Gson gson = new Gson();
Type type = new TypeToken<BannerData>() {
}.getType();
return gson.fromJson(json, type);
}
public static String createjsonFromObject(BannerData banner) {
Gson gson = new Gson();
Type type = new TypeToken<BannerData>() {
}.getType();
return gson.toJson(banner, type);
}
}
| UTF-8 | Java | 2,549 | java | BannerData.java | Java | [] | null | [] | package com.sdh.bigcity.Entity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;
public class BannerData implements Serializable {
String id,
image,
banner_type,
bannertitle,
status,
created_at,
updated_at;
String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id1) {
this.id = id1;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBanner_type() {
return banner_type;
}
public void setBanner_type(String banner_type) {
this.banner_type = banner_type;
}
public String getBannertitle() {
return bannertitle;
}
public void setBannertitle(String bannertitle) {
this.bannertitle = bannertitle;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public static List<BannerData> createListFromJson(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<BannerData>>() {
}.getType();
return gson.fromJson(json, type);
}
public static String createJsonFromList(List<BannerData> object) {
Gson gson = new Gson();
Type type = new TypeToken<BannerData>() {
}.getType();
return gson.toJson(object, type);
}
public static BannerData createobjectFromJson(String json) {
Gson gson = new Gson();
Type type = new TypeToken<BannerData>() {
}.getType();
return gson.fromJson(json, type);
}
public static String createjsonFromObject(BannerData banner) {
Gson gson = new Gson();
Type type = new TypeToken<BannerData>() {
}.getType();
return gson.toJson(banner, type);
}
}
| 2,549 | 0.601412 | 0.600628 | 111 | 21.963964 | 18.914663 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414414 | false | false | 4 |
c721143042b7a8b1bb2d6236bc4f8bba895d4199 | 7,997,229,154,924 | 6296a1014bc736c9cf80525f6e51290b19008419 | /RinconGloton/src/bbdd/BD_Usuarios.java | 53682a50f5447ea29d25d900109a094186da73b8 | [] | no_license | el-rincon-gloton/Rinc-n-Glot-n | https://github.com/el-rincon-gloton/Rinc-n-Glot-n | bdfcdc81e59a0c5174c1fe3b1fd094431408dee3 | 03392ac21b7bbcbe8aa59077be2bad30e3ee7632 | refs/heads/master | 2020-05-07T08:02:42.111000 | 2019-05-16T19:31:46 | 2019-05-16T19:31:46 | 180,304,027 | 1 | 0 | null | false | 2019-05-16T19:31:47 | 2019-04-09T06:53:54 | 2019-05-13T11:00:24 | 2019-05-16T19:31:47 | 32 | 1 | 0 | 0 | Java | false | false | /**
*
*/
package bbdd;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.Vector;
import modelos.BloqueadaException;
import modelos.Carta;
import modelos.Empleados;
import modelos.Gastos;
import modelos.Orden;
import modelos.PedidoProducto;
import modelos.Producto;
import modelos.Proveedores;
import modelos.Ventas;
/**
* @author j.caballero
*
*/
public class BD_Usuarios extends BD_Conector {
private static Statement s;
private static ResultSet reg;
public BD_Usuarios() {
super();
// TODO Auto-generated constructor stub
}
/**
* funcion para comprobar que los datos del login sean correctos y para logearse
*
* @param nombre
* @param contraseņa
* @return String para comporbar el login
*/
public String login(String nombre, String contraseņa) {
String cadena = "SELECT Oficio FROM usuarios WHERE Login LIKE '" + nombre + "' AND Password LIKE '" + contraseņa
+ "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next())
t = reg.getString(1);
s.close();
this.cerrar();
return t;
} catch (SQLException e) {
return null;
}
}
/**
* funcion para aņadir un nuevo cliente
*
* @param nombreUsu
* @param nombre
* @param apellido
* @param correo
* @param contraseņa
* @return int para comporbar que se ha insertado la linea
*/
public int aņadir(String nombreUsu, String nombre, String apellido, String correo, String contraseņa) {
String cadena = "INSERT INTO cliente VALUES('" + nombreUsu + "','" + nombre + "','" + apellido + "','" + correo
+ "','" + contraseņa + "','" + 0 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para comporbar que se ha insertado el empleado
*
* @param nombreUsu
* @param nombre
* @param apellido
* @param correo
* @param contraseņa
* @return int para comporbar que se ha insertado la linea
*/
public int aņadirEmpleado(String nombreUsu, String nombre, String apellido, String correo, String contraseņa) {
String cadena = "INSERT INTO cliente VALUES('" + nombreUsu + "','" + nombre + "','" + apellido + "','" + correo
+ "','" + contraseņa + "','" + 0 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion que comprueba que el usuario y una contraseņa correspondan
* correctamente a un empleado
*
* @param nombre
* @param contraseņa
* @return int para comprobar que se ha obtenido algun valor de la select
*/
public int comporbarContraseņaclientes(String nombre, String contraseņa) {
String cadena = "SELECT * FROM cliente WHERE Ident_usuario LIKE '" + nombre + "' AND Contraseņa LIKE '"
+ contraseņa + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comporbar que el usuario y la contraseņa introducidad
* corresponden a un usuario
*
* @param nombre
* @param contraseņa
* @return int para comprobar que se ha obtenido algun valor de la select
*/
public int comporbarContraseņaUsuarios(String nombre, String contraseņa) {
String cadena = "SELECT * FROM usuarios WHERE Login LIKE '" + nombre + "' AND Password LIKE '" + contraseņa
+ "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* metodo para comporbar si un empleado es un cocinero
*
* @param nombre
* @param contraseņa
* @return int para comprobar que la select devuelve un dato
*/
public int comporbarCocinero(String nombre, String contraseņa) {
String cargo = "cocinero";
String cadena = "SELECT * FROM empleados WHERE Cod_Emple LIKE '" + nombre + "' AND Cargo_en_la_empresa LIKE '"
+ cargo + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comprobar que un numero de proveedor es correcto
*
* @param cod_prov
* @return int para comrpobar que la select devuelve algun dato
*/
public int comporbarCodProv(String cod_prov) {
String cadena = "SELECT * FROM proveedores WHERE Cod_prov LIKE '" + cod_prov + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funion para comprobar que la contraseņa y el usuario corresponde a un
* empleado
*
* @param nombre
* @param contraseņa
* @return int para comprobar que el select ha devuelve un valor
*/
public int comporbarContraseņaEmpleados(String nombre, String contraseņa) {
String cadena = "SELECT * FROM empleados WHERE Cod_Emple LIKE '" + nombre + "' AND contraseņa LIKE '"
+ contraseņa + "' AND encargado LIKE '" + 0 + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comprobar que el usuario es un encargado
*
* @param nombre
* @param contraseņa
* @return int para comporbar que la select devuelve algun valor
*/
public int comporbarContraseņaEncargado(String nombre, String contraseņa) {
String cadena = "SELECT * FROM empleados WHERE Cod_Emple LIKE '" + nombre + "' AND contraseņa LIKE '"
+ contraseņa + "' AND encargado LIKE '" + 1 + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comprobar que la cuenta este bloqueada
*
* @param nombre
* @return int para comporbar que la select devuelve algun valor
* @throws BloqueadaException
*/
public int mostrarbloq(String nombre) throws BloqueadaException {
int pp = 0;
String cadena = "SELECT bloqueada FROM cliente WHERE Ident_usuario LIKE '" + nombre + "';";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
if (reg.getInt("bloqueada") == 1) {
throw new BloqueadaException("no se puede retirar dinero por que la tarjeta esta bloqueada");
}
}
s.close();
this.cerrar();
return pp;
} catch (SQLException e) {
return 0;
}
}
/**
* funcion para bloquear una cuenta por exceso de fallos al introducir la
* contraseņa
*
* @param nombre
* @return int para comprobar que se ha ejecutado el update
*/
public int bloquear(String nombre) {
String cadena = "UPDATE cliente SET bloqueada =" + 1 + " WHERE Ident_usuario LIKE '" + nombre + "'";
try {
this.abrir();
s = c.createStatement();
int filas = s.executeUpdate(cadena);
s.close();
this.cerrar();
return 1;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion que devuelve los pedidos de los productos de la base de datos
*
* @return Vector con la ionformacion de los pedidos de los productos
*/
public Vector<PedidoProducto> mostrarPedidosProductos() {
Vector<PedidoProducto> v = new Vector<PedidoProducto>();
String cadena = "SELECT * FROM pedidos_productos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new PedidoProducto(reg.getString("ident_producto"), reg.getString("Cod_Prov"),
reg.getString("Cod_emple"), reg.getDouble("Gastos"), reg.getDate("Fecha_encargo").toLocalDate(),
reg.getInt("cantidad"), reg.getInt("Cod_Pedido")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que devuelve los proveedores de la base de datos
*
* @return Vector con la informacion de los proveedores de la base de datos
*/
public Vector<Proveedores> mostrarProveedores() {
Vector<Proveedores> v = new Vector<Proveedores>();
String cadena = "SELECT * FROM proveedores";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Proveedores(reg.getString("cod_prov"), reg.getString("nombre_prov"),
reg.getString("apellido_prov"), reg.getString("direccion"), reg.getInt("telefono")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que devuelve la informacion sobre los encargados
*
* @return Vector con los datos de los encargados
*/
public Vector<Empleados> mostrarEnacrgados() {
Vector<Empleados> v = new Vector<Empleados>();
String cadena = "SELECT * FROM empleados WHERE encargado LIKE '" + 1 + "'";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Empleados(reg.getString("Cod_Emple"), reg.getString("Nombre"), reg.getString("Apellido"),
reg.getString("DNI"), reg.getString("Direccion"), reg.getInt("Telefono"),
reg.getInt("Num_seguridad_social"), reg.getString("Cargo_en_la_empresa"),
reg.getInt("encargado")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra la informacion de los empleados
*
* @return Vector con los datos de los empleados de la base de datos
*/
public Vector<Empleados> mostrarEmpleados() {
Vector<Empleados> v = new Vector<Empleados>();
String cadena = "SELECT * FROM empleados";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Empleados(reg.getString("Cod_Emple"), reg.getString("Nombre"), reg.getString("Apellido"),
reg.getString("DNI"), reg.getString("Direccion"), reg.getInt("Telefono"),
reg.getInt("Num_seguridad_social"), reg.getString("Cargo_en_la_empresa"),
reg.getInt("encargado")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* ´ funcion que muestra los productos que estan disponibles
*
* @return Vector con los datos de los productos
*/
public Vector<Producto> mostrarProductos() {
Vector<Producto> v = new Vector<Producto>();
String cadena = "SELECT * FROM productos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Producto(reg.getString("Ident_producto"), reg.getString("Cod_prov"),
reg.getDate("Fecha_entrega").toLocalDate(), reg.getDate("Fecha_caducidad").toLocalDate(),
reg.getDouble("Coste"), reg.getString("Cod_emple"), reg.getInt("cantidad")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra el stock disponible de nuestros productos
*
* @return Vector que guarda los datos del stock de los productos
*/
public Vector<Producto> mostrarStock() {
Vector<Producto> v = new Vector<Producto>();
String cadena = "SELECT * FROM productos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Producto(reg.getString("Ident_producto"), reg.getInt("cantidad")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra la carta disponible de la aplicacion
*
* @return Vector con la carta disponible en el momento y todos sus datos
*/
public Vector<Carta> mostrarCarta() {
Vector<Carta> v = new Vector<Carta>();
String cadena = "SELECT * FROM carta";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Carta(reg.getString("nombre_producto"), reg.getDouble("precio_unidad")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion para eliminar pedidos de productos
*
* @param cod
* @return int para comporbar que se ha realizado el delete
*/
public int borrarPedidoProducto(int cod) {
String cadena = "DELETE FROM pedidos_productos WHERE Cod_pedido ='" + cod + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para eliminar un proveedor
*
* @param codProv
* @return int para comprobar que se ha eliminado el proveedor
*/
public int borrarProveedor(String codProv) {
String cadena = "DELETE FROM proveedores WHERE Cod_prov ='" + codProv + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para aņadir un pedido de un producto
*
* @param Ident_Producto
* @param Cod_Prov
* @param Cod_emple
* @param Gastos
* @param cantidad
* @return int para comporbar que se ha insertado el pedido del producto
*/
public int aņadirPedido_producto(String Ident_Producto, String Cod_Prov, String Cod_emple, Double Gastos,
int cantidad) {
String cadena = "INSERT INTO pedidos_productos (Ident_Producto,Cod_Prov,Cod_emple,Gastos,Fecha_encargo,cantidad) VALUES('"
+ Ident_Producto + "','" + Cod_Prov + "','" + Cod_emple + "','" + Gastos + "','" + LocalDate.now()
+ "','" + cantidad + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para modificar la informacion de los proveedores
*
* @param dato
* @param variable2
* @param codigo
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarProveedor(String dato, String variable2, String codigo) {
String cadena = "UPDATE proveedores SET " + dato + " = '" + variable2 + "' WHERE Cod_prov LIKE '" + codigo
+ "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para modificar la informacion de lo empleados
*
* @param dato
* @param variable2
* @param codigo
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarEmpleados(String dato, String variable2, String codigo) {
String cadena = "UPDATE empleados SET " + dato + " = '" + variable2 + "' WHERE Cod_Emple LIKE '" + codigo + "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* ´ funcion para modificar el telefono de los empleados
*
* @param dato
* @param variable2
* @param codigo
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarTelefonoEMpleados(String dato, int variable2, String codigo) {
String cadena = "UPDATE empleados SET " + dato + " = '" + variable2 + "' WHERE Cod_Emple LIKE '" + codigo + "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para modificar el telefono de los proveedores
*
* @param codigo
* @param telefonoModificado
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarProveedorTelefono(String codigo, int telefonoModificado) {
String cadena = "UPDATE proveedores SET Telefono = '" + telefonoModificado + "' WHERE Cod_prov LIKE '" + codigo
+ "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para aņadir un empleado a la base de datos
*
* @param cod_emp
* @param nombre
* @param apellido
* @param dni
* @param direccion
* @param telefono
* @param numSegSocial
* @param cargo
* @param contraseņa
* @return int para comporbar que se ha insertado el emplado correctamente
*/
public int aņadirEmpleado(String cod_emp, String nombre, String apellido, String dni, String direccion,
int telefono, int numSegSocial, String cargo, String contraseņa) {
String cadena = "INSERT INTO empleados VALUES('" + cod_emp + "','" + nombre + "','" + apellido + "','" + dni
+ "','" + direccion + "','" + telefono + "','" + numSegSocial + "','" + cargo + "','" + contraseņa
+ "','" + 0 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para aņadir un proveedor a la base de datos
*
* @param cod_prov
* @param nombre
* @param apellido
* @param direccion
* @param telefono
* @return int para comprobar que se ha aņadido el proveedor
*/
public int aņadirProveedor(String cod_prov, String nombre, String apellido, String direccion, int telefono) {
String cadena = "INSERT INTO proveedores VALUES('" + cod_prov + "','" + nombre + "','" + apellido + "','"
+ direccion + "','" + telefono + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para eliminar un empleado de la base de datos
*
* @param cod_Emp
* @return int para comporbar que se ha eliminado el empleado
*/
public int borrarEmpleado(String cod_Emp) {
String cadena = "DELETE FROM empleados WHERE Cod_Emple ='" + cod_Emp + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* ´ funcion para aņadir una orden a la base de datos
*
* @param cod_empleado
* @param precio
* @param direccion
* @param p1
* @param p2
* @param p3
* @param p4
* @param p5
* @return int para comporbar que se ha aņadido la orden
*/
public int aņadirOrden(String cod_empleado, double precio, String direccion, int p1, int p2, int p3, int p4,
int p5) {
String cadena = "INSERT INTO orden (Cod_emple,Precio,Direccion,producto1,producto2,producto3,producto4,producto5) VALUES('"
+ cod_empleado + "','" + precio + "','" + direccion + "','" + p1 + "','" + p2 + "','" + p3 + "','" + p4
+ "','" + p5 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para mostrar las ordenes de la base de datos
*
* @return Vector con la informacion de las ordenes
*/
public Vector<Orden> mostrarOrden() {
Vector<Orden> v = new Vector<Orden>();
String cadena = "SELECT * FROM orden";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Orden(reg.getString("Cod_orden"), reg.getString("Cod_emple"), reg.getDouble("Precio"),
reg.getString("Direccion"), reg.getInt("producto1"), reg.getInt("producto2"),
reg.getInt("producto3"), reg.getInt("producto4"), reg.getInt("producto5")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion para modificar la informacion de los clientes
*
* @param dato
* @param variable2
* @param codigo
* @return int para comprobar que se ha realizado el update
*/
public int modificarCliente(String dato, String variable2, String codigo) {
String cadena = "UPDATE cliente SET " + dato + " = '" + variable2 + "' WHERE Ident_usuario LIKE '" + codigo
+ "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 0;
}
s.close();
return 1;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para desbloquear la cuenta de un cliente
*
* @param codigo
* @return int para comporbar que se ha ejecutado el update
*/
public int desbloquearCliente(String codigo) {
String cadena = "UPDATE cliente SET bloqueada = '" + 0 + "' WHERE Ident_usuario LIKE '" + codigo + "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para eliminar una orden de la base de datos
*
* @param cod_Emp
* @return int para comporbar que se ha ejecutado la orden
*/
public int borrarOrden(String cod_Emp) {
String cadena = "DELETE FROM orden WHERE Cod_orden ='" + cod_Emp + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
this.cerrar();
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para aņadir un gasto a la base de datos
*
* @param descripcion
* @param importe
* @return int para comprobar que se ha realizado el insert
*/
public int aņadirGasto(String descripcion, double importe) {
String cadena = "INSERT INTO gastos (descripcion_gasto,importe) VALUES('" + descripcion + "','" + importe
+ "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para obtener la informacion de los gastos de la base de datos
*
* @return Vector con la informacion de los gastos
*/
public Vector<Gastos> mostrarGastos() {
Vector<Gastos> v = new Vector<Gastos>();
String cadena = "SELECT * FROM gastos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Gastos(reg.getDate("fecha_gastos").toLocalDate(), reg.getString("descripcion_gasto"),
reg.getInt("cod_gasto"), reg.getDouble("importe")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra la informacion de las ventas de la base de datos
*
* @return Vector con los datos de las ventas
*/
public Vector<Ventas> mostrarVentas() {
Vector<Ventas> v = new Vector<Ventas>();
String cadena = "SELECT * FROM Ventas";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Ventas(reg.getDouble("beneficios"), reg.getInt("cod_orden"), reg.getInt("Cod_venta"),
reg.getDate("fecha_venta").toLocalDate()));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
}
| ISO-8859-4 | Java | 26,044 | java | BD_Usuarios.java | Java | [
{
"context": "edores;\r\nimport modelos.Ventas;\r\n\r\n/**\r\n * @author j.caballero\r\n *\r\n */\r\npublic class BD_Usuarios extends BD_Con",
"end": 449,
"score": 0.9958140254020691,
"start": 438,
"tag": "USERNAME",
"value": "j.caballero"
},
{
"context": "al introducir la\r\n\t * contraseņa\r\n\t * \r\n\t * @param nombre\r\n\t * @return int para comprobar que se ha ejecuta",
"end": 7918,
"score": 0.6464606523513794,
"start": 7912,
"tag": "NAME",
"value": "nombre"
},
{
"context": "se de datos\r\n\t * \r\n\t * @param cod_prov\r\n\t * @param nombre\r\n\t * @param apellido\r\n\t * @param direccion\r\n\t * @",
"end": 19359,
"score": 0.5411204099655151,
"start": 19353,
"tag": "NAME",
"value": "nombre"
}
] | null | [] | /**
*
*/
package bbdd;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.Vector;
import modelos.BloqueadaException;
import modelos.Carta;
import modelos.Empleados;
import modelos.Gastos;
import modelos.Orden;
import modelos.PedidoProducto;
import modelos.Producto;
import modelos.Proveedores;
import modelos.Ventas;
/**
* @author j.caballero
*
*/
public class BD_Usuarios extends BD_Conector {
private static Statement s;
private static ResultSet reg;
public BD_Usuarios() {
super();
// TODO Auto-generated constructor stub
}
/**
* funcion para comprobar que los datos del login sean correctos y para logearse
*
* @param nombre
* @param contraseņa
* @return String para comporbar el login
*/
public String login(String nombre, String contraseņa) {
String cadena = "SELECT Oficio FROM usuarios WHERE Login LIKE '" + nombre + "' AND Password LIKE '" + contraseņa
+ "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next())
t = reg.getString(1);
s.close();
this.cerrar();
return t;
} catch (SQLException e) {
return null;
}
}
/**
* funcion para aņadir un nuevo cliente
*
* @param nombreUsu
* @param nombre
* @param apellido
* @param correo
* @param contraseņa
* @return int para comporbar que se ha insertado la linea
*/
public int aņadir(String nombreUsu, String nombre, String apellido, String correo, String contraseņa) {
String cadena = "INSERT INTO cliente VALUES('" + nombreUsu + "','" + nombre + "','" + apellido + "','" + correo
+ "','" + contraseņa + "','" + 0 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para comporbar que se ha insertado el empleado
*
* @param nombreUsu
* @param nombre
* @param apellido
* @param correo
* @param contraseņa
* @return int para comporbar que se ha insertado la linea
*/
public int aņadirEmpleado(String nombreUsu, String nombre, String apellido, String correo, String contraseņa) {
String cadena = "INSERT INTO cliente VALUES('" + nombreUsu + "','" + nombre + "','" + apellido + "','" + correo
+ "','" + contraseņa + "','" + 0 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion que comprueba que el usuario y una contraseņa correspondan
* correctamente a un empleado
*
* @param nombre
* @param contraseņa
* @return int para comprobar que se ha obtenido algun valor de la select
*/
public int comporbarContraseņaclientes(String nombre, String contraseņa) {
String cadena = "SELECT * FROM cliente WHERE Ident_usuario LIKE '" + nombre + "' AND Contraseņa LIKE '"
+ contraseņa + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comporbar que el usuario y la contraseņa introducidad
* corresponden a un usuario
*
* @param nombre
* @param contraseņa
* @return int para comprobar que se ha obtenido algun valor de la select
*/
public int comporbarContraseņaUsuarios(String nombre, String contraseņa) {
String cadena = "SELECT * FROM usuarios WHERE Login LIKE '" + nombre + "' AND Password LIKE '" + contraseņa
+ "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* metodo para comporbar si un empleado es un cocinero
*
* @param nombre
* @param contraseņa
* @return int para comprobar que la select devuelve un dato
*/
public int comporbarCocinero(String nombre, String contraseņa) {
String cargo = "cocinero";
String cadena = "SELECT * FROM empleados WHERE Cod_Emple LIKE '" + nombre + "' AND Cargo_en_la_empresa LIKE '"
+ cargo + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comprobar que un numero de proveedor es correcto
*
* @param cod_prov
* @return int para comrpobar que la select devuelve algun dato
*/
public int comporbarCodProv(String cod_prov) {
String cadena = "SELECT * FROM proveedores WHERE Cod_prov LIKE '" + cod_prov + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funion para comprobar que la contraseņa y el usuario corresponde a un
* empleado
*
* @param nombre
* @param contraseņa
* @return int para comprobar que el select ha devuelve un valor
*/
public int comporbarContraseņaEmpleados(String nombre, String contraseņa) {
String cadena = "SELECT * FROM empleados WHERE Cod_Emple LIKE '" + nombre + "' AND contraseņa LIKE '"
+ contraseņa + "' AND encargado LIKE '" + 0 + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comprobar que el usuario es un encargado
*
* @param nombre
* @param contraseņa
* @return int para comporbar que la select devuelve algun valor
*/
public int comporbarContraseņaEncargado(String nombre, String contraseņa) {
String cadena = "SELECT * FROM empleados WHERE Cod_Emple LIKE '" + nombre + "' AND contraseņa LIKE '"
+ contraseņa + "' AND encargado LIKE '" + 1 + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
if (reg.next()) {
t = reg.getString(1);
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para comprobar que la cuenta este bloqueada
*
* @param nombre
* @return int para comporbar que la select devuelve algun valor
* @throws BloqueadaException
*/
public int mostrarbloq(String nombre) throws BloqueadaException {
int pp = 0;
String cadena = "SELECT bloqueada FROM cliente WHERE Ident_usuario LIKE '" + nombre + "';";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
if (reg.getInt("bloqueada") == 1) {
throw new BloqueadaException("no se puede retirar dinero por que la tarjeta esta bloqueada");
}
}
s.close();
this.cerrar();
return pp;
} catch (SQLException e) {
return 0;
}
}
/**
* funcion para bloquear una cuenta por exceso de fallos al introducir la
* contraseņa
*
* @param nombre
* @return int para comprobar que se ha ejecutado el update
*/
public int bloquear(String nombre) {
String cadena = "UPDATE cliente SET bloqueada =" + 1 + " WHERE Ident_usuario LIKE '" + nombre + "'";
try {
this.abrir();
s = c.createStatement();
int filas = s.executeUpdate(cadena);
s.close();
this.cerrar();
return 1;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion que devuelve los pedidos de los productos de la base de datos
*
* @return Vector con la ionformacion de los pedidos de los productos
*/
public Vector<PedidoProducto> mostrarPedidosProductos() {
Vector<PedidoProducto> v = new Vector<PedidoProducto>();
String cadena = "SELECT * FROM pedidos_productos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new PedidoProducto(reg.getString("ident_producto"), reg.getString("Cod_Prov"),
reg.getString("Cod_emple"), reg.getDouble("Gastos"), reg.getDate("Fecha_encargo").toLocalDate(),
reg.getInt("cantidad"), reg.getInt("Cod_Pedido")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que devuelve los proveedores de la base de datos
*
* @return Vector con la informacion de los proveedores de la base de datos
*/
public Vector<Proveedores> mostrarProveedores() {
Vector<Proveedores> v = new Vector<Proveedores>();
String cadena = "SELECT * FROM proveedores";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Proveedores(reg.getString("cod_prov"), reg.getString("nombre_prov"),
reg.getString("apellido_prov"), reg.getString("direccion"), reg.getInt("telefono")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que devuelve la informacion sobre los encargados
*
* @return Vector con los datos de los encargados
*/
public Vector<Empleados> mostrarEnacrgados() {
Vector<Empleados> v = new Vector<Empleados>();
String cadena = "SELECT * FROM empleados WHERE encargado LIKE '" + 1 + "'";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Empleados(reg.getString("Cod_Emple"), reg.getString("Nombre"), reg.getString("Apellido"),
reg.getString("DNI"), reg.getString("Direccion"), reg.getInt("Telefono"),
reg.getInt("Num_seguridad_social"), reg.getString("Cargo_en_la_empresa"),
reg.getInt("encargado")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra la informacion de los empleados
*
* @return Vector con los datos de los empleados de la base de datos
*/
public Vector<Empleados> mostrarEmpleados() {
Vector<Empleados> v = new Vector<Empleados>();
String cadena = "SELECT * FROM empleados";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Empleados(reg.getString("Cod_Emple"), reg.getString("Nombre"), reg.getString("Apellido"),
reg.getString("DNI"), reg.getString("Direccion"), reg.getInt("Telefono"),
reg.getInt("Num_seguridad_social"), reg.getString("Cargo_en_la_empresa"),
reg.getInt("encargado")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* ´ funcion que muestra los productos que estan disponibles
*
* @return Vector con los datos de los productos
*/
public Vector<Producto> mostrarProductos() {
Vector<Producto> v = new Vector<Producto>();
String cadena = "SELECT * FROM productos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Producto(reg.getString("Ident_producto"), reg.getString("Cod_prov"),
reg.getDate("Fecha_entrega").toLocalDate(), reg.getDate("Fecha_caducidad").toLocalDate(),
reg.getDouble("Coste"), reg.getString("Cod_emple"), reg.getInt("cantidad")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra el stock disponible de nuestros productos
*
* @return Vector que guarda los datos del stock de los productos
*/
public Vector<Producto> mostrarStock() {
Vector<Producto> v = new Vector<Producto>();
String cadena = "SELECT * FROM productos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Producto(reg.getString("Ident_producto"), reg.getInt("cantidad")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra la carta disponible de la aplicacion
*
* @return Vector con la carta disponible en el momento y todos sus datos
*/
public Vector<Carta> mostrarCarta() {
Vector<Carta> v = new Vector<Carta>();
String cadena = "SELECT * FROM carta";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Carta(reg.getString("nombre_producto"), reg.getDouble("precio_unidad")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion para eliminar pedidos de productos
*
* @param cod
* @return int para comporbar que se ha realizado el delete
*/
public int borrarPedidoProducto(int cod) {
String cadena = "DELETE FROM pedidos_productos WHERE Cod_pedido ='" + cod + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para eliminar un proveedor
*
* @param codProv
* @return int para comprobar que se ha eliminado el proveedor
*/
public int borrarProveedor(String codProv) {
String cadena = "DELETE FROM proveedores WHERE Cod_prov ='" + codProv + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para aņadir un pedido de un producto
*
* @param Ident_Producto
* @param Cod_Prov
* @param Cod_emple
* @param Gastos
* @param cantidad
* @return int para comporbar que se ha insertado el pedido del producto
*/
public int aņadirPedido_producto(String Ident_Producto, String Cod_Prov, String Cod_emple, Double Gastos,
int cantidad) {
String cadena = "INSERT INTO pedidos_productos (Ident_Producto,Cod_Prov,Cod_emple,Gastos,Fecha_encargo,cantidad) VALUES('"
+ Ident_Producto + "','" + Cod_Prov + "','" + Cod_emple + "','" + Gastos + "','" + LocalDate.now()
+ "','" + cantidad + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para modificar la informacion de los proveedores
*
* @param dato
* @param variable2
* @param codigo
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarProveedor(String dato, String variable2, String codigo) {
String cadena = "UPDATE proveedores SET " + dato + " = '" + variable2 + "' WHERE Cod_prov LIKE '" + codigo
+ "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para modificar la informacion de lo empleados
*
* @param dato
* @param variable2
* @param codigo
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarEmpleados(String dato, String variable2, String codigo) {
String cadena = "UPDATE empleados SET " + dato + " = '" + variable2 + "' WHERE Cod_Emple LIKE '" + codigo + "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* ´ funcion para modificar el telefono de los empleados
*
* @param dato
* @param variable2
* @param codigo
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarTelefonoEMpleados(String dato, int variable2, String codigo) {
String cadena = "UPDATE empleados SET " + dato + " = '" + variable2 + "' WHERE Cod_Emple LIKE '" + codigo + "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para modificar el telefono de los proveedores
*
* @param codigo
* @param telefonoModificado
* @return int para comporbar que se ha ejecutado con exito el update
*/
public int modificarProveedorTelefono(String codigo, int telefonoModificado) {
String cadena = "UPDATE proveedores SET Telefono = '" + telefonoModificado + "' WHERE Cod_prov LIKE '" + codigo
+ "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para aņadir un empleado a la base de datos
*
* @param cod_emp
* @param nombre
* @param apellido
* @param dni
* @param direccion
* @param telefono
* @param numSegSocial
* @param cargo
* @param contraseņa
* @return int para comporbar que se ha insertado el emplado correctamente
*/
public int aņadirEmpleado(String cod_emp, String nombre, String apellido, String dni, String direccion,
int telefono, int numSegSocial, String cargo, String contraseņa) {
String cadena = "INSERT INTO empleados VALUES('" + cod_emp + "','" + nombre + "','" + apellido + "','" + dni
+ "','" + direccion + "','" + telefono + "','" + numSegSocial + "','" + cargo + "','" + contraseņa
+ "','" + 0 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para aņadir un proveedor a la base de datos
*
* @param cod_prov
* @param nombre
* @param apellido
* @param direccion
* @param telefono
* @return int para comprobar que se ha aņadido el proveedor
*/
public int aņadirProveedor(String cod_prov, String nombre, String apellido, String direccion, int telefono) {
String cadena = "INSERT INTO proveedores VALUES('" + cod_prov + "','" + nombre + "','" + apellido + "','"
+ direccion + "','" + telefono + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para eliminar un empleado de la base de datos
*
* @param cod_Emp
* @return int para comporbar que se ha eliminado el empleado
*/
public int borrarEmpleado(String cod_Emp) {
String cadena = "DELETE FROM empleados WHERE Cod_Emple ='" + cod_Emp + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* ´ funcion para aņadir una orden a la base de datos
*
* @param cod_empleado
* @param precio
* @param direccion
* @param p1
* @param p2
* @param p3
* @param p4
* @param p5
* @return int para comporbar que se ha aņadido la orden
*/
public int aņadirOrden(String cod_empleado, double precio, String direccion, int p1, int p2, int p3, int p4,
int p5) {
String cadena = "INSERT INTO orden (Cod_emple,Precio,Direccion,producto1,producto2,producto3,producto4,producto5) VALUES('"
+ cod_empleado + "','" + precio + "','" + direccion + "','" + p1 + "','" + p2 + "','" + p3 + "','" + p4
+ "','" + p5 + "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para mostrar las ordenes de la base de datos
*
* @return Vector con la informacion de las ordenes
*/
public Vector<Orden> mostrarOrden() {
Vector<Orden> v = new Vector<Orden>();
String cadena = "SELECT * FROM orden";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Orden(reg.getString("Cod_orden"), reg.getString("Cod_emple"), reg.getDouble("Precio"),
reg.getString("Direccion"), reg.getInt("producto1"), reg.getInt("producto2"),
reg.getInt("producto3"), reg.getInt("producto4"), reg.getInt("producto5")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion para modificar la informacion de los clientes
*
* @param dato
* @param variable2
* @param codigo
* @return int para comprobar que se ha realizado el update
*/
public int modificarCliente(String dato, String variable2, String codigo) {
String cadena = "UPDATE cliente SET " + dato + " = '" + variable2 + "' WHERE Ident_usuario LIKE '" + codigo
+ "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 0;
}
s.close();
return 1;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para desbloquear la cuenta de un cliente
*
* @param codigo
* @return int para comporbar que se ha ejecutado el update
*/
public int desbloquearCliente(String codigo) {
String cadena = "UPDATE cliente SET bloqueada = '" + 0 + "' WHERE Ident_usuario LIKE '" + codigo + "'";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para eliminar una orden de la base de datos
*
* @param cod_Emp
* @return int para comporbar que se ha ejecutado la orden
*/
public int borrarOrden(String cod_Emp) {
String cadena = "DELETE FROM orden WHERE Cod_orden ='" + cod_Emp + "'";
try {
String t = "";
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
this.cerrar();
if (resul == 1) {
return 1;
}
s.close();
return 0;
} catch (SQLException e) {
return -1;
}
}
/**
* funcion para aņadir un gasto a la base de datos
*
* @param descripcion
* @param importe
* @return int para comprobar que se ha realizado el insert
*/
public int aņadirGasto(String descripcion, double importe) {
String cadena = "INSERT INTO gastos (descripcion_gasto,importe) VALUES('" + descripcion + "','" + importe
+ "')";
try {
this.abrir();
s = c.createStatement();
int resul = s.executeUpdate(cadena);
if (resul == 1) {
return 1;
}
s.close();
this.cerrar();
return 0;
} catch (SQLException e) {
this.cerrar();
return -1;
}
}
/**
* funcion para obtener la informacion de los gastos de la base de datos
*
* @return Vector con la informacion de los gastos
*/
public Vector<Gastos> mostrarGastos() {
Vector<Gastos> v = new Vector<Gastos>();
String cadena = "SELECT * FROM gastos";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Gastos(reg.getDate("fecha_gastos").toLocalDate(), reg.getString("descripcion_gasto"),
reg.getInt("cod_gasto"), reg.getDouble("importe")));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
/**
* funcion que muestra la informacion de las ventas de la base de datos
*
* @return Vector con los datos de las ventas
*/
public Vector<Ventas> mostrarVentas() {
Vector<Ventas> v = new Vector<Ventas>();
String cadena = "SELECT * FROM Ventas";
try {
this.abrir();
s = c.createStatement();
reg = s.executeQuery(cadena);
while (reg.next()) {
v.add(new Ventas(reg.getDouble("beneficios"), reg.getInt("cod_orden"), reg.getInt("Cod_venta"),
reg.getDate("fecha_venta").toLocalDate()));
}
s.close();
this.cerrar();
return v;
} catch (SQLException e) {
return null;
}
}
}
| 26,044 | 0.596021 | 0.590519 | 1,086 | 21.930939 | 25.490398 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.347146 | false | false | 4 |
b9401fd7eca03a2a412beb125fca400c1a61226c | 35,407,710,392,863 | cc50f32f8232b9a29a8193fae904bb60a3d484e7 | /src/test/java/com/cucumber/stepdefinitions/gokul1.java | 1c30d2e486843a938c0febecc85ac57f938b6533 | [] | no_license | daisytraining01/VULCUAN_Cucumber_Framework | https://github.com/daisytraining01/VULCUAN_Cucumber_Framework | 648506d2e026ebd21d30ee30d2fd96b2d24dc5db | 3b4d5a8e4434e5ccaa6b34b3d5e8189d279e63c5 | refs/heads/master | 2023-04-12T16:41:52.326000 | 2020-05-18T03:57:30 | 2020-05-18T03:57:30 | 263,903,713 | 0 | 0 | null | false | 2021-04-26T20:16:51 | 2020-05-14T12:04:45 | 2020-05-18T03:57:46 | 2021-04-26T20:16:51 | 18,519 | 0 | 0 | 2 | Java | false | false | package com.cucumber.stepdefinitions;
import static org.junit.Assert.assertEquals;
import java.util.Hashtable;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import com.cucumber.helper.UserActions;
import com.cucumber.pageobjects.LoginPage;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class gokul1 {
private static Logger Log = Logger.getLogger(UserActions.class.getName());
UserActions logger;
Hashtable<String,String> Data;
public gokul1(UserActions logger) {
this.logger = logger;
}
@Given("User launches to {string} in the browser")
public void user_launches_to_in_the_browser(String string) {
// Write code here that turns the phrase above into concrete actions
logger.OpenUrl("http://demo.rapidtestpro.com/login.php");
}
@Then("user able to view the home page with username and password field for login")
public void user_able_to_view_the_home_page_with_username_and_password_field_for_login() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true, logger.isDisplayed(LoginPage.UserName));
assertEquals(true, logger.isDisplayed(LoginPage.Password));
}
@When("User to enter login : {string} , password : {string}")
public void user_to_enter_login_password(String login, String password) {
// Write code here that turns the phrase above into concrete actions
logger.SendKeys(LoginPage.UserName,login);
logger.SendKeys(LoginPage.Password,password);
}
@When("user clicks submit button")
public void user_clicks_submit_button() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true,logger.isEnabled(LoginPage.Submit));
logger.Click(LoginPage.Submit);
}
@Then("Application move to next oage for Pin verification")
public void application_move_to_next_oage_for_Pin_verification() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true, logger.isDisplayed(LoginPage.PIN));
}
@Then("user enters Pin {string}")
public void user_enters_Pin(String string) {
// Write code here that turns the phrase above into concrete actions
logger.SendKeys(LoginPage.PIN,string);
}
@Then("user clicks validate Pin")
public void user_clicks_validate_Pin() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true,logger.isEnabled(LoginPage.Submit));
logger.Click(LoginPage.Submit);
}
@Then("user able to login successfully")
public void user_able_to_login_successfully() {
}
@Given("Upon successfull login user able to land Account summary screen")
public void upon_successfull_login_user_able_to_land_Account_summary_screen() {
}
@Given("User to click on account statement menu")
public void user_to_click_on_account_statement_menu() {
// Write code here that turns the phrase above into concrete actions
logger.Click(LoginPage.AccountStatement);
}
@Then("User can able to view the latest account statement on screen")
public void user_can_able_to_view_the_latest_account_statement_on_screen() {
assertEquals(true, logger.isDisplayed(By.xpath("/html/body/table/tbody/tr[3]/td[2]/table/tbody/tr/td/p[1]")));
}
}
| UTF-8 | Java | 3,279 | java | gokul1.java | Java | [] | null | [] | package com.cucumber.stepdefinitions;
import static org.junit.Assert.assertEquals;
import java.util.Hashtable;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import com.cucumber.helper.UserActions;
import com.cucumber.pageobjects.LoginPage;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class gokul1 {
private static Logger Log = Logger.getLogger(UserActions.class.getName());
UserActions logger;
Hashtable<String,String> Data;
public gokul1(UserActions logger) {
this.logger = logger;
}
@Given("User launches to {string} in the browser")
public void user_launches_to_in_the_browser(String string) {
// Write code here that turns the phrase above into concrete actions
logger.OpenUrl("http://demo.rapidtestpro.com/login.php");
}
@Then("user able to view the home page with username and password field for login")
public void user_able_to_view_the_home_page_with_username_and_password_field_for_login() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true, logger.isDisplayed(LoginPage.UserName));
assertEquals(true, logger.isDisplayed(LoginPage.Password));
}
@When("User to enter login : {string} , password : {string}")
public void user_to_enter_login_password(String login, String password) {
// Write code here that turns the phrase above into concrete actions
logger.SendKeys(LoginPage.UserName,login);
logger.SendKeys(LoginPage.Password,password);
}
@When("user clicks submit button")
public void user_clicks_submit_button() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true,logger.isEnabled(LoginPage.Submit));
logger.Click(LoginPage.Submit);
}
@Then("Application move to next oage for Pin verification")
public void application_move_to_next_oage_for_Pin_verification() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true, logger.isDisplayed(LoginPage.PIN));
}
@Then("user enters Pin {string}")
public void user_enters_Pin(String string) {
// Write code here that turns the phrase above into concrete actions
logger.SendKeys(LoginPage.PIN,string);
}
@Then("user clicks validate Pin")
public void user_clicks_validate_Pin() {
// Write code here that turns the phrase above into concrete actions
assertEquals(true,logger.isEnabled(LoginPage.Submit));
logger.Click(LoginPage.Submit);
}
@Then("user able to login successfully")
public void user_able_to_login_successfully() {
}
@Given("Upon successfull login user able to land Account summary screen")
public void upon_successfull_login_user_able_to_land_Account_summary_screen() {
}
@Given("User to click on account statement menu")
public void user_to_click_on_account_statement_menu() {
// Write code here that turns the phrase above into concrete actions
logger.Click(LoginPage.AccountStatement);
}
@Then("User can able to view the latest account statement on screen")
public void user_can_able_to_view_the_latest_account_statement_on_screen() {
assertEquals(true, logger.isDisplayed(By.xpath("/html/body/table/tbody/tr[3]/td[2]/table/tbody/tr/td/p[1]")));
}
}
| 3,279 | 0.742299 | 0.740775 | 101 | 31.465347 | 29.575064 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.217822 | false | false | 4 |
f8b19f578bb779e5864402ba266810df17cafc7e | 13,280,038,938,450 | 13c3cd702becb62f4c34e6172a4bf692d19bd0f4 | /back-end/app/controllers/PhotoController.java | b3919330ffa6fceb207224719faa877901a91905 | [
"CC0-1.0"
] | permissive | mirza1995/restaurant_review | https://github.com/mirza1995/restaurant_review | b1a5129ea9b7b782ab85a605910e364721665449 | 4e705f5d960811c8020741206a860d448a3dd654 | refs/heads/master | 2020-04-03T06:32:39.440000 | 2018-10-28T14:24:18 | 2018-10-28T14:24:18 | 155,077,759 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import services.PhotoService;
import javax.inject.Inject;
import java.util.ArrayList;
public class PhotoController extends Controller {
@Inject private PhotoService photoService;
@Transactional(readOnly = true)
public Result getRestaurantPhotos(int id){
if(id == 0){
return ok(Json.toJson(new ArrayList<>()));
}
JsonNode photos=photoService.getRestaurantPhotos(id,0);
if(photos==null){
return notFound("No photos");
}
return ok(photos);
}
@Transactional(readOnly = true)
public Result getGallery(int id){
JsonNode photos=photoService.getRestaurantPhotos(id,7);
if(photos==null){
return notFound("No photos");
}
return ok(photos);
}
@Transactional(readOnly = true)
public Result getNumberOfPhotos(int id){
return ok(Json.toJson(photoService.getAllPhotos(id).size()));
}
}
| UTF-8 | Java | 1,117 | java | PhotoController.java | Java | [] | null | [] | package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import services.PhotoService;
import javax.inject.Inject;
import java.util.ArrayList;
public class PhotoController extends Controller {
@Inject private PhotoService photoService;
@Transactional(readOnly = true)
public Result getRestaurantPhotos(int id){
if(id == 0){
return ok(Json.toJson(new ArrayList<>()));
}
JsonNode photos=photoService.getRestaurantPhotos(id,0);
if(photos==null){
return notFound("No photos");
}
return ok(photos);
}
@Transactional(readOnly = true)
public Result getGallery(int id){
JsonNode photos=photoService.getRestaurantPhotos(id,7);
if(photos==null){
return notFound("No photos");
}
return ok(photos);
}
@Transactional(readOnly = true)
public Result getNumberOfPhotos(int id){
return ok(Json.toJson(photoService.getAllPhotos(id).size()));
}
}
| 1,117 | 0.66786 | 0.665175 | 39 | 27.641026 | 18.846869 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.512821 | false | false | 4 |
f088db27c7605f97da2edf165b1ab7c077e062b6 | 14,190,572,001,230 | 61dea18460df6f2bc1fe19af8bfa6e0809406885 | /ecmoban/src/main/java/com/ecjia/entity/requestmodel/SubOrderCondition.java | ce7998d659dbfe767f4b5bae124c3113299f9795 | [] | no_license | hackerlc/SJQ_ECSHOP_MJ_NEW | https://github.com/hackerlc/SJQ_ECSHOP_MJ_NEW | a006261856124671bceaf92d1f65d4905dc35078 | 2c8ac3f2464c4536c079ac067ec761adcd9c267e | refs/heads/master | 2021-08-31T11:01:29.247000 | 2017-12-21T03:55:09 | 2017-12-21T03:55:09 | 114,960,406 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ecjia.entity.requestmodel;
import java.io.Serializable;
/**
* 类名介绍:
* Created by sun
* Created time 2017-04-07.
*/
public class SubOrderCondition implements Serializable {
/*{//店铺用优惠活动,用优惠券情况
...."shop_id": "310", //店铺id
...."cou_id": "11",..//优惠券id
...."act_id": 2,......//优惠活动id
...."shipping_id": 37 //配送方式id
..}*/
private String shop_id;
private String cou_id;
private String act_id;
private String shipping_id;
public String getShop_id() {
return shop_id;
}
public void setShop_id(String shop_id) {
this.shop_id = shop_id;
}
public String getCou_id() {
return cou_id;
}
public void setCou_id(String cou_id) {
this.cou_id = cou_id;
}
public String getAct_id() {
return act_id;
}
public void setAct_id(String act_id) {
this.act_id = act_id;
}
public String getShipping_id() {
return shipping_id;
}
public void setShipping_id(String shipping_id) {
this.shipping_id = shipping_id;
}
}
| UTF-8 | Java | 1,170 | java | SubOrderCondition.java | Java | [
{
"context": " java.io.Serializable;\n\n/**\n * 类名介绍:\n * Created by sun\n * Created time 2017-04-07.\n */\n\npublic class Sub",
"end": 100,
"score": 0.48710498213768005,
"start": 97,
"tag": "NAME",
"value": "sun"
}
] | null | [] | package com.ecjia.entity.requestmodel;
import java.io.Serializable;
/**
* 类名介绍:
* Created by sun
* Created time 2017-04-07.
*/
public class SubOrderCondition implements Serializable {
/*{//店铺用优惠活动,用优惠券情况
...."shop_id": "310", //店铺id
...."cou_id": "11",..//优惠券id
...."act_id": 2,......//优惠活动id
...."shipping_id": 37 //配送方式id
..}*/
private String shop_id;
private String cou_id;
private String act_id;
private String shipping_id;
public String getShop_id() {
return shop_id;
}
public void setShop_id(String shop_id) {
this.shop_id = shop_id;
}
public String getCou_id() {
return cou_id;
}
public void setCou_id(String cou_id) {
this.cou_id = cou_id;
}
public String getAct_id() {
return act_id;
}
public void setAct_id(String act_id) {
this.act_id = act_id;
}
public String getShipping_id() {
return shipping_id;
}
public void setShipping_id(String shipping_id) {
this.shipping_id = shipping_id;
}
}
| 1,170 | 0.560579 | 0.546112 | 55 | 19.109091 | 16.360344 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.309091 | false | false | 4 |
7016921b4fdfe5a422cbc063a301d1f1ffff07b2 | 5,609,227,329,962 | ffb152ac8087c935ee27a7dcf6cfcf23f8e29dab | /src/main/java/com/asiainfo/iot/common/service/BaseSevice.java | 5d6504939cccba9f8c581e497c8cb3a0afe2b290 | [] | no_license | sylar12138/My-test-proj | https://github.com/sylar12138/My-test-proj | 6ff7d07c3d140921f42c01efc17fa99fd9cef29c | 44aa0dcd436cdd7979255e4c8b1b8566ba37d798 | refs/heads/master | 2020-04-04T19:53:42.128000 | 2018-11-05T13:14:33 | 2018-11-05T13:14:33 | 156,224,937 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asiainfo.iot.common.service;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.asiainfo.iot.common.dao.IBaseDao;
import com.asiainfo.iot.common.param.ReqParam;
import com.asiainfo.iot.common.param.RespParam;
import com.asiainfo.iot.common.param.page.Page;
@Service
@Transactional
public class BaseSevice implements IBaseSevice {
private static final Logger logger = Logger.getLogger(BaseSevice.class);
private IBaseDao baseDao;
public IBaseDao getBaseDao() {
return baseDao;
}
@Resource(name = "baseDao")
public void setBaseDao(IBaseDao baseDao) {
this.baseDao = baseDao;
}
@Override
public int insert(ReqParam req, RespParam res) {
int i = baseDao.insert(null, req.getEntity());
res.setEntity(req.getEntity());
return i;
}
@Override
public int update(ReqParam req, RespParam res) {
int i = baseDao.update(null, req.getEntity());
res.setEntity(req.getEntity());
return i;
}
@Override
public int updateById(ReqParam req, RespParam res) {
int i = baseDao.updateById(null, req.getEntity());
res.setEntity(req.getEntity());
return i;
}
@Override
public int delete(ReqParam req, RespParam res) {
return baseDao.delete(null, req.getEntity());
}
@Override
public int deleteById(ReqParam req, RespParam res) {
return baseDao.deleteById(null, req.getEntity());
}
@Override
public int deleteByArrayIds(ReqParam req, RespParam res) {
return baseDao.deleteByArrayIds(null, req.getEntity(), req.getArrayIds());
}
@Override
public int findById(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findOne(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findList(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findListPage(ReqParam req, RespParam res) {
return 0;
}
@Override
public int batchInsert(ReqParam req, RespParam res) {
return 0;
}
@Override
public int batchUpdate(ReqParam req, RespParam res) {
return 0;
}
@Override
public int insertByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int updateByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int deleteByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findListByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findListPageByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findOneByNativeSql(ReqParam req, RespParam res) {
return 0;
}
}
| UTF-8 | Java | 2,691 | java | BaseSevice.java | Java | [] | null | [] | package com.asiainfo.iot.common.service;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.asiainfo.iot.common.dao.IBaseDao;
import com.asiainfo.iot.common.param.ReqParam;
import com.asiainfo.iot.common.param.RespParam;
import com.asiainfo.iot.common.param.page.Page;
@Service
@Transactional
public class BaseSevice implements IBaseSevice {
private static final Logger logger = Logger.getLogger(BaseSevice.class);
private IBaseDao baseDao;
public IBaseDao getBaseDao() {
return baseDao;
}
@Resource(name = "baseDao")
public void setBaseDao(IBaseDao baseDao) {
this.baseDao = baseDao;
}
@Override
public int insert(ReqParam req, RespParam res) {
int i = baseDao.insert(null, req.getEntity());
res.setEntity(req.getEntity());
return i;
}
@Override
public int update(ReqParam req, RespParam res) {
int i = baseDao.update(null, req.getEntity());
res.setEntity(req.getEntity());
return i;
}
@Override
public int updateById(ReqParam req, RespParam res) {
int i = baseDao.updateById(null, req.getEntity());
res.setEntity(req.getEntity());
return i;
}
@Override
public int delete(ReqParam req, RespParam res) {
return baseDao.delete(null, req.getEntity());
}
@Override
public int deleteById(ReqParam req, RespParam res) {
return baseDao.deleteById(null, req.getEntity());
}
@Override
public int deleteByArrayIds(ReqParam req, RespParam res) {
return baseDao.deleteByArrayIds(null, req.getEntity(), req.getArrayIds());
}
@Override
public int findById(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findOne(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findList(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findListPage(ReqParam req, RespParam res) {
return 0;
}
@Override
public int batchInsert(ReqParam req, RespParam res) {
return 0;
}
@Override
public int batchUpdate(ReqParam req, RespParam res) {
return 0;
}
@Override
public int insertByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int updateByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int deleteByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findListByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findListPageByNativeSql(ReqParam req, RespParam res) {
return 0;
}
@Override
public int findOneByNativeSql(ReqParam req, RespParam res) {
return 0;
}
}
| 2,691 | 0.739502 | 0.734671 | 130 | 19.700001 | 21.928082 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.361538 | false | false | 4 |
98c39500b77433abef8c739e3b4f4ed73edad622 | 34,531,537,087,916 | 7ccc2a62b70328de995550ac5e15fbe56947ad4f | /src/org/isf/utils/db/DbQueryLogger.java | 8b199ea5d921073444fb7dc223f5b714ebe49558 | [] | no_license | mwithi/OpenHospital | https://github.com/mwithi/OpenHospital | 4b0ff2f0e55cb5e4626c013b70e2629d99947f9a | ead1c27cfe15bcae38449cda37c127d6c11088d8 | refs/heads/master | 2019-07-06T05:13:46.320000 | 2019-01-17T23:08:47 | 2019-01-17T23:08:47 | 47,989,895 | 1 | 1 | null | true | 2017-01-27T20:11:32 | 2015-12-14T17:16:36 | 2016-01-13T19:07:12 | 2017-01-27T20:11:32 | 52,369 | 0 | 0 | 0 | Java | null | null | package org.isf.utils.db;
import org.isf.generaldata.MessageBundle;
import org.isf.utils.exception.OHException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Class that executes a query using the connection DbSingleJpaConn
* The various methods that open a connection with the
* autocommit flag set to false have the responsability
* of doing the commit/rollback operation
*/
public class DbQueryLogger {
protected Logger logger = LoggerFactory.getLogger(DbQueryLogger.class);
/**
* method that executes a query and returns a resultset
* @param aQuery
* @param autocommit
* @return "ResultSet"
* @throws SQLException
* @throws IOException
*/
public ResultSet getData(String aQuery, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
Statement stat = conn.createStatement();
return stat.executeQuery(aQuery);
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); //, e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes a PreparedStatement with params and returns a resultset
* @param aQuery
* @param params
* @param autocommit
* @return
* @throws OHException
*/
public ResultSet getDataWithParams(String aQuery, List<?> params, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
if (!params.isEmpty()) logger.trace(" parameters : " + sanitize(params));
}
ResultSet results = null;
Connection conn = null;
try {
conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
PreparedStatement pstmt = conn.prepareStatement(aQuery);
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i + 1, params.get(i));
}
results = pstmt.executeQuery();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
return results;
}
/**
* method that executes an insert-update-delete query and returns true or false
* depending on the success of the operation
* @param String aQuery
* @param boolean autocommit
* @return Boolean True/False
* @throws SQLException
* @throws IOException
*/
public boolean setData(String aQuery, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
Statement stat = conn.createStatement();
return stat.executeUpdate(aQuery) > 0;
}catch (OHException e){
throw e;
} catch (SQLIntegrityConstraintViolationException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.theselecteditemisstillusedsomewhere"), e); // + ": " + aQuery, e);
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes an insert-update-delete PreparedStatement with params and returns true or false
* depending on the success of the operation
* @param aQuery
* @param params
* @param autocommit
* @return
* @throws OHException
*/
public boolean setDataWithParams(String aQuery, List<?> params, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
if (!params.isEmpty()) logger.trace(" parameters : " + sanitize(params));
}
Connection conn = null;
try {
conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
PreparedStatement pstmt = conn.prepareStatement(aQuery);
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i+1, params.get(i));
}
return pstmt.executeUpdate() > 0;
}catch (OHException e){
throw e;
} catch (SQLIntegrityConstraintViolationException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.theselecteditemisstillusedsomewhere"), e); // + ": " + aQuery, e);
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes an insert-update-delete query and returns A ResultSet
* containing the autogenerated key (integer counter)
* if no key has been generated the ResultSet will be empty
* @param String aQuery
* @param boolean autocommit
* @return ResultSet
* @throws SQLException
* @throws IOException
*/
public ResultSet setDataReturnGeneratedKey(String aQuery, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
Statement stat = conn.createStatement();
stat.execute(aQuery,Statement.RETURN_GENERATED_KEYS);
return stat.getGeneratedKeys();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes an insert-update-delete PreparedStatement with params and returns A ResultSet
* containing the autogenerated key (integer counter)
* if no key has been generated the ResultSet will be empty
* @param aQuery
* @param params
* @param autocommit
* @return
* @throws OHException
*/
public ResultSet setDataReturnGeneratedKeyWithParams(String aQuery, List<?> params, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
if (!params.isEmpty()) logger.trace(" parameters : " + sanitize(params));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
PreparedStatement pstmt = conn.prepareStatement(aQuery, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i+1, params.get(i));
}
pstmt.execute();
return pstmt.getGeneratedKeys();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes a query and returns true or false
* depending on the existence of records or not in
* the Recordset
* @param String aQuery
* @return Boolean True/False
* @throws SQLException
* @throws IOException
*/
public boolean isData(String aQuery) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try {
Connection conn = DbSingleJpaConn.getConnection();
Statement stat = conn.createStatement();
ResultSet set = stat.executeQuery(aQuery);
return set.first();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method for sanitize every String object in the list for logging purpose
* @param params - the list of objects
* @return the list sanitized
*/
private List<?> sanitize(List<?> params) {
List<Object> saneParams = new ArrayList<Object>();
for (Object param : params) {
if (param instanceof String) {
saneParams.add(sanitize((String) param));
} else {
saneParams.add(param);
}
}
return saneParams;
}
/**
* method for sanitize a String object for logging purpose
* @param aString - the String object
* @return the string sanitized
*/
private String sanitize(String aString) {
return aString.replace("'", "\\'");
}
}
| UTF-8 | Java | 9,976 | java | DbQueryLogger.java | Java | [] | null | [] | package org.isf.utils.db;
import org.isf.generaldata.MessageBundle;
import org.isf.utils.exception.OHException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Class that executes a query using the connection DbSingleJpaConn
* The various methods that open a connection with the
* autocommit flag set to false have the responsability
* of doing the commit/rollback operation
*/
public class DbQueryLogger {
protected Logger logger = LoggerFactory.getLogger(DbQueryLogger.class);
/**
* method that executes a query and returns a resultset
* @param aQuery
* @param autocommit
* @return "ResultSet"
* @throws SQLException
* @throws IOException
*/
public ResultSet getData(String aQuery, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
Statement stat = conn.createStatement();
return stat.executeQuery(aQuery);
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); //, e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes a PreparedStatement with params and returns a resultset
* @param aQuery
* @param params
* @param autocommit
* @return
* @throws OHException
*/
public ResultSet getDataWithParams(String aQuery, List<?> params, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
if (!params.isEmpty()) logger.trace(" parameters : " + sanitize(params));
}
ResultSet results = null;
Connection conn = null;
try {
conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
PreparedStatement pstmt = conn.prepareStatement(aQuery);
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i + 1, params.get(i));
}
results = pstmt.executeQuery();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
return results;
}
/**
* method that executes an insert-update-delete query and returns true or false
* depending on the success of the operation
* @param String aQuery
* @param boolean autocommit
* @return Boolean True/False
* @throws SQLException
* @throws IOException
*/
public boolean setData(String aQuery, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
Statement stat = conn.createStatement();
return stat.executeUpdate(aQuery) > 0;
}catch (OHException e){
throw e;
} catch (SQLIntegrityConstraintViolationException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.theselecteditemisstillusedsomewhere"), e); // + ": " + aQuery, e);
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes an insert-update-delete PreparedStatement with params and returns true or false
* depending on the success of the operation
* @param aQuery
* @param params
* @param autocommit
* @return
* @throws OHException
*/
public boolean setDataWithParams(String aQuery, List<?> params, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
if (!params.isEmpty()) logger.trace(" parameters : " + sanitize(params));
}
Connection conn = null;
try {
conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
PreparedStatement pstmt = conn.prepareStatement(aQuery);
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i+1, params.get(i));
}
return pstmt.executeUpdate() > 0;
}catch (OHException e){
throw e;
} catch (SQLIntegrityConstraintViolationException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.theselecteditemisstillusedsomewhere"), e); // + ": " + aQuery, e);
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes an insert-update-delete query and returns A ResultSet
* containing the autogenerated key (integer counter)
* if no key has been generated the ResultSet will be empty
* @param String aQuery
* @param boolean autocommit
* @return ResultSet
* @throws SQLException
* @throws IOException
*/
public ResultSet setDataReturnGeneratedKey(String aQuery, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
Statement stat = conn.createStatement();
stat.execute(aQuery,Statement.RETURN_GENERATED_KEYS);
return stat.getGeneratedKeys();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes an insert-update-delete PreparedStatement with params and returns A ResultSet
* containing the autogenerated key (integer counter)
* if no key has been generated the ResultSet will be empty
* @param aQuery
* @param params
* @param autocommit
* @return
* @throws OHException
*/
public ResultSet setDataReturnGeneratedKeyWithParams(String aQuery, List<?> params, boolean autocommit) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
if (!params.isEmpty()) logger.trace(" parameters : " + sanitize(params));
}
try{
Connection conn = DbSingleJpaConn.getConnection();
conn.setAutoCommit(autocommit);
PreparedStatement pstmt = conn.prepareStatement(aQuery, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(i+1, params.get(i));
}
pstmt.execute();
return pstmt.getGeneratedKeys();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method that executes a query and returns true or false
* depending on the existence of records or not in
* the Recordset
* @param String aQuery
* @return Boolean True/False
* @throws SQLException
* @throws IOException
*/
public boolean isData(String aQuery) throws OHException {
if (logger.isDebugEnabled()) {
logger.debug("Query " + sanitize(aQuery));
}
try {
Connection conn = DbSingleJpaConn.getConnection();
Statement stat = conn.createStatement();
ResultSet set = stat.executeQuery(aQuery);
return set.first();
}catch (OHException e){
throw e;
} catch (SQLException e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwiththesqlistruction"), e); // + ": " + aQuery, e);
} catch (Exception e) {
throw new OHException(MessageBundle.getMessage("angal.sql.problemsoccurredwithserverconnection"), e);
}
}
/**
* method for sanitize every String object in the list for logging purpose
* @param params - the list of objects
* @return the list sanitized
*/
private List<?> sanitize(List<?> params) {
List<Object> saneParams = new ArrayList<Object>();
for (Object param : params) {
if (param instanceof String) {
saneParams.add(sanitize((String) param));
} else {
saneParams.add(param);
}
}
return saneParams;
}
/**
* method for sanitize a String object for logging purpose
* @param aString - the String object
* @return the string sanitized
*/
private String sanitize(String aString) {
return aString.replace("'", "\\'");
}
}
| 9,976 | 0.659383 | 0.65838 | 264 | 36.78788 | 31.869177 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.329545 | false | false | 4 |
2b02b899c1f198dd699e9e4e361b9fcd4b621eec | 36,344,013,269,330 | 27ff92112503263911d35a5336a5cd93dcd5c247 | /sample/src/main/java/org/smartregister/chw/hf/fragment/FamilyRemoveMemberFragment.java | 5e03163d492f9a4611b3c98e0a6efdca289f90dc | [
"Apache-2.0"
] | permissive | SoftmedTanzania/opensrp-client-chw-core | https://github.com/SoftmedTanzania/opensrp-client-chw-core | 77441d7481dbe4d78dea91151dd9d469bf6be152 | ac6859bd51fd23572f0d8ed82a86f103376dd57b | refs/heads/tanzania-ministry-of-health-nacp | 2023-05-13T01:44:10.012000 | 2023-05-11T18:58:03 | 2023-05-11T18:58:03 | 425,199,013 | 0 | 2 | NOASSERTION | true | 2023-04-18T09:51:24 | 2021-11-06T09:02:04 | 2022-01-03T07:37:53 | 2023-04-18T09:51:22 | 109,863 | 0 | 1 | 2 | Java | false | false | package org.smartregister.chw.hf.fragment;
import android.os.Bundle;
import org.smartregister.chw.core.activity.CoreFamilyRegisterActivity;
import org.smartregister.chw.core.fragment.CoreFamilyProfileChangeDialog;
import org.smartregister.chw.core.fragment.CoreFamilyRemoveMemberFragment;
import org.smartregister.chw.core.utils.CoreConstants;
import org.smartregister.chw.hf.activity.FamilyRegisterActivity;
import org.smartregister.chw.hf.model.FamilyRemoveMemberModel;
import org.smartregister.chw.hf.presenter.FamilyRemoveMemberPresenter;
import org.smartregister.chw.hf.provider.HfFamilyRemoveMemberProvider;
import java.util.HashMap;
import java.util.Set;
import timber.log.Timber;
public class FamilyRemoveMemberFragment extends CoreFamilyRemoveMemberFragment {
public static final String DIALOG_TAG = FamilyRemoveMemberFragment.class.getSimpleName();
public static CoreFamilyRemoveMemberFragment newInstance(Bundle bundle) {
Bundle args = bundle;
FamilyRemoveMemberFragment fragment = new FamilyRemoveMemberFragment();
if (args == null) {
args = new Bundle();
}
fragment.setArguments(args);
return fragment;
}
@Override
protected void setRemoveMemberProvider(Set visibleColumns, String familyHead, String primaryCaregiver, String familyBaseEntityId) {
this.removeMemberProvider = new HfFamilyRemoveMemberProvider(familyBaseEntityId, this.getActivity(),
this.commonRepository(), visibleColumns, new RemoveMemberListener(), new FooterListener(), familyHead, primaryCaregiver);
}
@Override
public void setAdvancedSearchFormData(HashMap<String, String> hashMap) {
Timber.v(DIALOG_TAG, "setAdvancedSearchFormData");
}
@Override
protected void setPresenter(String familyHead, String primaryCareGiver) {
this.presenter = new FamilyRemoveMemberPresenter(this, new FamilyRemoveMemberModel(), null, familyBaseEntityId, familyHead, primaryCareGiver);
}
@Override
protected Class<? extends CoreFamilyRegisterActivity> getFamilyRegisterActivityClass() {
return FamilyRegisterActivity.class;
}
@Override
protected CoreFamilyProfileChangeDialog getChangeFamilyCareGiverDialog() {
return FamilyProfileChangeDialog.newInstance(getContext(), familyBaseEntityId,
CoreConstants.PROFILE_CHANGE_ACTION.PRIMARY_CARE_GIVER);
}
@Override
protected CoreFamilyProfileChangeDialog getChangeFamilyHeadDialog() {
return FamilyProfileChangeDialog.newInstance(getContext(), familyBaseEntityId,
CoreConstants.PROFILE_CHANGE_ACTION.HEAD_OF_FAMILY);
}
@Override
protected String getRemoveFamilyMemberDialogTag() {
return FamilyRemoveMemberFragment.DIALOG_TAG;
}
}
| UTF-8 | Java | 2,812 | java | FamilyRemoveMemberFragment.java | Java | [] | null | [] | package org.smartregister.chw.hf.fragment;
import android.os.Bundle;
import org.smartregister.chw.core.activity.CoreFamilyRegisterActivity;
import org.smartregister.chw.core.fragment.CoreFamilyProfileChangeDialog;
import org.smartregister.chw.core.fragment.CoreFamilyRemoveMemberFragment;
import org.smartregister.chw.core.utils.CoreConstants;
import org.smartregister.chw.hf.activity.FamilyRegisterActivity;
import org.smartregister.chw.hf.model.FamilyRemoveMemberModel;
import org.smartregister.chw.hf.presenter.FamilyRemoveMemberPresenter;
import org.smartregister.chw.hf.provider.HfFamilyRemoveMemberProvider;
import java.util.HashMap;
import java.util.Set;
import timber.log.Timber;
public class FamilyRemoveMemberFragment extends CoreFamilyRemoveMemberFragment {
public static final String DIALOG_TAG = FamilyRemoveMemberFragment.class.getSimpleName();
public static CoreFamilyRemoveMemberFragment newInstance(Bundle bundle) {
Bundle args = bundle;
FamilyRemoveMemberFragment fragment = new FamilyRemoveMemberFragment();
if (args == null) {
args = new Bundle();
}
fragment.setArguments(args);
return fragment;
}
@Override
protected void setRemoveMemberProvider(Set visibleColumns, String familyHead, String primaryCaregiver, String familyBaseEntityId) {
this.removeMemberProvider = new HfFamilyRemoveMemberProvider(familyBaseEntityId, this.getActivity(),
this.commonRepository(), visibleColumns, new RemoveMemberListener(), new FooterListener(), familyHead, primaryCaregiver);
}
@Override
public void setAdvancedSearchFormData(HashMap<String, String> hashMap) {
Timber.v(DIALOG_TAG, "setAdvancedSearchFormData");
}
@Override
protected void setPresenter(String familyHead, String primaryCareGiver) {
this.presenter = new FamilyRemoveMemberPresenter(this, new FamilyRemoveMemberModel(), null, familyBaseEntityId, familyHead, primaryCareGiver);
}
@Override
protected Class<? extends CoreFamilyRegisterActivity> getFamilyRegisterActivityClass() {
return FamilyRegisterActivity.class;
}
@Override
protected CoreFamilyProfileChangeDialog getChangeFamilyCareGiverDialog() {
return FamilyProfileChangeDialog.newInstance(getContext(), familyBaseEntityId,
CoreConstants.PROFILE_CHANGE_ACTION.PRIMARY_CARE_GIVER);
}
@Override
protected CoreFamilyProfileChangeDialog getChangeFamilyHeadDialog() {
return FamilyProfileChangeDialog.newInstance(getContext(), familyBaseEntityId,
CoreConstants.PROFILE_CHANGE_ACTION.HEAD_OF_FAMILY);
}
@Override
protected String getRemoveFamilyMemberDialogTag() {
return FamilyRemoveMemberFragment.DIALOG_TAG;
}
}
| 2,812 | 0.766714 | 0.766714 | 71 | 38.605633 | 38.683796 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.676056 | false | false | 4 |
8d5ffde9585b54722be95d9e0052d451be84d0c0 | 33,981,781,267,617 | e0b11e75387f2a93f6d92bdea8a8b22611a4c262 | /app/src/main/java/com/example/eventrese/models/User.java | 4e5a129dd058a4ba981b81a61334975d4e36d7ca | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ubelyse/Week4IP | https://github.com/ubelyse/Week4IP | e157ca5c3a32d2cf057986c5be6143f96853330a | 335d5cac3f67017d57023d5406ccdb4c93621609 | refs/heads/master | 2023-03-05T21:55:16.230000 | 2021-02-07T17:07:23 | 2021-02-07T17:07:23 | 336,003,757 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.eventrese.models;
import androidx.annotation.NonNull;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class User {
private String id;
private String username;
private String fullName;
private String address;
private String description;
private boolean gender;
private String phoneNumber;
private String dateOfBirth;
private String search;
public User() {
}
public User(String id,String username, String fullName, String address, String description, boolean gender, String phoneNumber, String dateOfBirth, String search) {
this.id = id;
this.username = username;
this.fullName = fullName;
this.address = address;
if(description.isEmpty())
this.description = "Description is not available";
else
this.description = description;
this.gender = gender;
this.phoneNumber = phoneNumber;
this.dateOfBirth = dateOfBirth;
this.search = search;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
} | UTF-8 | Java | 2,672 | java | User.java | Java | [
{
"context": "h) {\n this.id = id;\n this.username = username;\n this.fullName = fullName;\n this.a",
"end": 928,
"score": 0.9712438583374023,
"start": 920,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package com.example.eventrese.models;
import androidx.annotation.NonNull;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class User {
private String id;
private String username;
private String fullName;
private String address;
private String description;
private boolean gender;
private String phoneNumber;
private String dateOfBirth;
private String search;
public User() {
}
public User(String id,String username, String fullName, String address, String description, boolean gender, String phoneNumber, String dateOfBirth, String search) {
this.id = id;
this.username = username;
this.fullName = fullName;
this.address = address;
if(description.isEmpty())
this.description = "Description is not available";
else
this.description = description;
this.gender = gender;
this.phoneNumber = phoneNumber;
this.dateOfBirth = dateOfBirth;
this.search = search;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
} | 2,672 | 0.651198 | 0.651198 | 116 | 22.043104 | 22.092045 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465517 | false | false | 4 |
6438f9d0206fc7cba7677f38aa45eb6c20e5e1af | 26,199,300,543,787 | dadca7f5ebbec27c1c20bb93016ba7033a7f2383 | /src/main/java/cn/bluegod/mycinema/DB/DB.java | 27498824190cfda6487ce87ebb8b420d889464ec | [] | no_license | ftq617/MyMovie | https://github.com/ftq617/MyMovie | ef0b7a153d99838c825728fc0ff5c95aa64f5211 | f15d88745d542cc34e501e8895a9d6ac6dfbee91 | refs/heads/master | 2020-03-25T04:34:51.213000 | 2018-08-03T08:44:25 | 2018-08-03T08:44:25 | 143,402,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.bluegod.mycinema.DB;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @description: 连接数据库读写工具类
* @author: Mr.Fu
* @create: 2018-07-25 17:40
* @Version V1.0
*/
public class DB {
private static JdbcConnectionsPool pool = new JdbcConnectionsPool();
private Connection con;
private PreparedStatement statement;
public DB(){ }
private void getConnect() {
try {
con=pool.getConnection();
System.out.println("获得数据库连接成功");
} catch (SQLException e) {
System.out.println("获得数据库连接失败");
e.printStackTrace();
}
}
private void getStatement(String sql){
getConnect();
try {
statement=con.prepareStatement(sql);
System.out.println("获得statement成功");
} catch (SQLException e) {
System.out.println("获得statement失败");
e.printStackTrace();
}
}
public int executeUpdate(String sql,Object... objs) throws SQLException {
getStatement(sql);
if (objs!=null){
for (int i = 1; i <= objs.length; i++) {
statement.setObject(i, objs[i-1]);
}
}
int a=statement.executeUpdate();
closedStatement();
closedCon();
return a;
}
public <T> List<T> executeQuery(Class tClass, String sql, Object... value) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {
getStatement(sql);
if (value!=null){
for (int i = 1; i <= value.length; i++) {
statement.setObject(i, value[i-1]);
}
}
ResultSet rs = statement.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
List<T> list=new ArrayList<T>();
if (rs!=null) {
while (rs.next()) {
T entity = (T)tClass.newInstance();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
Field field=tClass.getDeclaredField(rsmd.getColumnName(i+1));
field.setAccessible(true);
try {
field.set(entity, rs.getObject(i + 1));
}catch (Exception e){
field.set(entity, rs.getObject(i + 1)+"");
}
}
list.add(entity);
}
}
rs.close();
closedStatement();
closedCon();
return list;
}
public void closedStatement() throws SQLException {
if (statement!=null){
statement.close();
}
//
}
public void closedCon() throws SQLException {
if (con!=null){
con.close();
con=null;
}
}
}
| UTF-8 | Java | 2,985 | java | DB.java | Java | [
{
"context": "List;\n\n/**\n * @description: 连接数据库读写工具类\n * @author: Mr.Fu\n * @create: 2018-07-25 17:40\n * @Version V1.0\n */",
"end": 237,
"score": 0.9792883992195129,
"start": 232,
"tag": "NAME",
"value": "Mr.Fu"
}
] | null | [] | package cn.bluegod.mycinema.DB;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @description: 连接数据库读写工具类
* @author: Mr.Fu
* @create: 2018-07-25 17:40
* @Version V1.0
*/
public class DB {
private static JdbcConnectionsPool pool = new JdbcConnectionsPool();
private Connection con;
private PreparedStatement statement;
public DB(){ }
private void getConnect() {
try {
con=pool.getConnection();
System.out.println("获得数据库连接成功");
} catch (SQLException e) {
System.out.println("获得数据库连接失败");
e.printStackTrace();
}
}
private void getStatement(String sql){
getConnect();
try {
statement=con.prepareStatement(sql);
System.out.println("获得statement成功");
} catch (SQLException e) {
System.out.println("获得statement失败");
e.printStackTrace();
}
}
public int executeUpdate(String sql,Object... objs) throws SQLException {
getStatement(sql);
if (objs!=null){
for (int i = 1; i <= objs.length; i++) {
statement.setObject(i, objs[i-1]);
}
}
int a=statement.executeUpdate();
closedStatement();
closedCon();
return a;
}
public <T> List<T> executeQuery(Class tClass, String sql, Object... value) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {
getStatement(sql);
if (value!=null){
for (int i = 1; i <= value.length; i++) {
statement.setObject(i, value[i-1]);
}
}
ResultSet rs = statement.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
List<T> list=new ArrayList<T>();
if (rs!=null) {
while (rs.next()) {
T entity = (T)tClass.newInstance();
for (int i = 0; i < rsmd.getColumnCount(); i++) {
Field field=tClass.getDeclaredField(rsmd.getColumnName(i+1));
field.setAccessible(true);
try {
field.set(entity, rs.getObject(i + 1));
}catch (Exception e){
field.set(entity, rs.getObject(i + 1)+"");
}
}
list.add(entity);
}
}
rs.close();
closedStatement();
closedCon();
return list;
}
public void closedStatement() throws SQLException {
if (statement!=null){
statement.close();
}
//
}
public void closedCon() throws SQLException {
if (con!=null){
con.close();
con=null;
}
}
}
| 2,985 | 0.532784 | 0.525232 | 103 | 27.281553 | 25.857119 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.572816 | false | false | 4 |
3962fbe2c82b111ffc7b762b0db1db864e08a60d | 35,622,458,773,341 | 9df56d8a9c01f2b7f9acc5745910c262bdc6a86a | /src/model/bo/SituacaoBO.java | 1b82d01f3f8e3ca5312addff1d9da2e19c0c7ece | [] | no_license | DemetrioProgram/ProjetoFinal | https://github.com/DemetrioProgram/ProjetoFinal | 0997ddd341879a487ec651c53c0deb6302801398 | 0a9536f7c6cffb4dffbf7decc392f98afd3c698f | refs/heads/master | 2022-07-10T03:01:30.187000 | 2019-12-11T22:20:11 | 2019-12-11T22:20:11 | 217,630,350 | 0 | 0 | null | false | 2022-06-29T17:48:48 | 2019-10-25T23:46:08 | 2019-12-11T22:20:32 | 2022-06-29T17:48:47 | 854 | 0 | 0 | 4 | Java | false | false | package model.bo;
import java.util.ArrayList;
import model.dao.SituacaoDAO;
public class SituacaoBO {
public ArrayList<String> consultarSituacao() {
SituacaoDAO situacaoDAO = new SituacaoDAO();
return situacaoDAO.consultar();
}
}
| UTF-8 | Java | 242 | java | SituacaoBO.java | Java | [] | null | [] | package model.bo;
import java.util.ArrayList;
import model.dao.SituacaoDAO;
public class SituacaoBO {
public ArrayList<String> consultarSituacao() {
SituacaoDAO situacaoDAO = new SituacaoDAO();
return situacaoDAO.consultar();
}
}
| 242 | 0.756198 | 0.756198 | 14 | 16.285715 | 17.301645 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 4 |
22d2f730a630fcdc29eec0af808b87f603491aa0 | 31,301,721,696,685 | 397fc8afbd144733fa7db2c39d2f0be3fc061b90 | /src/main/java/com/github/jerdeb/daqvalidator/Editor.java | d7aa516c73c14037bba0c2fabe906cc40892930c | [
"MIT"
] | permissive | jerdeb/daqvalidator | https://github.com/jerdeb/daqvalidator | f0ade8fac68b6b5f21759c3fc72727ed8cf17167 | 9da85323b3a2827ef39106e01467caffabd88887 | refs/heads/master | 2016-09-06T14:06:57.630000 | 2015-08-25T07:29:40 | 2015-08-25T07:29:40 | 33,206,367 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.jerdeb.daqvalidator;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
public class Editor {
Dataset clientSchemas = ValidatorFactory.getDataset();
private String uid = "";
private Model schema = null;
public Editor(String uid){
this.uid = uid;
this.schema = clientSchemas.getNamedModel(this.uid);
}
public void createCategory(String categoryURI, String label, String comment){
}
private void linkMetric(String dimensionURI, String metricURI){
}
private void createProperty(String uri){
}
}
| UTF-8 | Java | 575 | java | Editor.java | Java | [
{
"context": "package com.github.jerdeb.daqvalidator;\n\nimport com.hp.hpl.jena.query.Datas",
"end": 25,
"score": 0.9960172176361084,
"start": 19,
"tag": "USERNAME",
"value": "jerdeb"
}
] | null | [] | package com.github.jerdeb.daqvalidator;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
public class Editor {
Dataset clientSchemas = ValidatorFactory.getDataset();
private String uid = "";
private Model schema = null;
public Editor(String uid){
this.uid = uid;
this.schema = clientSchemas.getNamedModel(this.uid);
}
public void createCategory(String categoryURI, String label, String comment){
}
private void linkMetric(String dimensionURI, String metricURI){
}
private void createProperty(String uri){
}
}
| 575 | 0.735652 | 0.735652 | 29 | 18.827587 | 22.661024 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.275862 | false | false | 4 |
196f0fb17916c92a4bd320588d9a1b6c0af1aa12 | 35,278,861,392,995 | c294fa5cf1e4be717be208e66f13330f64fe49ac | /app/src/main/java/com/pmirkelam/mygroceryshopping/OrderRepository.java | 285d4ae44975b3a929ebe237ff230696ae6ae4b5 | [
"Apache-2.0"
] | permissive | perihanmirkelam/MyGroceryShopping | https://github.com/perihanmirkelam/MyGroceryShopping | ce40cb97c37e8d43936257966564289250f0729c | 1e8c90d6f72aa1b76d71046db498bee5d893ddb8 | refs/heads/master | 2020-07-30T01:34:09.108000 | 2019-09-23T16:44:58 | 2019-09-23T16:44:58 | 210,039,228 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pmirkelam.mygroceryshopping;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.pmirkelam.mygroceryshopping.model.Order;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class OrderRepository {
private static final String TAG = OrderRepository.class.getSimpleName();
private ArrayList<Order> orders = new ArrayList<>();
private MutableLiveData<List<Order>> mutableLiveData = new MutableLiveData<>();
public OrderRepository() {
}
public MutableLiveData<List<Order>> getMutableLiveData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://kariyertechchallenge.mockable.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
OrderService service = retrofit.create(OrderService.class);
Call<List<Order>> call = service.listOrders();
call.enqueue(new Callback<List<Order>>() {
@Override
public void onResponse(Call<List<Order>> call, Response<List<Order>> response) {
List<Order> orders = response.body();
mutableLiveData.setValue(orders);
}
@Override
public void onFailure(Call<List<Order>> call, Throwable t) {
Log.e(TAG, t.getMessage());
}
});
return mutableLiveData;
}
}
| UTF-8 | Java | 1,558 | java | OrderRepository.java | Java | [
{
"context": "package com.pmirkelam.mygroceryshopping;\n\nimport android.util.Log;\n\nimp",
"end": 21,
"score": 0.7101197242736816,
"start": 19,
"tag": "USERNAME",
"value": "am"
},
{
"context": "t androidx.lifecycle.MutableLiveData;\n\nimport com.pmirkelam.mygroceryshopping.model.Order;\n\nimport jav",
"end": 125,
"score": 0.5848273634910583,
"start": 123,
"tag": "USERNAME",
"value": "pm"
},
{
"context": "idx.lifecycle.MutableLiveData;\n\nimport com.pmirkelam.mygroceryshopping.model.Order;\n\nimport java.util.",
"end": 132,
"score": 0.7860483527183533,
"start": 130,
"tag": "USERNAME",
"value": "am"
}
] | null | [] | package com.pmirkelam.mygroceryshopping;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.pmirkelam.mygroceryshopping.model.Order;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class OrderRepository {
private static final String TAG = OrderRepository.class.getSimpleName();
private ArrayList<Order> orders = new ArrayList<>();
private MutableLiveData<List<Order>> mutableLiveData = new MutableLiveData<>();
public OrderRepository() {
}
public MutableLiveData<List<Order>> getMutableLiveData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://kariyertechchallenge.mockable.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
OrderService service = retrofit.create(OrderService.class);
Call<List<Order>> call = service.listOrders();
call.enqueue(new Callback<List<Order>>() {
@Override
public void onResponse(Call<List<Order>> call, Response<List<Order>> response) {
List<Order> orders = response.body();
mutableLiveData.setValue(orders);
}
@Override
public void onFailure(Call<List<Order>> call, Throwable t) {
Log.e(TAG, t.getMessage());
}
});
return mutableLiveData;
}
}
| 1,558 | 0.66303 | 0.65982 | 51 | 29.549019 | 26.268831 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false | 4 |
028c59eacf0941052969a8618b762bd87e7fcc2b | 28,269,474,802,617 | c33982c70c18bbc022c97a7a4aa8772697cd7d72 | /src/paquete1/Envoltorio.java | 3bf6f1b960835a60499ab75d3e2e06128a218f9b | [] | no_license | davidkowest/Programacion2020 | https://github.com/davidkowest/Programacion2020 | f0c3fcd523fe2abf3b2c8846bb800db354186989 | be5698335a13270da2fac36908c7a81c1c20c123 | refs/heads/master | 2023-01-18T16:19:17.718000 | 2020-11-30T13:12:39 | 2020-11-30T13:12:39 | 313,146,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package paquete1;
public class Envoltorio {
private Numero n;
public Envoltorio(Numero n) {
n.setValor(0);
}
public Numero getNumero() {
return n;
}
} | UTF-8 | Java | 162 | java | Envoltorio.java | Java | [] | null | [] | package paquete1;
public class Envoltorio {
private Numero n;
public Envoltorio(Numero n) {
n.setValor(0);
}
public Numero getNumero() {
return n;
}
} | 162 | 0.685185 | 0.67284 | 13 | 11.538462 | 11.014783 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
9dbe6eb8ceb4a1bc591e9a466216bf6901275b84 | 35,296,041,258,162 | 4c155b3463ebce8f9877926e7bee2331baf0c186 | /jdk9/src/interfacetest/TestInterface.java | 72b61fe3aedf23bb5317169490a259a31025b2ff | [] | no_license | gurq/jdk_features | https://github.com/gurq/jdk_features | 4372d31c75adaee16605e337f8f5823f1b58d30e | 5943fe9f44a9905bdc0493dd6cd0cf3a9438130f | refs/heads/master | 2021-05-20T19:59:12.173000 | 2020-05-09T07:19:43 | 2020-05-09T07:19:43 | 252,398,942 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package interfacetest;
public interface TestInterface {
private String hello() {
return "hello";
}
void say(final String message);
default void say() {
say(hello());
}
}
| UTF-8 | Java | 209 | java | TestInterface.java | Java | [] | null | [] | package interfacetest;
public interface TestInterface {
private String hello() {
return "hello";
}
void say(final String message);
default void say() {
say(hello());
}
}
| 209 | 0.593301 | 0.593301 | 13 | 15.076923 | 12.886854 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 4 |
436de51c5f1b6854ae279af4435a5a3c7f23a32f | 35,725,537,990,514 | 20dbcc8e6dad766f083fa8ca0c8b9905bdd70af3 | /MPPROJ/Sample/src/com/sample/pack/test.java | fad1e07b0520c0f99f17e431d99347d65f333dca | [] | no_license | pvishnu991/SampleProject | https://github.com/pvishnu991/SampleProject | 60126d7e0bcef62a366c3ef296e71c497139710e | 6cbdc7bb4c66eb15a410bfc467b374509e582d0b | refs/heads/master | 2020-08-20T09:40:19.941000 | 2019-11-04T17:32:55 | 2019-11-04T17:32:55 | 216,007,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sample.pack;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
//a change made
//third change made
//forth change
//fifth change
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("!!!!!!");System.out.println("!!!!!!");System.out.println("!!!!!!");
}
}
| UTF-8 | Java | 1,316 | java | test.java | Java | [] | null | [] | package com.sample.pack;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
//a change made
//third change made
//forth change
//fifth change
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("hi ho lets go !!!!!!");
System.out.println("!!!!!!");
System.out.println("!!!!!!");System.out.println("!!!!!!");System.out.println("!!!!!!");
}
}
| 1,316 | 0.547112 | 0.547112 | 41 | 30.097561 | 20.564953 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.487805 | false | false | 4 |
93869cd565b0a542dd841ab8bc60ef4c64bc559b | 34,144,990,036,423 | e2ae04d0e004c15c018f114783520a661030fa97 | /curso06.stillUseful_2.5/src/main/java/es/cic/curso06/stillUseful/service/producto/CategoriaService2.java | 52d06840b3143b39356b256d96658fed8fca440d | [
"MIT"
] | permissive | jmccMantamusica/java_cic_02 | https://github.com/jmccMantamusica/java_cic_02 | 5442ef93b570283b6a14a043f08fe24a1d0034f1 | a70d9c637868c014543d896e106be5c87a3ffce1 | refs/heads/master | 2021-09-05T18:46:57.770000 | 2018-01-30T10:54:00 | 2018-01-30T10:54:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package es.cic.curso06.stillUseful.service.producto;
import java.util.List;
import es.cic.curso06.stillUseful.dominio.producto.Categoria;
public interface CategoriaService2 {
Long aniadirCategoria2(String nombre, String descripcion);
List<Categoria> obtenerCategorias();
//uno, READ
Categoria obtenerCategoria(Long id);
//UPDATE
Categoria actualizarCategoria(Categoria modificada);
//DELETE
void borrarcategoriaRepository(Long id);
} | UTF-8 | Java | 450 | java | CategoriaService2.java | Java | [] | null | [] | package es.cic.curso06.stillUseful.service.producto;
import java.util.List;
import es.cic.curso06.stillUseful.dominio.producto.Categoria;
public interface CategoriaService2 {
Long aniadirCategoria2(String nombre, String descripcion);
List<Categoria> obtenerCategorias();
//uno, READ
Categoria obtenerCategoria(Long id);
//UPDATE
Categoria actualizarCategoria(Categoria modificada);
//DELETE
void borrarcategoriaRepository(Long id);
} | 450 | 0.8 | 0.786667 | 22 | 19.5 | 22.213326 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false | 4 |
70f896a37713aba03a561ce1f9461a640c0ca9a4 | 34,299,608,857,096 | d4c0c94e5ac83cd0d38876f323b24b8a777e4489 | /src/main/java/com/middle/main/exception/RequestLimitException.java | 94d63864c0b814faa9873dbbacb99d19a9eb68ce | [] | no_license | wl00254294/MiddleServer | https://github.com/wl00254294/MiddleServer | 7e08f6cf2aafcd2d8cc2fe16008a2d38ddaf04b0 | 0e75cc3d8a5101699b5f269bb65bdf1372bd2820 | refs/heads/master | 2023-04-27T21:32:03.017000 | 2019-08-21T08:06:32 | 2019-08-21T08:06:32 | 199,357,840 | 0 | 0 | null | false | 2023-04-14T17:56:18 | 2019-07-29T01:39:37 | 2019-08-21T08:06:48 | 2023-04-14T17:56:18 | 76 | 0 | 0 | 2 | Java | false | false | package com.middle.main.exception;
public class RequestLimitException extends Exception{
private static final long serialVersionUID = 1364225358754654702L;
public RequestLimitException() {
super("API Request number has Limtit");
}
public RequestLimitException(String message) {
super(message);
}
}
| UTF-8 | Java | 364 | java | RequestLimitException.java | Java | [] | null | [] | package com.middle.main.exception;
public class RequestLimitException extends Exception{
private static final long serialVersionUID = 1364225358754654702L;
public RequestLimitException() {
super("API Request number has Limtit");
}
public RequestLimitException(String message) {
super(message);
}
}
| 364 | 0.67033 | 0.618132 | 13 | 26 | 24.232845 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 4 |
f53bc5a5c0170dfa586a086adbac8949aafd1110 | 36,438,502,563,171 | 0dc5569decf81d48d6424e5480f9a3a579301423 | /src/main/java/com/example/spring_boot_api/exceptions/ExceptionDetails.java | abc9ae414d76a02cd477e084c37de505bd16be5b | [] | no_license | cckfnn/spring_boot_api | https://github.com/cckfnn/spring_boot_api | bffaebd22cbac8eebbdb7b0b5b30e6a41d4e7474 | 7bd6ad874e1f42e58468bb51250f78404ff3eca0 | refs/heads/master | 2023-02-15T06:42:41.303000 | 2021-01-12T06:59:37 | 2021-01-12T06:59:37 | 320,294,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.spring_boot_api.exceptions;
import lombok.*;
import java.util.Date;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class ExceptionDetails {
private Date timestamp;
private String message;
private String details;
private String path;
} | UTF-8 | Java | 307 | java | ExceptionDetails.java | Java | [] | null | [] | package com.example.spring_boot_api.exceptions;
import lombok.*;
import java.util.Date;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class ExceptionDetails {
private Date timestamp;
private String message;
private String details;
private String path;
} | 307 | 0.76873 | 0.76873 | 18 | 16.111111 | 12.757956 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 4 |
58f623c1a3b47abce9e4fccd49e720fa0578728f | 10,806,137,783,072 | f08256664e46e5ac1466f5c67dadce9e19b4e173 | /sources/p163g/p503n/p504a/C11839v.java | eafc09bba24575592abfbebe10f6e5c1e0be0f53 | [] | no_license | IOIIIO/DisneyPlusSource | https://github.com/IOIIIO/DisneyPlusSource | 5f981420df36bfbc3313756ffc7872d84246488d | 658947960bd71c0582324f045a400ae6c3147cc3 | refs/heads/master | 2020-09-30T22:33:43.011000 | 2019-12-11T22:27:58 | 2019-12-11T22:27:58 | 227,382,471 | 6 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package p163g.p503n.p504a;
import p520io.reactivex.disposables.Disposable;
import p520io.reactivex.functions.C11945a;
import p520io.reactivex.functions.Consumer;
/* renamed from: g.n.a.v */
/* compiled from: CompletableSubscribeProxy */
public interface C11839v {
/* renamed from: a */
Disposable mo29926a(C11945a aVar, Consumer<? super Throwable> consumer);
}
| UTF-8 | Java | 371 | java | C11839v.java | Java | [] | null | [] | package p163g.p503n.p504a;
import p520io.reactivex.disposables.Disposable;
import p520io.reactivex.functions.C11945a;
import p520io.reactivex.functions.Consumer;
/* renamed from: g.n.a.v */
/* compiled from: CompletableSubscribeProxy */
public interface C11839v {
/* renamed from: a */
Disposable mo29926a(C11945a aVar, Consumer<? super Throwable> consumer);
}
| 371 | 0.765499 | 0.663073 | 12 | 29.916666 | 21.75798 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
82ad53c9a7e4485d3e227da657271879412d1f2f | 36,541,581,779,962 | 44c72a13600554fb645d1e4b432cbfec5481deef | /Project Euler/src/Problem001.java | 17d8662a35c9afad888beaf6f6877a7a517384f6 | [] | no_license | mnitchie/ProjectEuler | https://github.com/mnitchie/ProjectEuler | 0102e40445c825c92e9c7bcc4a00ac2016a60de2 | 72b62986e841a4c26eb982996004048d8f4eafd9 | refs/heads/master | 2016-09-10T19:53:35.156000 | 2014-08-06T16:55:08 | 2014-08-06T16:55:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Project Euler problem 1.
* This program sums up all the natural numbers up to
* 1000 that are multiples of 3 or 5
*/
public class Problem001 {
public static void main(String[] args) {
int sum = 0;
int i;
long start = System.currentTimeMillis();
for (i = 1; i < 1000; i++) {
if ((i % 3 == 0) || (i % 5 == 0)) {
sum = sum + i;
}
}
long end = System.currentTimeMillis();
System.out.println("Solution = " + sum);
System.out.println("Time taken: " + (end - start) + "ms");
}
}
| UTF-8 | Java | 597 | java | Problem001.java | Java | [] | null | [] | /**
* Project Euler problem 1.
* This program sums up all the natural numbers up to
* 1000 that are multiples of 3 or 5
*/
public class Problem001 {
public static void main(String[] args) {
int sum = 0;
int i;
long start = System.currentTimeMillis();
for (i = 1; i < 1000; i++) {
if ((i % 3 == 0) || (i % 5 == 0)) {
sum = sum + i;
}
}
long end = System.currentTimeMillis();
System.out.println("Solution = " + sum);
System.out.println("Time taken: " + (end - start) + "ms");
}
}
| 597 | 0.500838 | 0.467337 | 23 | 24.956522 | 20.264507 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 4 |
e85739904c7ffaf171f05033080820cbe0a54eeb | 36,593,121,379,939 | c785eb7007e21834c9d7126a6b55d575cd2a51a3 | /src/main/java/cards/SkyTemple.java | fe802f7cfb8260f9e7e381f73749d55b318466b2 | [] | no_license | RyanHecht/cardstone | https://github.com/RyanHecht/cardstone | 36f3b376820a3cba8627e430bab395df061ed094 | a3f16a8290b04701e612253721ae0a8c084ac3e5 | refs/heads/master | 2021-01-19T14:25:00.054000 | 2017-09-23T18:41:19 | 2017-09-23T18:41:19 | 84,145,899 | 3 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cards;
import java.util.LinkedList;
import java.util.List;
import cardgamelibrary.AuraCard;
import cardgamelibrary.Board;
import cardgamelibrary.Card;
import cardgamelibrary.CardType;
import cardgamelibrary.Effect;
import cardgamelibrary.ElementType;
import cardgamelibrary.ManaPool;
import cardgamelibrary.Zone;
import effects.AddToOccEffect;
import effects.CardDrawEffect;
import effects.EffectMaker;
import effects.EffectType;
import effects.RequestCardChooseEffect;
import game.Player;
import templates.ChooseResponderCard;
public class SkyTemple extends AuraCard implements ChooseResponderCard{
private static final String defaultImage = "images/SkyTemple.jpg";
private static final String defaultName = "Sky Temple";
private static final String defaultText = "Whenever you would draw a card on your turn, instead search your deck for an air card or air element and add it to your hand.";
private static final CardType defaultType = CardType.AURA;
public SkyTemple(Player owner) {
super(new ManaPool(20, 0, 0, 2, 0, 0), defaultImage, owner, defaultName, defaultText, defaultType);
}
public boolean onProposedEffect(Effect e, Zone z, Board b){
if(z.equals(Zone.AURA_BOARD)){
if(e.getType().equals(EffectType.CARD_DRAWN)){
CardDrawEffect cde = (CardDrawEffect)e;
if(cde.getTarget().equals(getOwner())){
if(b.getActivePlayer().equals(getOwner())){
return true;
}
}
}
}
return false;
}
public Effect getNewProposition(Effect e, Zone z){
return new EffectMaker((Board b) -> {
List<Card> options = new LinkedList<>();
for(Card c : b.getOcc(getOwner(), Zone.DECK)){
if(c.hasElement(ElementType.AIR) || c.isA(AirElement.class)){
options.add(c);
}
}
if(options.size() != 0){
return new RequestCardChooseEffect(options,getOwner(),this,this);
}
else{
return e;
}
},this);
}
public Effect getChooseEffect(ChooseResponderCard chooser, Card chosenCard) {
return new AddToOccEffect(chosenCard,getOwner(),Zone.HAND,Zone.DECK,this);
}
}
| UTF-8 | Java | 2,050 | java | SkyTemple.java | Java | [] | null | [] | package cards;
import java.util.LinkedList;
import java.util.List;
import cardgamelibrary.AuraCard;
import cardgamelibrary.Board;
import cardgamelibrary.Card;
import cardgamelibrary.CardType;
import cardgamelibrary.Effect;
import cardgamelibrary.ElementType;
import cardgamelibrary.ManaPool;
import cardgamelibrary.Zone;
import effects.AddToOccEffect;
import effects.CardDrawEffect;
import effects.EffectMaker;
import effects.EffectType;
import effects.RequestCardChooseEffect;
import game.Player;
import templates.ChooseResponderCard;
public class SkyTemple extends AuraCard implements ChooseResponderCard{
private static final String defaultImage = "images/SkyTemple.jpg";
private static final String defaultName = "Sky Temple";
private static final String defaultText = "Whenever you would draw a card on your turn, instead search your deck for an air card or air element and add it to your hand.";
private static final CardType defaultType = CardType.AURA;
public SkyTemple(Player owner) {
super(new ManaPool(20, 0, 0, 2, 0, 0), defaultImage, owner, defaultName, defaultText, defaultType);
}
public boolean onProposedEffect(Effect e, Zone z, Board b){
if(z.equals(Zone.AURA_BOARD)){
if(e.getType().equals(EffectType.CARD_DRAWN)){
CardDrawEffect cde = (CardDrawEffect)e;
if(cde.getTarget().equals(getOwner())){
if(b.getActivePlayer().equals(getOwner())){
return true;
}
}
}
}
return false;
}
public Effect getNewProposition(Effect e, Zone z){
return new EffectMaker((Board b) -> {
List<Card> options = new LinkedList<>();
for(Card c : b.getOcc(getOwner(), Zone.DECK)){
if(c.hasElement(ElementType.AIR) || c.isA(AirElement.class)){
options.add(c);
}
}
if(options.size() != 0){
return new RequestCardChooseEffect(options,getOwner(),this,this);
}
else{
return e;
}
},this);
}
public Effect getChooseEffect(ChooseResponderCard chooser, Card chosenCard) {
return new AddToOccEffect(chosenCard,getOwner(),Zone.HAND,Zone.DECK,this);
}
}
| 2,050 | 0.740488 | 0.736585 | 69 | 28.710144 | 29.430883 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.391304 | false | false | 4 |
fa6ee8428f743a6248caff6b24c45b9ffe1d5d20 | 33,621,004,057,728 | 7ef52de9984aaa6bbb393b01117c3ac98cbcb90d | /trxapi/src/com/trx/neon/model/building/NeonBuildingFloor.java | 34879fc954b9a1cc47148fce0249305772b88971 | [] | no_license | jax79sg/dhBFTLocal | https://github.com/jax79sg/dhBFTLocal | c22742fe059b78a53af12881d72be09269cb04b7 | a00754d3d172418ca91de24676271c3265843914 | refs/heads/master | 2021-07-25T08:06:38.239000 | 2019-01-10T03:46:25 | 2019-01-10T03:46:25 | 155,312,775 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /******************************************************************************
*
* Copyright 2017, TRX Systems, Inc. All Rights Reserved.
*
* TRX Systems, Inc.
* 7500 Greenway Center Drive, Suite 420
* Greenbelt, Maryland 20770
*
* Tel: (301) 313-0053
* email: info@trxsystems.com
*
*****************************************************************************/
package com.trx.neon.model.building;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* A Neon Building Floor is identified by a zero-based floorNumber, and contains
* a building outline and potentially a floorplan ID and georeferencing information
* for that image
* @author Travis
*
*/
public class NeonBuildingFloor implements Parcelable
{
/**
* The floor number in the containing building
*
* The ground floor is index 0, basement floors have negative indices,
* and above-ground floors have positive indices
*/
private final int FloorNumber;
/**
* A friendly label for the floor,
* such as "B1" or "C"
*/
private final String Label;
/**
* An outline for this floor (can be different from other floors)
*/
private final NeonFloorOutline Outline;
/**
* Set of LatLongs that georeference floor plan image
* Use Neon.getFloorPlan to retrieve the floor plan image
*/
private final ArrayList<LatLong> FloorPlanCorners;
/**
* Unique ID for the floor plan image
* Use Neon.getFloorPlan to retrieve the floor plan image
*/
private final String FloorPlanImageID;
public NeonBuildingFloor(
int floorNumber,
String label,
NeonFloorOutline outline,
ArrayList<LatLong> floorPlanCorners,
String floorPlanImageID)
{
this.FloorNumber = floorNumber;
this.Label = label;
this.Outline = new NeonFloorOutline(outline);
this.FloorPlanCorners = floorPlanCorners;
this.FloorPlanImageID = floorPlanImageID;
}
public int getFloorNumber() {
return FloorNumber;
}
public String getLabel() {
return Label;
}
public NeonFloorOutline getOutline() {
return Outline;
}
public String getFloorPlanImageID() {return FloorPlanImageID; }
public ArrayList<LatLong> getFloorPlanCorners() {return FloorPlanCorners;}
/**
* @return Whether the building floor has an associated floor plan image
*/
public boolean hasFloorPlan() {
return (FloorPlanImageID != null);
}
/**
* Used for sending data across binders
*/
private NeonBuildingFloor(Parcel in)
{
FloorNumber = in.readInt();
Label = in.readString();
Outline = new NeonFloorOutline(in);
FloorPlanCorners = new ArrayList<>();
in.readTypedList(FloorPlanCorners, LatLong.CREATOR);
FloorPlanImageID = in.readString();
}
public static final Creator<NeonBuildingFloor> CREATOR = new Creator<NeonBuildingFloor>() {
@Override
public NeonBuildingFloor createFromParcel(Parcel in) {
return new NeonBuildingFloor(in);
}
@Override
public NeonBuildingFloor[] newArray(int size) {
return new NeonBuildingFloor[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(FloorNumber);
dest.writeString(Label);
Outline.writeToParcel(dest, flags);
dest.writeTypedList(FloorPlanCorners);
dest.writeString(FloorPlanImageID);
}
}
| UTF-8 | Java | 3,314 | java | NeonBuildingFloor.java | Java | [
{
"context": " 20770\n *\n * Tel: (301) 313-0053\n * email: info@trxsystems.com\n *\n *********************************************",
"end": 308,
"score": 0.999928891658783,
"start": 289,
"tag": "EMAIL",
"value": "info@trxsystems.com"
},
{
"context": "ferencing information\n * for that image\n * @author Travis\n *\n */\npublic class NeonBuildingFloor implements ",
"end": 720,
"score": 0.9961502552032471,
"start": 714,
"tag": "NAME",
"value": "Travis"
}
] | null | [] | /******************************************************************************
*
* Copyright 2017, TRX Systems, Inc. All Rights Reserved.
*
* TRX Systems, Inc.
* 7500 Greenway Center Drive, Suite 420
* Greenbelt, Maryland 20770
*
* Tel: (301) 313-0053
* email: <EMAIL>
*
*****************************************************************************/
package com.trx.neon.model.building;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* A Neon Building Floor is identified by a zero-based floorNumber, and contains
* a building outline and potentially a floorplan ID and georeferencing information
* for that image
* @author Travis
*
*/
public class NeonBuildingFloor implements Parcelable
{
/**
* The floor number in the containing building
*
* The ground floor is index 0, basement floors have negative indices,
* and above-ground floors have positive indices
*/
private final int FloorNumber;
/**
* A friendly label for the floor,
* such as "B1" or "C"
*/
private final String Label;
/**
* An outline for this floor (can be different from other floors)
*/
private final NeonFloorOutline Outline;
/**
* Set of LatLongs that georeference floor plan image
* Use Neon.getFloorPlan to retrieve the floor plan image
*/
private final ArrayList<LatLong> FloorPlanCorners;
/**
* Unique ID for the floor plan image
* Use Neon.getFloorPlan to retrieve the floor plan image
*/
private final String FloorPlanImageID;
public NeonBuildingFloor(
int floorNumber,
String label,
NeonFloorOutline outline,
ArrayList<LatLong> floorPlanCorners,
String floorPlanImageID)
{
this.FloorNumber = floorNumber;
this.Label = label;
this.Outline = new NeonFloorOutline(outline);
this.FloorPlanCorners = floorPlanCorners;
this.FloorPlanImageID = floorPlanImageID;
}
public int getFloorNumber() {
return FloorNumber;
}
public String getLabel() {
return Label;
}
public NeonFloorOutline getOutline() {
return Outline;
}
public String getFloorPlanImageID() {return FloorPlanImageID; }
public ArrayList<LatLong> getFloorPlanCorners() {return FloorPlanCorners;}
/**
* @return Whether the building floor has an associated floor plan image
*/
public boolean hasFloorPlan() {
return (FloorPlanImageID != null);
}
/**
* Used for sending data across binders
*/
private NeonBuildingFloor(Parcel in)
{
FloorNumber = in.readInt();
Label = in.readString();
Outline = new NeonFloorOutline(in);
FloorPlanCorners = new ArrayList<>();
in.readTypedList(FloorPlanCorners, LatLong.CREATOR);
FloorPlanImageID = in.readString();
}
public static final Creator<NeonBuildingFloor> CREATOR = new Creator<NeonBuildingFloor>() {
@Override
public NeonBuildingFloor createFromParcel(Parcel in) {
return new NeonBuildingFloor(in);
}
@Override
public NeonBuildingFloor[] newArray(int size) {
return new NeonBuildingFloor[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(FloorNumber);
dest.writeString(Label);
Outline.writeToParcel(dest, flags);
dest.writeTypedList(FloorPlanCorners);
dest.writeString(FloorPlanImageID);
}
}
| 3,302 | 0.692517 | 0.683766 | 135 | 23.548147 | 23.204315 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.355556 | false | false | 4 |
ff44f3dddac787befdbff242e1f19df90b23fd18 | 37,005,438,240,821 | 7af928921898828426b7af6eff4dd9b7e4252817 | /platforms/android-28/android-stubs-src/file/android/view/autofill/AutofillManager.java | bd6f696589b7379723aa75d3cfd87b739844df88 | [] | no_license | Davidxiahao/RAPID | https://github.com/Davidxiahao/RAPID | 40c546a739a818a6562d0c9bce5df9f1a462d92b | e99f46155a2f3e6b84324ba75ecd22a278ba7167 | refs/heads/master | 2023-06-27T13:09:02.418000 | 2020-03-06T01:38:16 | 2020-03-06T01:38:16 | 239,509,129 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 android.view.autofill;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.view.View;
import android.util.SparseArray;
import android.service.autofill.AutofillService;
import android.service.autofill.FillEventHistory;
import android.service.autofill.UserData;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
/**
* The {@link AutofillManager} provides ways for apps and custom views to integrate with the
* Autofill Framework lifecycle.
*
* <p>The autofill lifecycle starts with the creation of an autofill context associated with an
* activity context; the autofill context is created when one of the following methods is called for
* the first time in an activity context, and the current user has an enabled autofill service:
*
* <ul>
* <li>{@link #notifyViewEntered(View)}
* <li>{@link #notifyViewEntered(View, int, Rect)}
* <li>{@link #requestAutofill(View)}
* </ul>
*
* <p>Tipically, the context is automatically created when the first view of the activity is
* focused because {@code View.onFocusChanged()} indirectly calls
* {@link #notifyViewEntered(View)}. App developers can call {@link #requestAutofill(View)} to
* explicitly create it (for example, a custom view developer could offer a contextual menu action
* in a text-field view to let users manually request autofill).
*
* <p>After the context is created, the Android System creates a {@link android.view.ViewStructure}
* that represents the view hierarchy by calling
* {@link View#dispatchProvideAutofillStructure(android.view.ViewStructure, int)} in the root views
* of all application windows. By default, {@code dispatchProvideAutofillStructure()} results in
* subsequent calls to {@link View#onProvideAutofillStructure(android.view.ViewStructure, int)} and
* {@link View#onProvideAutofillVirtualStructure(android.view.ViewStructure, int)} for each view in
* the hierarchy.
*
* <p>The resulting {@link android.view.ViewStructure} is then passed to the autofill service, which
* parses it looking for views that can be autofilled. If the service finds such views, it returns
* a data structure to the Android System containing the following optional info:
*
* <ul>
* <li>Datasets used to autofill subsets of views in the activity.
* <li>Id of views that the service can save their values for future autofilling.
* </ul>
*
* <p>When the service returns datasets, the Android System displays an autofill dataset picker
* UI associated with the view, when the view is focused on and is part of a dataset.
* The application can be notified when the UI is shown by registering an
* {@link AutofillCallback} through {@link #registerCallback(AutofillCallback)}. When the user
* selects a dataset from the UI, all views present in the dataset are autofilled, through
* calls to {@link View#autofill(AutofillValue)} or {@link View#autofill(SparseArray)}.
*
* <p>When the service returns ids of savable views, the Android System keeps track of changes
* made to these views, so they can be used to determine if the autofill save UI is shown later.
*
* <p>The context is then finished when one of the following occurs:
*
* <ul>
* <li>{@link #commit()} is called or all savable views are gone.
* <li>{@link #cancel()} is called.
* </ul>
*
* <p>Finally, after the autofill context is commited (i.e., not cancelled), the Android System
* shows an autofill save UI if the value of savable views have changed. If the user selects the
* option to Save, the current value of the views is then sent to the autofill service.
*
* <p>It is safe to call into its methods from any thread.
* Requires the {@link android.content.pm.PackageManager#FEATURE_AUTOFILL PackageManager#FEATURE_AUTOFILL} feature which can be detected using {@link android.content.pm.PackageManager#hasSystemFeature(String) PackageManager.hasSystemFeature(String)}.
*/
@SuppressWarnings({"unchecked", "deprecation", "all"})
public final class AutofillManager {
AutofillManager() { throw new RuntimeException("Stub!"); }
/**
* Checks whether autofill is enabled for the current user.
*
* <p>Typically used to determine whether the option to explicitly request autofill should
* be offered - see {@link #requestAutofill(View)}.
*
* @return whether autofill is enabled for the current user.
*/
public boolean isEnabled() { throw new RuntimeException("Stub!"); }
/**
* Explicitly requests a new autofill context.
*
* <p>Normally, the autofill context is automatically started if necessary when
* {@link #notifyViewEntered(View)} is called, but this method should be used in the
* cases where it must be explicitly started. For example, when the view offers an AUTOFILL
* option on its contextual overflow menu, and the user selects it.
*
* @param view view requesting the new autofill context.
* This value must never be {@code null}.
*/
public void requestAutofill(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Explicitly requests a new autofill context for virtual views.
*
* <p>Normally, the autofill context is automatically started if necessary when
* {@link #notifyViewEntered(View, int, Rect)} is called, but this method should be used in the
* cases where it must be explicitly started. For example, when the virtual view offers an
* AUTOFILL option on its contextual overflow menu, and the user selects it.
*
* <p>The virtual view boundaries must be absolute screen coordinates. For example, if the
* parent view uses {@code bounds} to draw the virtual view inside its Canvas,
* the absolute bounds could be calculated by:
*
* <pre class="prettyprint">
* int offset[] = new int[2];
* getLocationOnScreen(offset);
* Rect absBounds = new Rect(bounds.left + offset[0],
* bounds.top + offset[1],
* bounds.right + offset[0], bounds.bottom + offset[1]);
* </pre>
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
* @param absBounds absolute boundaries of the virtual view in the screen.
* This value must never be {@code null}.
*/
public void requestAutofill(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, @androidx.annotation.RecentlyNonNull android.graphics.Rect absBounds) { throw new RuntimeException("Stub!"); }
/**
* Called when a {@link View} that supports autofill is entered.
*
* @param view {@link View} that was entered.
* This value must never be {@code null}.
*/
public void notifyViewEntered(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called when a {@link View} that supports autofill is exited.
*
* @param view {@link View} that was exited.
* This value must never be {@code null}.
*/
public void notifyViewExited(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called when a {@link View view's} visibility changed.
*
* @param view {@link View} that was exited.
* This value must never be {@code null}.
* @param isVisible visible if the view is visible in the view hierarchy.
*/
public void notifyViewVisibilityChanged(@androidx.annotation.RecentlyNonNull android.view.View view, boolean isVisible) { throw new RuntimeException("Stub!"); }
/**
* Called when a virtual view's visibility changed.
*
* @param view {@link View} that was exited.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
* @param isVisible visible if the view is visible in the view hierarchy.
*/
public void notifyViewVisibilityChanged(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, boolean isVisible) { throw new RuntimeException("Stub!"); }
/**
* Called when a virtual view that supports autofill is entered.
*
* <p>The virtual view boundaries must be absolute screen coordinates. For example, if the
* parent, non-virtual view uses {@code bounds} to draw the virtual view inside its Canvas,
* the absolute bounds could be calculated by:
*
* <pre class="prettyprint">
* int offset[] = new int[2];
* getLocationOnScreen(offset);
* Rect absBounds = new Rect(bounds.left + offset[0],
* bounds.top + offset[1],
* bounds.right + offset[0], bounds.bottom + offset[1]);
* </pre>
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
* @param absBounds absolute boundaries of the virtual view in the screen.
* This value must never be {@code null}.
*/
public void notifyViewEntered(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, @androidx.annotation.RecentlyNonNull android.graphics.Rect absBounds) { throw new RuntimeException("Stub!"); }
/**
* Called when a virtual view that supports autofill is exited.
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
*/
public void notifyViewExited(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the value of an autofillable {@link View} changed.
*
* @param view view whose value changed.
*/
public void notifyValueChanged(android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the value of an autofillable virtual view has changed.
*
* @param view the virtual view parent.
* @param virtualId id identifying the virtual child inside the parent view.
* @param value new value of the child.
*/
public void notifyValueChanged(android.view.View view, int virtualId, android.view.autofill.AutofillValue value) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate a {@link View} is clicked.
*
* @param view view that has been clicked.
* This value must never be {@code null}.
*/
public void notifyViewClicked(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate a virtual view has been clicked.
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
*/
public void notifyViewClicked(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the current autofill context should be commited.
*
* <p>This method is typically called by {@link View Views} that manage virtual views; for
* example, when the view is rendering an {@code HTML} page with a form and virtual views
* that represent the HTML elements, it should call this method after the form is submitted and
* another page is rendered.
*
* <p><b>Note:</b> This method does not need to be called on regular application lifecycle
* methods such as {@link android.app.Activity#finish()}.
*/
public void commit() { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the current autofill context should be cancelled.
*
* <p>This method is typically called by {@link View Views} that manage virtual views; for
* example, when the view is rendering an {@code HTML} page with a form and virtual views
* that represent the HTML elements, it should call this method if the user does not post the
* form but moves to another form in this page.
*
* <p><b>Note:</b> This method does not need to be called on regular application lifecycle
* methods such as {@link android.app.Activity#finish()}.
*/
public void cancel() { throw new RuntimeException("Stub!"); }
/**
* If the app calling this API has enabled autofill services they
* will be disabled.
*/
public void disableAutofillServices() { throw new RuntimeException("Stub!"); }
/**
* Returns {@code true} if the calling application provides a {@link AutofillService} that is
* enabled for the current user, or {@code false} otherwise.
*/
public boolean hasEnabledAutofillServices() { throw new RuntimeException("Stub!"); }
/**
* Returns the component name of the {@link AutofillService} that is enabled for the current
* user.
* @return This value may be {@code null}.
*/
@androidx.annotation.RecentlyNullable public android.content.ComponentName getAutofillServiceComponentName() { throw new RuntimeException("Stub!"); }
/**
* Gets the id of the {@link UserData} used for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p>This method is useful when the service must check the status of the {@link UserData} in
* the device without fetching the whole object.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
*
* @return id of the {@link UserData} previously set by {@link #setUserData(UserData)}
* or {@code null} if it was reset or if the caller currently does not have an enabled autofill
* service for the user.
*/
@androidx.annotation.RecentlyNullable public java.lang.String getUserDataId() { throw new RuntimeException("Stub!"); }
/**
* Gets the user data used for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
*
* @return value previously set by {@link #setUserData(UserData)} or {@code null} if it was
* reset or if the caller currently does not have an enabled autofill service for the user.
*/
@androidx.annotation.RecentlyNullable public android.service.autofill.UserData getUserData() { throw new RuntimeException("Stub!"); }
/**
* Sets the {@link UserData} used for
* <a href="AutofillService.html#FieldClassification">field classification</a>
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
* @param userData This value may be {@code null}.
*/
public void setUserData(@androidx.annotation.RecentlyNullable android.service.autofill.UserData userData) { throw new RuntimeException("Stub!"); }
/**
* Checks if <a href="AutofillService.html#FieldClassification">field classification</a> is
* enabled.
*
* <p>As field classification is an expensive operation, it could be disabled, either
* temporarily (for example, because the service exceeded a rate-limit threshold) or
* permanently (for example, because the device is a low-level device).
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
*/
public boolean isFieldClassificationEnabled() { throw new RuntimeException("Stub!"); }
/**
* Gets the name of the default algorithm used for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p>The default algorithm is used when the algorithm on {@link UserData} is invalid or not
* set.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
* @return This value may be {@code null}.
*/
@androidx.annotation.RecentlyNullable public java.lang.String getDefaultFieldClassificationAlgorithm() { throw new RuntimeException("Stub!"); }
/**
* Gets the name of all algorithms currently available for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it returns an empty list if the caller currently doesn't have an enabled autofill service
* for the user.
* @return This value will never be {@code null}.
*/
@androidx.annotation.RecentlyNonNull public java.util.List<java.lang.String> getAvailableFieldClassificationAlgorithms() { throw new RuntimeException("Stub!"); }
/**
* Returns {@code true} if autofill is supported by the current device and
* is supported for this user.
*
* <p>Autofill is typically supported, but it could be unsupported in cases like:
* <ol>
* <li>Low-end devices.
* <li>Device policy rules that forbid its usage.
* </ol>
*/
public boolean isAutofillSupported() { throw new RuntimeException("Stub!"); }
/**
* Gets the next unique autofill ID for the activity context.
*
* <p>Typically used to manage views whose content is recycled - see
* {@link View#setAutofillId(AutofillId)} for more info.
*
* @return An ID that is unique in the activity, or {@code null} if autofill is not supported in
* the {@link Context} associated with this {@link AutofillManager}.
*/
@androidx.annotation.RecentlyNullable public android.view.autofill.AutofillId getNextAutofillId() { throw new RuntimeException("Stub!"); }
/**
* Registers a {@link AutofillCallback} to receive autofill events.
*
* @param callback callback to receive events.
* This value may be {@code null}.
*/
public void registerCallback(@androidx.annotation.RecentlyNullable android.view.autofill.AutofillManager.AutofillCallback callback) { throw new RuntimeException("Stub!"); }
/**
* Unregisters a {@link AutofillCallback} to receive autofill events.
*
* @param callback callback to stop receiving events.
* This value may be {@code null}.
*/
public void unregisterCallback(@androidx.annotation.RecentlyNullable android.view.autofill.AutofillManager.AutofillCallback callback) { throw new RuntimeException("Stub!"); }
/**
* Intent extra: The assist structure which captures the filled screen.
*
* <p>
* Type: {@link android.app.assist.AssistStructure}
*/
public static final java.lang.String EXTRA_ASSIST_STRUCTURE = "android.view.autofill.extra.ASSIST_STRUCTURE";
/**
* Intent extra: The result of an authentication operation. It is
* either a fully populated {@link android.service.autofill.FillResponse}
* or a fully populated {@link android.service.autofill.Dataset} if
* a response or a dataset is being authenticated respectively.
*
* <p>
* Type: {@link android.service.autofill.FillResponse} or a
* {@link android.service.autofill.Dataset}
*/
public static final java.lang.String EXTRA_AUTHENTICATION_RESULT = "android.view.autofill.extra.AUTHENTICATION_RESULT";
/**
* Intent extra: The optional extras provided by the
* {@link android.service.autofill.AutofillService}.
*
* <p>For example, when the service responds to a {@link
* android.service.autofill.FillCallback#onSuccess(android.service.autofill.FillResponse)} with
* a {@code FillResponse} that requires authentication, the Intent that launches the
* service authentication will contain the Bundle set by
* {@link android.service.autofill.FillResponse.Builder#setClientState(Bundle)} on this extra.
*
* <p>On Android {@link android.os.Build.VERSION_CODES#P} and higher, the autofill service
* can also add this bundle to the {@link Intent} set as the
* {@link android.app.Activity#setResult(int, Intent) result} for an authentication request,
* so the bundle can be recovered later on
* {@link android.service.autofill.SaveRequest#getClientState()}.
*
* <p>
* Type: {@link android.os.Bundle}
*/
public static final java.lang.String EXTRA_CLIENT_STATE = "android.view.autofill.extra.CLIENT_STATE";
/**
* Callback for autofill related events.
*
* <p>Typically used for applications that display their own "auto-complete" views, so they can
* enable / disable such views when the autofill UI is shown / hidden.
*/
@SuppressWarnings({"unchecked", "deprecation", "all"})
public abstract static class AutofillCallback {
public AutofillCallback() { throw new RuntimeException("Stub!"); }
/**
* Called after a change in the autofill state associated with a view.
*
* @param view view associated with the change.
*
* This value must never be {@code null}.
* @param event currently either {@link #EVENT_INPUT_SHOWN} or {@link #EVENT_INPUT_HIDDEN}.
* Value is {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_SHOWN}, {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_HIDDEN}, or {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_UNAVAILABLE}
*/
public void onAutofillEvent(@androidx.annotation.RecentlyNonNull android.view.View view, int event) { throw new RuntimeException("Stub!"); }
/**
* Called after a change in the autofill state associated with a virtual view.
*
* @param view parent view associated with the change.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
*
* @param event currently either {@link #EVENT_INPUT_SHOWN} or {@link #EVENT_INPUT_HIDDEN}.
* Value is {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_SHOWN}, {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_HIDDEN}, or {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_UNAVAILABLE}
*/
public void onAutofillEvent(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, int event) { throw new RuntimeException("Stub!"); }
/**
* The autofill input UI associated with the view was hidden.
*
* <p>If the view provides its own auto-complete UI that was hidden upon a
* {@link #EVENT_INPUT_SHOWN} event, it could be shown again now.
*/
public static final int EVENT_INPUT_HIDDEN = 2; // 0x2
/**
* The autofill input UI associated with the view was shown.
*
* <p>If the view provides its own auto-complete UI and its currently shown, it
* should be hidden upon receiving this event.
*/
public static final int EVENT_INPUT_SHOWN = 1; // 0x1
/**
* The autofill input UI associated with the view isn't shown because
* autofill is not available.
*
* <p>If the view provides its own auto-complete UI but was not displaying it
* to avoid flickering, it could shown it upon receiving this event.
*/
public static final int EVENT_INPUT_UNAVAILABLE = 3; // 0x3
}
}
| UTF-8 | Java | 23,184 | java | AutofillManager.java | Java | [] | null | [] | /*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 android.view.autofill;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.view.View;
import android.util.SparseArray;
import android.service.autofill.AutofillService;
import android.service.autofill.FillEventHistory;
import android.service.autofill.UserData;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
/**
* The {@link AutofillManager} provides ways for apps and custom views to integrate with the
* Autofill Framework lifecycle.
*
* <p>The autofill lifecycle starts with the creation of an autofill context associated with an
* activity context; the autofill context is created when one of the following methods is called for
* the first time in an activity context, and the current user has an enabled autofill service:
*
* <ul>
* <li>{@link #notifyViewEntered(View)}
* <li>{@link #notifyViewEntered(View, int, Rect)}
* <li>{@link #requestAutofill(View)}
* </ul>
*
* <p>Tipically, the context is automatically created when the first view of the activity is
* focused because {@code View.onFocusChanged()} indirectly calls
* {@link #notifyViewEntered(View)}. App developers can call {@link #requestAutofill(View)} to
* explicitly create it (for example, a custom view developer could offer a contextual menu action
* in a text-field view to let users manually request autofill).
*
* <p>After the context is created, the Android System creates a {@link android.view.ViewStructure}
* that represents the view hierarchy by calling
* {@link View#dispatchProvideAutofillStructure(android.view.ViewStructure, int)} in the root views
* of all application windows. By default, {@code dispatchProvideAutofillStructure()} results in
* subsequent calls to {@link View#onProvideAutofillStructure(android.view.ViewStructure, int)} and
* {@link View#onProvideAutofillVirtualStructure(android.view.ViewStructure, int)} for each view in
* the hierarchy.
*
* <p>The resulting {@link android.view.ViewStructure} is then passed to the autofill service, which
* parses it looking for views that can be autofilled. If the service finds such views, it returns
* a data structure to the Android System containing the following optional info:
*
* <ul>
* <li>Datasets used to autofill subsets of views in the activity.
* <li>Id of views that the service can save their values for future autofilling.
* </ul>
*
* <p>When the service returns datasets, the Android System displays an autofill dataset picker
* UI associated with the view, when the view is focused on and is part of a dataset.
* The application can be notified when the UI is shown by registering an
* {@link AutofillCallback} through {@link #registerCallback(AutofillCallback)}. When the user
* selects a dataset from the UI, all views present in the dataset are autofilled, through
* calls to {@link View#autofill(AutofillValue)} or {@link View#autofill(SparseArray)}.
*
* <p>When the service returns ids of savable views, the Android System keeps track of changes
* made to these views, so they can be used to determine if the autofill save UI is shown later.
*
* <p>The context is then finished when one of the following occurs:
*
* <ul>
* <li>{@link #commit()} is called or all savable views are gone.
* <li>{@link #cancel()} is called.
* </ul>
*
* <p>Finally, after the autofill context is commited (i.e., not cancelled), the Android System
* shows an autofill save UI if the value of savable views have changed. If the user selects the
* option to Save, the current value of the views is then sent to the autofill service.
*
* <p>It is safe to call into its methods from any thread.
* Requires the {@link android.content.pm.PackageManager#FEATURE_AUTOFILL PackageManager#FEATURE_AUTOFILL} feature which can be detected using {@link android.content.pm.PackageManager#hasSystemFeature(String) PackageManager.hasSystemFeature(String)}.
*/
@SuppressWarnings({"unchecked", "deprecation", "all"})
public final class AutofillManager {
AutofillManager() { throw new RuntimeException("Stub!"); }
/**
* Checks whether autofill is enabled for the current user.
*
* <p>Typically used to determine whether the option to explicitly request autofill should
* be offered - see {@link #requestAutofill(View)}.
*
* @return whether autofill is enabled for the current user.
*/
public boolean isEnabled() { throw new RuntimeException("Stub!"); }
/**
* Explicitly requests a new autofill context.
*
* <p>Normally, the autofill context is automatically started if necessary when
* {@link #notifyViewEntered(View)} is called, but this method should be used in the
* cases where it must be explicitly started. For example, when the view offers an AUTOFILL
* option on its contextual overflow menu, and the user selects it.
*
* @param view view requesting the new autofill context.
* This value must never be {@code null}.
*/
public void requestAutofill(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Explicitly requests a new autofill context for virtual views.
*
* <p>Normally, the autofill context is automatically started if necessary when
* {@link #notifyViewEntered(View, int, Rect)} is called, but this method should be used in the
* cases where it must be explicitly started. For example, when the virtual view offers an
* AUTOFILL option on its contextual overflow menu, and the user selects it.
*
* <p>The virtual view boundaries must be absolute screen coordinates. For example, if the
* parent view uses {@code bounds} to draw the virtual view inside its Canvas,
* the absolute bounds could be calculated by:
*
* <pre class="prettyprint">
* int offset[] = new int[2];
* getLocationOnScreen(offset);
* Rect absBounds = new Rect(bounds.left + offset[0],
* bounds.top + offset[1],
* bounds.right + offset[0], bounds.bottom + offset[1]);
* </pre>
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
* @param absBounds absolute boundaries of the virtual view in the screen.
* This value must never be {@code null}.
*/
public void requestAutofill(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, @androidx.annotation.RecentlyNonNull android.graphics.Rect absBounds) { throw new RuntimeException("Stub!"); }
/**
* Called when a {@link View} that supports autofill is entered.
*
* @param view {@link View} that was entered.
* This value must never be {@code null}.
*/
public void notifyViewEntered(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called when a {@link View} that supports autofill is exited.
*
* @param view {@link View} that was exited.
* This value must never be {@code null}.
*/
public void notifyViewExited(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called when a {@link View view's} visibility changed.
*
* @param view {@link View} that was exited.
* This value must never be {@code null}.
* @param isVisible visible if the view is visible in the view hierarchy.
*/
public void notifyViewVisibilityChanged(@androidx.annotation.RecentlyNonNull android.view.View view, boolean isVisible) { throw new RuntimeException("Stub!"); }
/**
* Called when a virtual view's visibility changed.
*
* @param view {@link View} that was exited.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
* @param isVisible visible if the view is visible in the view hierarchy.
*/
public void notifyViewVisibilityChanged(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, boolean isVisible) { throw new RuntimeException("Stub!"); }
/**
* Called when a virtual view that supports autofill is entered.
*
* <p>The virtual view boundaries must be absolute screen coordinates. For example, if the
* parent, non-virtual view uses {@code bounds} to draw the virtual view inside its Canvas,
* the absolute bounds could be calculated by:
*
* <pre class="prettyprint">
* int offset[] = new int[2];
* getLocationOnScreen(offset);
* Rect absBounds = new Rect(bounds.left + offset[0],
* bounds.top + offset[1],
* bounds.right + offset[0], bounds.bottom + offset[1]);
* </pre>
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
* @param absBounds absolute boundaries of the virtual view in the screen.
* This value must never be {@code null}.
*/
public void notifyViewEntered(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, @androidx.annotation.RecentlyNonNull android.graphics.Rect absBounds) { throw new RuntimeException("Stub!"); }
/**
* Called when a virtual view that supports autofill is exited.
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
*/
public void notifyViewExited(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the value of an autofillable {@link View} changed.
*
* @param view view whose value changed.
*/
public void notifyValueChanged(android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the value of an autofillable virtual view has changed.
*
* @param view the virtual view parent.
* @param virtualId id identifying the virtual child inside the parent view.
* @param value new value of the child.
*/
public void notifyValueChanged(android.view.View view, int virtualId, android.view.autofill.AutofillValue value) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate a {@link View} is clicked.
*
* @param view view that has been clicked.
* This value must never be {@code null}.
*/
public void notifyViewClicked(@androidx.annotation.RecentlyNonNull android.view.View view) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate a virtual view has been clicked.
*
* @param view the virtual view parent.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
*/
public void notifyViewClicked(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId) { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the current autofill context should be commited.
*
* <p>This method is typically called by {@link View Views} that manage virtual views; for
* example, when the view is rendering an {@code HTML} page with a form and virtual views
* that represent the HTML elements, it should call this method after the form is submitted and
* another page is rendered.
*
* <p><b>Note:</b> This method does not need to be called on regular application lifecycle
* methods such as {@link android.app.Activity#finish()}.
*/
public void commit() { throw new RuntimeException("Stub!"); }
/**
* Called to indicate the current autofill context should be cancelled.
*
* <p>This method is typically called by {@link View Views} that manage virtual views; for
* example, when the view is rendering an {@code HTML} page with a form and virtual views
* that represent the HTML elements, it should call this method if the user does not post the
* form but moves to another form in this page.
*
* <p><b>Note:</b> This method does not need to be called on regular application lifecycle
* methods such as {@link android.app.Activity#finish()}.
*/
public void cancel() { throw new RuntimeException("Stub!"); }
/**
* If the app calling this API has enabled autofill services they
* will be disabled.
*/
public void disableAutofillServices() { throw new RuntimeException("Stub!"); }
/**
* Returns {@code true} if the calling application provides a {@link AutofillService} that is
* enabled for the current user, or {@code false} otherwise.
*/
public boolean hasEnabledAutofillServices() { throw new RuntimeException("Stub!"); }
/**
* Returns the component name of the {@link AutofillService} that is enabled for the current
* user.
* @return This value may be {@code null}.
*/
@androidx.annotation.RecentlyNullable public android.content.ComponentName getAutofillServiceComponentName() { throw new RuntimeException("Stub!"); }
/**
* Gets the id of the {@link UserData} used for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p>This method is useful when the service must check the status of the {@link UserData} in
* the device without fetching the whole object.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
*
* @return id of the {@link UserData} previously set by {@link #setUserData(UserData)}
* or {@code null} if it was reset or if the caller currently does not have an enabled autofill
* service for the user.
*/
@androidx.annotation.RecentlyNullable public java.lang.String getUserDataId() { throw new RuntimeException("Stub!"); }
/**
* Gets the user data used for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
*
* @return value previously set by {@link #setUserData(UserData)} or {@code null} if it was
* reset or if the caller currently does not have an enabled autofill service for the user.
*/
@androidx.annotation.RecentlyNullable public android.service.autofill.UserData getUserData() { throw new RuntimeException("Stub!"); }
/**
* Sets the {@link UserData} used for
* <a href="AutofillService.html#FieldClassification">field classification</a>
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
* @param userData This value may be {@code null}.
*/
public void setUserData(@androidx.annotation.RecentlyNullable android.service.autofill.UserData userData) { throw new RuntimeException("Stub!"); }
/**
* Checks if <a href="AutofillService.html#FieldClassification">field classification</a> is
* enabled.
*
* <p>As field classification is an expensive operation, it could be disabled, either
* temporarily (for example, because the service exceeded a rate-limit threshold) or
* permanently (for example, because the device is a low-level device).
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
*/
public boolean isFieldClassificationEnabled() { throw new RuntimeException("Stub!"); }
/**
* Gets the name of the default algorithm used for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p>The default algorithm is used when the algorithm on {@link UserData} is invalid or not
* set.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it's ignored if the caller currently doesn't have an enabled autofill service for
* the user.
* @return This value may be {@code null}.
*/
@androidx.annotation.RecentlyNullable public java.lang.String getDefaultFieldClassificationAlgorithm() { throw new RuntimeException("Stub!"); }
/**
* Gets the name of all algorithms currently available for
* <a href="AutofillService.html#FieldClassification">field classification</a>.
*
* <p><b>Note:</b> This method should only be called by an app providing an autofill service,
* and it returns an empty list if the caller currently doesn't have an enabled autofill service
* for the user.
* @return This value will never be {@code null}.
*/
@androidx.annotation.RecentlyNonNull public java.util.List<java.lang.String> getAvailableFieldClassificationAlgorithms() { throw new RuntimeException("Stub!"); }
/**
* Returns {@code true} if autofill is supported by the current device and
* is supported for this user.
*
* <p>Autofill is typically supported, but it could be unsupported in cases like:
* <ol>
* <li>Low-end devices.
* <li>Device policy rules that forbid its usage.
* </ol>
*/
public boolean isAutofillSupported() { throw new RuntimeException("Stub!"); }
/**
* Gets the next unique autofill ID for the activity context.
*
* <p>Typically used to manage views whose content is recycled - see
* {@link View#setAutofillId(AutofillId)} for more info.
*
* @return An ID that is unique in the activity, or {@code null} if autofill is not supported in
* the {@link Context} associated with this {@link AutofillManager}.
*/
@androidx.annotation.RecentlyNullable public android.view.autofill.AutofillId getNextAutofillId() { throw new RuntimeException("Stub!"); }
/**
* Registers a {@link AutofillCallback} to receive autofill events.
*
* @param callback callback to receive events.
* This value may be {@code null}.
*/
public void registerCallback(@androidx.annotation.RecentlyNullable android.view.autofill.AutofillManager.AutofillCallback callback) { throw new RuntimeException("Stub!"); }
/**
* Unregisters a {@link AutofillCallback} to receive autofill events.
*
* @param callback callback to stop receiving events.
* This value may be {@code null}.
*/
public void unregisterCallback(@androidx.annotation.RecentlyNullable android.view.autofill.AutofillManager.AutofillCallback callback) { throw new RuntimeException("Stub!"); }
/**
* Intent extra: The assist structure which captures the filled screen.
*
* <p>
* Type: {@link android.app.assist.AssistStructure}
*/
public static final java.lang.String EXTRA_ASSIST_STRUCTURE = "android.view.autofill.extra.ASSIST_STRUCTURE";
/**
* Intent extra: The result of an authentication operation. It is
* either a fully populated {@link android.service.autofill.FillResponse}
* or a fully populated {@link android.service.autofill.Dataset} if
* a response or a dataset is being authenticated respectively.
*
* <p>
* Type: {@link android.service.autofill.FillResponse} or a
* {@link android.service.autofill.Dataset}
*/
public static final java.lang.String EXTRA_AUTHENTICATION_RESULT = "android.view.autofill.extra.AUTHENTICATION_RESULT";
/**
* Intent extra: The optional extras provided by the
* {@link android.service.autofill.AutofillService}.
*
* <p>For example, when the service responds to a {@link
* android.service.autofill.FillCallback#onSuccess(android.service.autofill.FillResponse)} with
* a {@code FillResponse} that requires authentication, the Intent that launches the
* service authentication will contain the Bundle set by
* {@link android.service.autofill.FillResponse.Builder#setClientState(Bundle)} on this extra.
*
* <p>On Android {@link android.os.Build.VERSION_CODES#P} and higher, the autofill service
* can also add this bundle to the {@link Intent} set as the
* {@link android.app.Activity#setResult(int, Intent) result} for an authentication request,
* so the bundle can be recovered later on
* {@link android.service.autofill.SaveRequest#getClientState()}.
*
* <p>
* Type: {@link android.os.Bundle}
*/
public static final java.lang.String EXTRA_CLIENT_STATE = "android.view.autofill.extra.CLIENT_STATE";
/**
* Callback for autofill related events.
*
* <p>Typically used for applications that display their own "auto-complete" views, so they can
* enable / disable such views when the autofill UI is shown / hidden.
*/
@SuppressWarnings({"unchecked", "deprecation", "all"})
public abstract static class AutofillCallback {
public AutofillCallback() { throw new RuntimeException("Stub!"); }
/**
* Called after a change in the autofill state associated with a view.
*
* @param view view associated with the change.
*
* This value must never be {@code null}.
* @param event currently either {@link #EVENT_INPUT_SHOWN} or {@link #EVENT_INPUT_HIDDEN}.
* Value is {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_SHOWN}, {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_HIDDEN}, or {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_UNAVAILABLE}
*/
public void onAutofillEvent(@androidx.annotation.RecentlyNonNull android.view.View view, int event) { throw new RuntimeException("Stub!"); }
/**
* Called after a change in the autofill state associated with a virtual view.
*
* @param view parent view associated with the change.
* This value must never be {@code null}.
* @param virtualId id identifying the virtual child inside the parent view.
*
* @param event currently either {@link #EVENT_INPUT_SHOWN} or {@link #EVENT_INPUT_HIDDEN}.
* Value is {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_SHOWN}, {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_HIDDEN}, or {@link android.view.autofill.AutofillManager.AutofillCallback#EVENT_INPUT_UNAVAILABLE}
*/
public void onAutofillEvent(@androidx.annotation.RecentlyNonNull android.view.View view, int virtualId, int event) { throw new RuntimeException("Stub!"); }
/**
* The autofill input UI associated with the view was hidden.
*
* <p>If the view provides its own auto-complete UI that was hidden upon a
* {@link #EVENT_INPUT_SHOWN} event, it could be shown again now.
*/
public static final int EVENT_INPUT_HIDDEN = 2; // 0x2
/**
* The autofill input UI associated with the view was shown.
*
* <p>If the view provides its own auto-complete UI and its currently shown, it
* should be hidden upon receiving this event.
*/
public static final int EVENT_INPUT_SHOWN = 1; // 0x1
/**
* The autofill input UI associated with the view isn't shown because
* autofill is not available.
*
* <p>If the view provides its own auto-complete UI but was not displaying it
* to avoid flickering, it could shown it upon receiving this event.
*/
public static final int EVENT_INPUT_UNAVAILABLE = 3; // 0x3
}
}
| 23,184 | 0.743357 | 0.742193 | 567 | 39.887127 | 44.664036 | 266 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275132 | false | false | 4 |
bf0fbce8dde09584f8e442e50820ac526ffaa570 | 37,941,741,101,593 | d36f630036e114760c1ab39e5810421de5828ec3 | /src/BinaryTreeNode.java | f31849b7201fd6c4704b14d47e0e7eaca12081ee | [] | no_license | linaradwan/Figure-Manipulation | https://github.com/linaradwan/Figure-Manipulation | 7b5feabff46912ad3bfff7ba6d96e8206a58005f | 3d989366b0ccff0f93f96cad6c43312e048df4eb | refs/heads/master | 2020-08-01T17:10:36.084000 | 2016-11-12T19:00:53 | 2016-11-12T19:00:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class BinaryTreeNode {
private BinaryTreeNode left, right, parent; //left and right child node, parent node
//private DictEntry entry; //Dictionary entry of node
private DictEntry key;
public DictEntry getKey() {
return key;
}
public void setKey(DictEntry key) {
this.key = key;
}
/** creates node with links to two children, parent, and stores data */
public BinaryTreeNode(DictEntry data)
{
// this.entry = data;
this.parent = null;
this.left = null;
this.right = null;
}
/** set left child to node */
public void setLeft(BinaryTreeNode node)
{
this.left = node;
}
/** set right child to node */
public void setRight(BinaryTreeNode node)
{
this.right = node;
}
/** set parent to node */
public void setParent(BinaryTreeNode node)
{
this.parent = node;
}
/** set entry to data*/
// public void setEntry(DictEntry data)
//{
//this.entry = data;
//key = entry.getPosition();
//}
/** returns left child of this node */
public BinaryTreeNode getLeft()
{
if(left==null){
left =new BinaryTreeNode(null);
}
return left;
}
/** returns right child of this node */
public BinaryTreeNode getRight()
{
if(right==null){
right =new BinaryTreeNode(null);
}
return right;
}
/** returns parent of this node */
public BinaryTreeNode getParent()
{
return parent;
}
//public DictEntry getEntry() {
//return entry;
//}
} | UTF-8 | Java | 1,414 | java | BinaryTreeNode.java | Java | [] | null | [] | public class BinaryTreeNode {
private BinaryTreeNode left, right, parent; //left and right child node, parent node
//private DictEntry entry; //Dictionary entry of node
private DictEntry key;
public DictEntry getKey() {
return key;
}
public void setKey(DictEntry key) {
this.key = key;
}
/** creates node with links to two children, parent, and stores data */
public BinaryTreeNode(DictEntry data)
{
// this.entry = data;
this.parent = null;
this.left = null;
this.right = null;
}
/** set left child to node */
public void setLeft(BinaryTreeNode node)
{
this.left = node;
}
/** set right child to node */
public void setRight(BinaryTreeNode node)
{
this.right = node;
}
/** set parent to node */
public void setParent(BinaryTreeNode node)
{
this.parent = node;
}
/** set entry to data*/
// public void setEntry(DictEntry data)
//{
//this.entry = data;
//key = entry.getPosition();
//}
/** returns left child of this node */
public BinaryTreeNode getLeft()
{
if(left==null){
left =new BinaryTreeNode(null);
}
return left;
}
/** returns right child of this node */
public BinaryTreeNode getRight()
{
if(right==null){
right =new BinaryTreeNode(null);
}
return right;
}
/** returns parent of this node */
public BinaryTreeNode getParent()
{
return parent;
}
//public DictEntry getEntry() {
//return entry;
//}
} | 1,414 | 0.65983 | 0.65983 | 78 | 17.141026 | 17.964869 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.538462 | false | false | 4 |
35b2cfaff325ed0d16cba23d5c6eca4518a29cc4 | 26,027,501,873,648 | 0972c3e0fe6183d9ad4b5977a0eb27f4cfb089ad | /src/main/java/controller/SortedController.java | 4b23090319aa85dad8d53008c743b2d356dc4145 | [] | no_license | 1besser11/task1 | https://github.com/1besser11/task1 | 03e08e49e7a8d76de33e4e84dd58c5cf7be51536 | 26af1ab7c35b0d151608db33ef6ece0023891af6 | refs/heads/master | 2020-06-05T23:30:06.876000 | 2019-07-04T12:43:25 | 2019-07-04T12:43:25 | 192,574,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import model.human.Human;
import services.HumanService;
/**
* Контроллер разных типов сортировок
* @author nikita
*
*/
@Controller
public class SortedController {
@Autowired
HumanService hs;
@GetMapping({"/sort"})
public String sortIncome(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = new ArrayList();
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/income-asc"})
public String sortIncomeAsc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByIncomeAsc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/income-desc"})
public String sortIncomeDesc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByIncomeDesc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/tax-desc"})
public String sortTaxDesc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByTaxDesc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/tax-asc"})
public String sortTaxAsc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByTaxAsc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
}
| UTF-8 | Java | 2,584 | java | SortedController.java | Java | [
{
"context": "*\n * Контроллер разных типов сортировок\n * @author nikita\n *\n */\n@Controller\npublic class SortedController ",
"end": 520,
"score": 0.9993032813072205,
"start": 514,
"tag": "USERNAME",
"value": "nikita"
}
] | null | [] | package controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import model.human.Human;
import services.HumanService;
/**
* Контроллер разных типов сортировок
* @author nikita
*
*/
@Controller
public class SortedController {
@Autowired
HumanService hs;
@GetMapping({"/sort"})
public String sortIncome(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = new ArrayList();
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/income-asc"})
public String sortIncomeAsc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByIncomeAsc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/income-desc"})
public String sortIncomeDesc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByIncomeDesc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/tax-desc"})
public String sortTaxDesc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByTaxDesc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
@GetMapping({"/sort/tax-asc"})
public String sortTaxAsc(Model model,
@RequestParam(value="size", required=true, defaultValue="10") int size,
@RequestParam(value="page", required=true, defaultValue="0") int page
) {
List<Human> res = hs.findPageSortedByTaxAsc(size, page);
model.addAttribute("result", res);
return "sortIncome";
}
}
| 2,584 | 0.672542 | 0.666667 | 85 | 29.035294 | 25.523897 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.364706 | false | false | 4 |
8c83bb9b0d8fd2efc48eca577dabaee5248ad15e | 35,794,257,475,778 | d388f39cae82f76bb9e2e9554acd296016ebcbf8 | /onecode/agent/src/main/java/com/thinkgem/jeesite/modules/operate/web/checkordersuccess/BrcbCkeckOrderSuccessController.java | b4c762c2c0a6d4739b6a49dc6f3a2b2aa32b594e | [] | no_license | xinsec/operate | https://github.com/xinsec/operate | c04c787cc23ed73b6a3d73dc49b52d7fd1f599eb | fc4b7bad24f0313709e45c7277551246fd5457e9 | refs/heads/master | 2018-03-09T09:36:36.160000 | 2017-06-27T13:31:34 | 2017-06-27T13:31:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.operate.web.checkordersuccess;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.operate.entity.checkordersuccess.BrcbCkeckOrderSuccess;
import com.thinkgem.jeesite.modules.operate.service.checkordersuccess.BrcbCkeckOrderSuccessService;
/**
* 对账成功信息查询Controller
* @author zmm
* @version 2016-10-16
*/
@Controller
@RequestMapping(value = "${adminPath}/operate/checkordersuccess/brcbCkeckOrderSuccess")
public class BrcbCkeckOrderSuccessController extends BaseController {
@Autowired
private BrcbCkeckOrderSuccessService brcbCkeckOrderSuccessService;
@ModelAttribute
public BrcbCkeckOrderSuccess get(@RequestParam(required=false) String id) {
BrcbCkeckOrderSuccess entity = null;
if (StringUtils.isNotBlank(id)){
entity = brcbCkeckOrderSuccessService.get(id);
}
if (entity == null){
entity = new BrcbCkeckOrderSuccess();
}
return entity;
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:list")
@RequestMapping(value = {"list", ""})
public String list(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<BrcbCkeckOrderSuccess> pg = new Page<BrcbCkeckOrderSuccess>(request, response);
pg.setOrderBy("CREATE_TIME DESC");
Page<BrcbCkeckOrderSuccess> page = brcbCkeckOrderSuccessService.findPage(pg, brcbCkeckOrderSuccess);
model.addAttribute("page", page);
return "modules/operate/checkordersuccess/brcbCkeckOrderSuccessList";
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:view")
@RequestMapping(value = "form")
public String form(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, Model model) {
model.addAttribute("brcbCkeckOrderSuccess", brcbCkeckOrderSuccess);
return "modules/operate/checkordersuccess/brcbCkeckOrderSuccessForm";
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:edit")
@RequestMapping(value = "save")
public String save(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, brcbCkeckOrderSuccess)){
return form(brcbCkeckOrderSuccess, model);
}
brcbCkeckOrderSuccessService.save(brcbCkeckOrderSuccess);
addMessage(redirectAttributes, "操作成功");
return "redirect:"+Global.getAdminPath()+"/operate/checkordersuccess/brcbCkeckOrderSuccess/?repage";
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:edit")
@RequestMapping(value = "delete")
public String delete(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, RedirectAttributes redirectAttributes) {
brcbCkeckOrderSuccessService.delete(brcbCkeckOrderSuccess);
addMessage(redirectAttributes, "删除成功");
return "redirect:"+Global.getAdminPath()+"/operate/checkordersuccess/brcbCkeckOrderSuccess/?repage";
}
} | UTF-8 | Java | 3,729 | java | BrcbCkeckOrderSuccessController.java | Java | [
{
"context": "ight © 2012-2016 <a href=\"https://github.com/thinkgem/jeesite\">JeeSite</a> All rights reserved.\n */\npac",
"end": 70,
"score": 0.9990603923797607,
"start": 62,
"tag": "USERNAME",
"value": "thinkgem"
},
{
"context": "cessService;\n\n/**\n * 对账成功信息查询Controller\n * @author zmm\n * @version 2016-10-16\n */\n@Controller\n@RequestMa",
"end": 1196,
"score": 0.9996578693389893,
"start": 1193,
"tag": "USERNAME",
"value": "zmm"
}
] | null | [] | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.operate.web.checkordersuccess;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.operate.entity.checkordersuccess.BrcbCkeckOrderSuccess;
import com.thinkgem.jeesite.modules.operate.service.checkordersuccess.BrcbCkeckOrderSuccessService;
/**
* 对账成功信息查询Controller
* @author zmm
* @version 2016-10-16
*/
@Controller
@RequestMapping(value = "${adminPath}/operate/checkordersuccess/brcbCkeckOrderSuccess")
public class BrcbCkeckOrderSuccessController extends BaseController {
@Autowired
private BrcbCkeckOrderSuccessService brcbCkeckOrderSuccessService;
@ModelAttribute
public BrcbCkeckOrderSuccess get(@RequestParam(required=false) String id) {
BrcbCkeckOrderSuccess entity = null;
if (StringUtils.isNotBlank(id)){
entity = brcbCkeckOrderSuccessService.get(id);
}
if (entity == null){
entity = new BrcbCkeckOrderSuccess();
}
return entity;
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:list")
@RequestMapping(value = {"list", ""})
public String list(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<BrcbCkeckOrderSuccess> pg = new Page<BrcbCkeckOrderSuccess>(request, response);
pg.setOrderBy("CREATE_TIME DESC");
Page<BrcbCkeckOrderSuccess> page = brcbCkeckOrderSuccessService.findPage(pg, brcbCkeckOrderSuccess);
model.addAttribute("page", page);
return "modules/operate/checkordersuccess/brcbCkeckOrderSuccessList";
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:view")
@RequestMapping(value = "form")
public String form(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, Model model) {
model.addAttribute("brcbCkeckOrderSuccess", brcbCkeckOrderSuccess);
return "modules/operate/checkordersuccess/brcbCkeckOrderSuccessForm";
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:edit")
@RequestMapping(value = "save")
public String save(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, brcbCkeckOrderSuccess)){
return form(brcbCkeckOrderSuccess, model);
}
brcbCkeckOrderSuccessService.save(brcbCkeckOrderSuccess);
addMessage(redirectAttributes, "操作成功");
return "redirect:"+Global.getAdminPath()+"/operate/checkordersuccess/brcbCkeckOrderSuccess/?repage";
}
@RequiresPermissions("operate:checkordersuccess:brcbCkeckOrderSuccess:edit")
@RequestMapping(value = "delete")
public String delete(BrcbCkeckOrderSuccess brcbCkeckOrderSuccess, RedirectAttributes redirectAttributes) {
brcbCkeckOrderSuccessService.delete(brcbCkeckOrderSuccess);
addMessage(redirectAttributes, "删除成功");
return "redirect:"+Global.getAdminPath()+"/operate/checkordersuccess/brcbCkeckOrderSuccess/?repage";
}
} | 3,729 | 0.819042 | 0.814715 | 85 | 42.505882 | 35.136917 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.505882 | false | false | 4 |
58d4acce2c0093cd63e2c7523244deabd9a904b0 | 23,330,262,405,556 | e22bedb328010fad8b5e66a6cdc0059f970fdd66 | /DataTender/src/cn/j/data/dao/ObjectCompanyFilter.java | a70a5bc3f3531a1254de0dc70b1ced748d2be5d4 | [] | no_license | wenc000/DataTender | https://github.com/wenc000/DataTender | b4db13f1249a809c98b0eeb4a898349a61591c74 | 143d82bb296f96c4e9b6361d97a2788753eeffe8 | refs/heads/master | 2018-12-29T21:42:09.677000 | 2016-07-12T23:11:53 | 2016-07-12T23:11:53 | 63,198,364 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.j.data.dao;
/**
* ObjectCompanyFilter entity. @author MyEclipse Persistence Tools
*/
public class ObjectCompanyFilter implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 4696892605854186082L;
private Integer id;
private String filterWords;
// Constructors
/** default constructor */
public ObjectCompanyFilter() {
}
/** full constructor */
public ObjectCompanyFilter(String filterWords) {
this.filterWords = filterWords;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFilterWords() {
return this.filterWords;
}
public void setFilterWords(String filterWords) {
this.filterWords = filterWords;
}
} | UTF-8 | Java | 788 | java | ObjectCompanyFilter.java | Java | [] | null | [] | package cn.j.data.dao;
/**
* ObjectCompanyFilter entity. @author MyEclipse Persistence Tools
*/
public class ObjectCompanyFilter implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 4696892605854186082L;
private Integer id;
private String filterWords;
// Constructors
/** default constructor */
public ObjectCompanyFilter() {
}
/** full constructor */
public ObjectCompanyFilter(String filterWords) {
this.filterWords = filterWords;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFilterWords() {
return this.filterWords;
}
public void setFilterWords(String filterWords) {
this.filterWords = filterWords;
}
} | 788 | 0.718274 | 0.694162 | 47 | 15.787234 | 19.16328 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.893617 | false | false | 4 |
911e40b5d9487ff66536284bee525c6a02dd799f | 13,769,665,196,001 | 44d4bab0a72404dc5ee143d7dcd7307e62a96cb7 | /m-server/src/main/java/fun/bookish/blueberry/server/device/service/impl/DeviceServiceImpl.java | eaf23225ebd928a1a3ffc268d0efe5e634a30c0c | [
"MIT"
] | permissive | aiical/blueberry | https://github.com/aiical/blueberry | a7da0b92c015312bf0ef4c72046c93307bd4fc65 | 1279363921c20b6e976ce955e170f63b410c13a1 | refs/heads/master | 2023-05-31T23:05:44.020000 | 2021-07-07T09:12:54 | 2021-07-07T09:12:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fun.bookish.blueberry.server.device.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import fun.bookish.blueberry.core.exception.ManualRollbackException;
import fun.bookish.blueberry.core.page.PageResult;
import fun.bookish.blueberry.core.utils.BeanUtils;
import fun.bookish.blueberry.server.channel.service.IChannelService;
import fun.bookish.blueberry.server.device.entity.DevicePO;
import fun.bookish.blueberry.server.device.entity.DeviceParamVO;
import fun.bookish.blueberry.server.device.entity.DeviceVO;
import fun.bookish.blueberry.server.device.mapper.DeviceMapper;
import fun.bookish.blueberry.server.device.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.bookish.blueberry.server.hook.HttpHookExecutor;
import fun.bookish.blueberry.server.sip.conf.SipProperties;
import fun.bookish.blueberry.server.videoqualitydetect.arithmetic.entity.VideoQualityDetectArithmeticPO;
import fun.bookish.blueberry.server.videoqualitydetect.arithmetic.entity.VideoQualityDetectArithmeticVO;
import fun.bookish.blueberry.sip.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* <p>
* 设备表 服务实现类
* </p>
*
* @author RabbitNoTeeth
* @since 2021-06-11
*/
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, DevicePO> implements IDeviceService {
@Autowired
private IChannelService channelService;
@Autowired
private HttpHookExecutor httpHookExecutor;
@Autowired
private SipProperties sipProperties;
@Value("${server.port}")
private Integer serverPort;
@Override
public boolean save(DevicePO entity) {
boolean success = super.save(entity);
// 触发http hook
if (success) {
HttpHookExecutor.DeviceEntity device = HttpHookExecutor.DeviceEntity.mapFromDevicePO(query().eq("id", entity.getId()).one());
device.setServerIp(sipProperties.getHost());
device.setServerPort(serverPort);
httpHookExecutor.onDeviceCreated(device);
}
return success;
}
@Override
public boolean updateById(DevicePO entity) {
boolean success = super.updateById(entity);
// 触发http hook
if (success) {
HttpHookExecutor.DeviceEntity device = HttpHookExecutor.DeviceEntity.mapFromDevicePO(queryById(entity.getId()));
device.setServerIp(sipProperties.getHost());
device.setServerPort(serverPort);
httpHookExecutor.onDeviceUpdated(device);
}
return success;
}
@Override
public String add(DeviceVO deviceVO) {
DevicePO devicePO = BeanUtils.convert(deviceVO, DevicePO.class);
devicePO.setOnline(0);
String now = DateUtils.getNowDateTimeStr();
devicePO.setCreatedAt(now);
devicePO.setUpdatedAt(now);
save(devicePO);
return deviceVO.getId();
}
@Override
public String update(DeviceVO deviceVO) {
DevicePO devicePO = BeanUtils.convert(deviceVO, DevicePO.class);
String now = DateUtils.getNowDateTimeStr();
devicePO.setUpdatedAt(now);
updateById(devicePO);
return deviceVO.getId();
}
@Override
@Transactional(rollbackFor = Exception.class)
public String deleteById(String id) {
boolean success = removeById(id);
channelService.deleteByDeviceId(id);
// 触发http hook
if (success) {
HttpHookExecutor.DeviceRemove hookData = new HttpHookExecutor.DeviceRemove();
hookData.setDeviceId(id);
httpHookExecutor.onDeviceRemoved(hookData);
}
return id;
}
@Override
public DevicePO queryById(String id) {
return query().eq("id", id).one();
}
@Override
public List<DeviceVO> queryList(DeviceParamVO params) {
QueryChainWrapper<DevicePO> query = query();
String id = params.getId();
String name = params.getName();
String type = params.getType();
Integer online = params.getOnline();
if (StringUtils.isNotBlank(id)) {
query.like("id", id);
}
if (StringUtils.isNotBlank(name)) {
query.like("name", name);
}
if (StringUtils.isNotBlank(type)) {
query.eq("type", type);
}
if (online != null) {
query.eq("online", online);
}
List<DevicePO> list = query.orderByDesc("created_at").list();
return BeanUtils.convert(list, DeviceVO.class);
}
@Override
public PageResult<DeviceVO> queryPage(Integer page, Integer pageSize, DeviceParamVO params) {
if (page < 1) {
throw new ManualRollbackException("page参数值非法,必须大于等于1");
} else {
QueryWrapper<DevicePO> query = new QueryWrapper<>();
String id = params.getId();
String name = params.getName();
String type = params.getType();
Integer online = params.getOnline();
if (StringUtils.isNotBlank(id)) {
query.like("id", id);
}
if (StringUtils.isNotBlank(name)) {
query.like("name", name);
}
if (StringUtils.isNotBlank(type)) {
query.eq("type", type);
}
if (online != null) {
query.eq("online", online);
}
Page<DevicePO> pageEntity = new Page<>();
pageEntity.setCurrent(page);
pageEntity.setSize(pageSize);
Page<DevicePO> res = page(pageEntity, query);
PageResult<DeviceVO> result = new PageResult<>(res.getTotal(), BeanUtils.convert(res.getRecords(), DeviceVO.class));
return result;
}
}
@Override
public synchronized String addOrUpdate(DevicePO devicePO) {
String id = devicePO.getId();
DevicePO device = query().eq("id", devicePO.getId()).one();
if (device != null) {
updateById(devicePO);
} else {
save(devicePO);
}
return id;
}
}
| UTF-8 | Java | 6,570 | java | DeviceServiceImpl.java | Java | [
{
"context": "st;\n\n/**\n * <p>\n * 设备表 服务实现类\n * </p>\n *\n * @author RabbitNoTeeth\n * @since 2021-06-11\n */\n@Service\npublic class De",
"end": 1638,
"score": 0.9995953440666199,
"start": 1625,
"tag": "USERNAME",
"value": "RabbitNoTeeth"
}
] | null | [] | package fun.bookish.blueberry.server.device.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import fun.bookish.blueberry.core.exception.ManualRollbackException;
import fun.bookish.blueberry.core.page.PageResult;
import fun.bookish.blueberry.core.utils.BeanUtils;
import fun.bookish.blueberry.server.channel.service.IChannelService;
import fun.bookish.blueberry.server.device.entity.DevicePO;
import fun.bookish.blueberry.server.device.entity.DeviceParamVO;
import fun.bookish.blueberry.server.device.entity.DeviceVO;
import fun.bookish.blueberry.server.device.mapper.DeviceMapper;
import fun.bookish.blueberry.server.device.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.bookish.blueberry.server.hook.HttpHookExecutor;
import fun.bookish.blueberry.server.sip.conf.SipProperties;
import fun.bookish.blueberry.server.videoqualitydetect.arithmetic.entity.VideoQualityDetectArithmeticPO;
import fun.bookish.blueberry.server.videoqualitydetect.arithmetic.entity.VideoQualityDetectArithmeticVO;
import fun.bookish.blueberry.sip.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* <p>
* 设备表 服务实现类
* </p>
*
* @author RabbitNoTeeth
* @since 2021-06-11
*/
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, DevicePO> implements IDeviceService {
@Autowired
private IChannelService channelService;
@Autowired
private HttpHookExecutor httpHookExecutor;
@Autowired
private SipProperties sipProperties;
@Value("${server.port}")
private Integer serverPort;
@Override
public boolean save(DevicePO entity) {
boolean success = super.save(entity);
// 触发http hook
if (success) {
HttpHookExecutor.DeviceEntity device = HttpHookExecutor.DeviceEntity.mapFromDevicePO(query().eq("id", entity.getId()).one());
device.setServerIp(sipProperties.getHost());
device.setServerPort(serverPort);
httpHookExecutor.onDeviceCreated(device);
}
return success;
}
@Override
public boolean updateById(DevicePO entity) {
boolean success = super.updateById(entity);
// 触发http hook
if (success) {
HttpHookExecutor.DeviceEntity device = HttpHookExecutor.DeviceEntity.mapFromDevicePO(queryById(entity.getId()));
device.setServerIp(sipProperties.getHost());
device.setServerPort(serverPort);
httpHookExecutor.onDeviceUpdated(device);
}
return success;
}
@Override
public String add(DeviceVO deviceVO) {
DevicePO devicePO = BeanUtils.convert(deviceVO, DevicePO.class);
devicePO.setOnline(0);
String now = DateUtils.getNowDateTimeStr();
devicePO.setCreatedAt(now);
devicePO.setUpdatedAt(now);
save(devicePO);
return deviceVO.getId();
}
@Override
public String update(DeviceVO deviceVO) {
DevicePO devicePO = BeanUtils.convert(deviceVO, DevicePO.class);
String now = DateUtils.getNowDateTimeStr();
devicePO.setUpdatedAt(now);
updateById(devicePO);
return deviceVO.getId();
}
@Override
@Transactional(rollbackFor = Exception.class)
public String deleteById(String id) {
boolean success = removeById(id);
channelService.deleteByDeviceId(id);
// 触发http hook
if (success) {
HttpHookExecutor.DeviceRemove hookData = new HttpHookExecutor.DeviceRemove();
hookData.setDeviceId(id);
httpHookExecutor.onDeviceRemoved(hookData);
}
return id;
}
@Override
public DevicePO queryById(String id) {
return query().eq("id", id).one();
}
@Override
public List<DeviceVO> queryList(DeviceParamVO params) {
QueryChainWrapper<DevicePO> query = query();
String id = params.getId();
String name = params.getName();
String type = params.getType();
Integer online = params.getOnline();
if (StringUtils.isNotBlank(id)) {
query.like("id", id);
}
if (StringUtils.isNotBlank(name)) {
query.like("name", name);
}
if (StringUtils.isNotBlank(type)) {
query.eq("type", type);
}
if (online != null) {
query.eq("online", online);
}
List<DevicePO> list = query.orderByDesc("created_at").list();
return BeanUtils.convert(list, DeviceVO.class);
}
@Override
public PageResult<DeviceVO> queryPage(Integer page, Integer pageSize, DeviceParamVO params) {
if (page < 1) {
throw new ManualRollbackException("page参数值非法,必须大于等于1");
} else {
QueryWrapper<DevicePO> query = new QueryWrapper<>();
String id = params.getId();
String name = params.getName();
String type = params.getType();
Integer online = params.getOnline();
if (StringUtils.isNotBlank(id)) {
query.like("id", id);
}
if (StringUtils.isNotBlank(name)) {
query.like("name", name);
}
if (StringUtils.isNotBlank(type)) {
query.eq("type", type);
}
if (online != null) {
query.eq("online", online);
}
Page<DevicePO> pageEntity = new Page<>();
pageEntity.setCurrent(page);
pageEntity.setSize(pageSize);
Page<DevicePO> res = page(pageEntity, query);
PageResult<DeviceVO> result = new PageResult<>(res.getTotal(), BeanUtils.convert(res.getRecords(), DeviceVO.class));
return result;
}
}
@Override
public synchronized String addOrUpdate(DevicePO devicePO) {
String id = devicePO.getId();
DevicePO device = query().eq("id", devicePO.getId()).one();
if (device != null) {
updateById(devicePO);
} else {
save(devicePO);
}
return id;
}
}
| 6,570 | 0.658791 | 0.65695 | 180 | 35.211113 | 26.636856 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622222 | false | false | 4 |
a7f23a731e8a786048ba89cf44a7021a6ee874c5 | 38,422,777,451,569 | 6f333b879a968c5e55973abec3f51d121137808b | /src/cardRecognizer/XMLWorker.java | 19899ed3a8e7c296b532efc7c5bf59d1c9ccb706 | [] | no_license | stone-j/MtGCardRecognizer | https://github.com/stone-j/MtGCardRecognizer | de3d5fb53039059303709e789dc7d9e3bdca9170 | e8fc33fa2b3af25efe8848de1ff4815142760e14 | refs/heads/master | 2023-04-02T04:01:21.352000 | 2021-04-12T18:34:19 | 2021-04-12T18:34:19 | 332,590,174 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cardRecognizer;
import processing.data.XML;
public class XMLWorker extends core.helper.XmlHelper {
public XML[] configXML = new XML[1];
public XML[] urlsXML = new XML[1];
static final String configFilePath = System.getProperty("user.dir") + "\\config\\config.xml";
//this is here so that urls_private.xml can be .gitignored and contain URLs that are to be kept private
static final String urlsFilePath_private = System.getProperty("user.dir") + "\\config\\urls_private.xml";
static final String urlsFilePath = System.getProperty("user.dir") + "\\config\\urls.xml";
//------------------------------------------------------------
//CONSTRUCTOR
//------------------------------------------------------------
public XMLWorker(boolean useAppData, String appDataFolderName) {
super(useAppData, appDataFolderName);
configXML = GetXMLFromFile(configFilePath);
urlsXML = GetXMLFromFile(urlsFilePath_private, urlsFilePath);
}
public int GetIntFromXml(String nodePath) {
return GetIntFromXml(nodePath, configXML);
}
public String GetDataFromXml(String nodePath) {
return GetDataFromXml(nodePath, configXML);
}
public String GetURLFromXml(String nodePath) {
return GetDataFromXml(nodePath, urlsXML);
}
}
| UTF-8 | Java | 1,277 | java | XMLWorker.java | Java | [] | null | [] | package cardRecognizer;
import processing.data.XML;
public class XMLWorker extends core.helper.XmlHelper {
public XML[] configXML = new XML[1];
public XML[] urlsXML = new XML[1];
static final String configFilePath = System.getProperty("user.dir") + "\\config\\config.xml";
//this is here so that urls_private.xml can be .gitignored and contain URLs that are to be kept private
static final String urlsFilePath_private = System.getProperty("user.dir") + "\\config\\urls_private.xml";
static final String urlsFilePath = System.getProperty("user.dir") + "\\config\\urls.xml";
//------------------------------------------------------------
//CONSTRUCTOR
//------------------------------------------------------------
public XMLWorker(boolean useAppData, String appDataFolderName) {
super(useAppData, appDataFolderName);
configXML = GetXMLFromFile(configFilePath);
urlsXML = GetXMLFromFile(urlsFilePath_private, urlsFilePath);
}
public int GetIntFromXml(String nodePath) {
return GetIntFromXml(nodePath, configXML);
}
public String GetDataFromXml(String nodePath) {
return GetDataFromXml(nodePath, configXML);
}
public String GetURLFromXml(String nodePath) {
return GetDataFromXml(nodePath, urlsXML);
}
}
| 1,277 | 0.661707 | 0.660141 | 36 | 33.472221 | 32.30711 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.416667 | false | false | 4 |
0e8cc1d691aa69a935a36be092e97f5974174171 | 35,270,271,472,133 | 0117fcabd6cff61cb2767fcbdefe7ebd34369e49 | /proposals/app/android/app/src/main/java/com/schiller40/autocookerconcept/DiscoverCard.java | 090827ffba4d7b7271580764f67cb67a23d049b3 | [] | no_license | JonasKruckenberg/autocooker-concept | https://github.com/JonasKruckenberg/autocooker-concept | 19d1e48aaae8ec86ac33a164276c9f75ef663a24 | a93a721cd039aaefff68c99c22c274ef3462f6bc | refs/heads/master | 2020-07-22T21:44:58.263000 | 2020-01-28T12:01:46 | 2020-01-28T12:01:46 | 207,337,256 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.schiller40.autocookerconcept;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.squareup.picasso.Picasso;
public class DiscoverCard extends View {
private View view;
private ConstraintLayout cl;
private TextView textViewTitle, textViewDuration;
private ImageView imageViewMeal;
private MainActivity MainActivityContext;
private int nthChild;
String title = "unknown";
String duration = "unknown";
String imageUrl = "https://team-polaris.de/jsonrecipes/error_image.png";
public DiscoverCard(Context context) {
super(context);
}
public DiscoverCard(Context context, final LinearLayout root, final int recipeId) {
super(context);
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MainActivityContext = (MainActivity) root.getContext();
view = layoutInflater.inflate(R.layout.discover_card_template, root);
nthChild = ((LinearLayout)view).getChildCount() - 1;
PendingIntent pendingResult = MainActivityContext.createPendingResult(nthChild, new Intent(), 0);
Intent getJSONIntent = new Intent(getContext(),DownloadIntentService.class);
getJSONIntent.putExtra("recipeId", recipeId);
getJSONIntent.putExtra(DownloadIntentService.PENDING_RESULT_EXTRA, pendingResult);
MainActivityContext.startService(getJSONIntent);
cl = (ConstraintLayout) ((LinearLayout)view).getChildAt((nthChild));
cl.setAlpha(0);
textViewTitle = (TextView) cl.getChildAt(1);
textViewDuration = (TextView) cl.getChildAt(2);
imageViewMeal = (ImageView) cl.getChildAt(0);
cl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), DetailedRecipe.class);
intent.putExtra("recipeId", recipeId);
intent.putExtra("byId", true);
startActivity(intent, root);
}
});
}
public DiscoverCard(Context context, final LinearLayout root, final String title, final String duration) {
super(context);
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.discover_card_template, root);
cl = (ConstraintLayout) ((LinearLayout)view).getChildAt(((LinearLayout)view).getChildCount()-1);
textViewTitle = (TextView) cl.getChildAt(1);
textViewDuration = (TextView) cl.getChildAt(2);
imageViewMeal = (ImageView) cl.getChildAt(0);
textViewDuration.setText(duration);
textViewTitle.setText(title);
cl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), DetailedRecipe.class);
/*intent.putExtra("imageUrl", "");
intent.putExtra("title", title);
intent.putExtra("description", "");
intent.putExtra("duration", duration);
intent.putExtra("starred", false);
intent.putExtra("people", 4);
Bundle bundle = new Bundle();
String[][] ingredients = {{"50 g", "tomatoes"}, {"20 ml", "water"}};
bundle.putSerializable("ingredients", ingredients);
String[] tags = {"einfach", "schnell", "lecker"};
intent.putExtra("tags", tags);
intent.putExtra("bundle", bundle);*/
intent.putExtra("recipeId", 1);
intent.putExtra("byId", true);
startActivity(intent, root);
}
});
}
private void startActivity(Intent intent, ViewGroup container){
container.getContext().startActivity(intent);
}
public void setupContent(){
textViewDuration.setText(duration);
textViewTitle.setText(title);
Picasso.with(MainActivityContext).load(imageUrl).into(imageViewMeal);
cl.setAlpha(1);
}
} | UTF-8 | Java | 4,452 | java | DiscoverCard.java | Java | [
{
"context": "package com.schiller40.autocookerconcept;\n\nimport android.app.PendingInt",
"end": 22,
"score": 0.925505518913269,
"start": 12,
"tag": "USERNAME",
"value": "schiller40"
}
] | null | [] | package com.schiller40.autocookerconcept;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.squareup.picasso.Picasso;
public class DiscoverCard extends View {
private View view;
private ConstraintLayout cl;
private TextView textViewTitle, textViewDuration;
private ImageView imageViewMeal;
private MainActivity MainActivityContext;
private int nthChild;
String title = "unknown";
String duration = "unknown";
String imageUrl = "https://team-polaris.de/jsonrecipes/error_image.png";
public DiscoverCard(Context context) {
super(context);
}
public DiscoverCard(Context context, final LinearLayout root, final int recipeId) {
super(context);
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MainActivityContext = (MainActivity) root.getContext();
view = layoutInflater.inflate(R.layout.discover_card_template, root);
nthChild = ((LinearLayout)view).getChildCount() - 1;
PendingIntent pendingResult = MainActivityContext.createPendingResult(nthChild, new Intent(), 0);
Intent getJSONIntent = new Intent(getContext(),DownloadIntentService.class);
getJSONIntent.putExtra("recipeId", recipeId);
getJSONIntent.putExtra(DownloadIntentService.PENDING_RESULT_EXTRA, pendingResult);
MainActivityContext.startService(getJSONIntent);
cl = (ConstraintLayout) ((LinearLayout)view).getChildAt((nthChild));
cl.setAlpha(0);
textViewTitle = (TextView) cl.getChildAt(1);
textViewDuration = (TextView) cl.getChildAt(2);
imageViewMeal = (ImageView) cl.getChildAt(0);
cl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), DetailedRecipe.class);
intent.putExtra("recipeId", recipeId);
intent.putExtra("byId", true);
startActivity(intent, root);
}
});
}
public DiscoverCard(Context context, final LinearLayout root, final String title, final String duration) {
super(context);
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.discover_card_template, root);
cl = (ConstraintLayout) ((LinearLayout)view).getChildAt(((LinearLayout)view).getChildCount()-1);
textViewTitle = (TextView) cl.getChildAt(1);
textViewDuration = (TextView) cl.getChildAt(2);
imageViewMeal = (ImageView) cl.getChildAt(0);
textViewDuration.setText(duration);
textViewTitle.setText(title);
cl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), DetailedRecipe.class);
/*intent.putExtra("imageUrl", "");
intent.putExtra("title", title);
intent.putExtra("description", "");
intent.putExtra("duration", duration);
intent.putExtra("starred", false);
intent.putExtra("people", 4);
Bundle bundle = new Bundle();
String[][] ingredients = {{"50 g", "tomatoes"}, {"20 ml", "water"}};
bundle.putSerializable("ingredients", ingredients);
String[] tags = {"einfach", "schnell", "lecker"};
intent.putExtra("tags", tags);
intent.putExtra("bundle", bundle);*/
intent.putExtra("recipeId", 1);
intent.putExtra("byId", true);
startActivity(intent, root);
}
});
}
private void startActivity(Intent intent, ViewGroup container){
container.getContext().startActivity(intent);
}
public void setupContent(){
textViewDuration.setText(duration);
textViewTitle.setText(title);
Picasso.with(MainActivityContext).load(imageUrl).into(imageViewMeal);
cl.setAlpha(1);
}
} | 4,452 | 0.657457 | 0.65319 | 106 | 41.009434 | 28.240376 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.028302 | false | false | 4 |
e833272eaba3efdb7324c1b08a9d7a0264a6bc91 | 35,828,617,218,343 | 9380e6cef3e161ee9833f604c6827fd5be7f43e1 | /src/google/campustest2014/rounda/ReadPhoneNumber.java | 1319c83a27a245ce38ee7f24aa372f59e9724ea0 | [] | no_license | Qualified-gad/qualified_io | https://github.com/Qualified-gad/qualified_io | a439ac9ac5ecda4f929ed8a88acd5a8082b9d715 | 4e83e2f67c6416dfe07313cabbcb4a8f2f72bcf4 | refs/heads/master | 2020-12-13T06:59:26.711000 | 2019-07-18T18:47:01 | 2019-07-18T18:47:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package google.campustest2014.rounda;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by anthony on 8/20/14.
*/
public class ReadPhoneNumber {
public static void main(String args[]) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader
("src/google/campustest2014/rounda/A-large-practice.in"));
String temp = reader.readLine();
int T = Integer.parseInt(temp);
for (int _t = 0; _t < T; _t++) {
temp = reader.readLine();
String temp2[] = temp.split(" ");
StringBuilder sb = new StringBuilder();
String temp3[] = temp2[1].split("-");
int offset = 0;
for(String s : temp3){
int t = Integer.parseInt(s);
String current = temp2[0].substring(offset, offset+t);
offset += t;
convert(current, sb);
//System.out.println(current);
}
System.out.print("Case #");
System.out.print(_t+1);
System.out.print(": ");
System.out.println(sb.toString().substring(1));
}
reader.close();
}
private static String number2string(int c){
switch (c){
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
case 9:
return "nine";
}
return "";
}
private static String number2string2(int c){
switch (c){
case 2:
return "double";
case 3:
return "triple";
case 4:
return "quadruple";
case 5:
return "quintuple";
case 6:
return "sextuple";
case 7:
return "septuple";
case 8:
return "octuple";
case 9:
return "nonuple";
case 10:
return "decuple";
}
return "";
}
private static String convert(String current, StringBuilder sb) {
char c[] = current.toCharArray();
for(int i = 0; i < c.length; i++){
int k = 1;
while(i + k < c.length && c[i] == c[i+k]){
k++;
}
k--;
if(k > 0 && k < 10){
sb.append(' ');
sb.append(number2string2(k + 1));
i += k;
}
else if(k >= 10){
while(k > 0) {
sb.append(' ');
sb.append(number2string(c[i] - '0'));
i++;
k--;
}
}
sb.append(' ');
sb.append(number2string(c[i]-'0'));
}
return null;
}
}
| UTF-8 | Java | 3,232 | java | ReadPhoneNumber.java | Java | [
{
"context": "er;\nimport java.io.IOException;\n\n/**\n * Created by anthony on 8/20/14.\n */\npublic class ReadPhoneNumber {\n ",
"end": 151,
"score": 0.988968551158905,
"start": 144,
"tag": "USERNAME",
"value": "anthony"
}
] | null | [] | package google.campustest2014.rounda;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by anthony on 8/20/14.
*/
public class ReadPhoneNumber {
public static void main(String args[]) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader
("src/google/campustest2014/rounda/A-large-practice.in"));
String temp = reader.readLine();
int T = Integer.parseInt(temp);
for (int _t = 0; _t < T; _t++) {
temp = reader.readLine();
String temp2[] = temp.split(" ");
StringBuilder sb = new StringBuilder();
String temp3[] = temp2[1].split("-");
int offset = 0;
for(String s : temp3){
int t = Integer.parseInt(s);
String current = temp2[0].substring(offset, offset+t);
offset += t;
convert(current, sb);
//System.out.println(current);
}
System.out.print("Case #");
System.out.print(_t+1);
System.out.print(": ");
System.out.println(sb.toString().substring(1));
}
reader.close();
}
private static String number2string(int c){
switch (c){
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
case 9:
return "nine";
}
return "";
}
private static String number2string2(int c){
switch (c){
case 2:
return "double";
case 3:
return "triple";
case 4:
return "quadruple";
case 5:
return "quintuple";
case 6:
return "sextuple";
case 7:
return "septuple";
case 8:
return "octuple";
case 9:
return "nonuple";
case 10:
return "decuple";
}
return "";
}
private static String convert(String current, StringBuilder sb) {
char c[] = current.toCharArray();
for(int i = 0; i < c.length; i++){
int k = 1;
while(i + k < c.length && c[i] == c[i+k]){
k++;
}
k--;
if(k > 0 && k < 10){
sb.append(' ');
sb.append(number2string2(k + 1));
i += k;
}
else if(k >= 10){
while(k > 0) {
sb.append(' ');
sb.append(number2string(c[i] - '0'));
i++;
k--;
}
}
sb.append(' ');
sb.append(number2string(c[i]-'0'));
}
return null;
}
}
| 3,232 | 0.414604 | 0.395421 | 113 | 27.60177 | 15.877038 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566372 | false | false | 4 |
1504e47bc673cc33f84a9a2f3316e413efd21e79 | 31,301,721,715,419 | 2de53578996b84bfbcd1e1ca31ca957f3304b236 | /object-oriented-programming/2018-Patter-Adapter-FullName/FullNameAdapter1.java | 8b379bf9b1c47add45dc9fab9ed4477641a4133f | [] | no_license | star6973/cse_project | https://github.com/star6973/cse_project | 6caaa02e7e183da6884085c17e3fe395f776b05c | 052bb3cf0fb26e346d4fb25ff15d9c96729c1fed | refs/heads/master | 2023-02-02T07:23:58.648000 | 2021-07-18T15:02:06 | 2021-07-18T15:02:06 | 138,172,374 | 0 | 1 | null | false | 2020-06-05T15:22:21 | 2018-06-21T13:14:13 | 2020-06-02T13:39:04 | 2020-06-02T13:39:02 | 170,424 | 0 | 2 | 2 | Jupyter Notebook | false | false | // 객체 어댑터 방식
public class FullNameAdapter1 implements FullName { // HAS-A
User user;
public FullNameAdapter1(User user) {
this.user = user;
}
@Override
public String getFullName() {
return user.getFirstName() + user.getLastName();
}
}
| UTF-8 | Java | 265 | java | FullNameAdapter1.java | Java | [] | null | [] | // 객체 어댑터 방식
public class FullNameAdapter1 implements FullName { // HAS-A
User user;
public FullNameAdapter1(User user) {
this.user = user;
}
@Override
public String getFullName() {
return user.getFirstName() + user.getLastName();
}
}
| 265 | 0.693227 | 0.685259 | 15 | 15.733334 | 18.961246 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
f319e629e6c9d15e15403b547080c3a7e792c905 | 39,084,202,419,998 | d7f72c2d6eb255c90b0ce73d4537fee2003f913b | /NewBaron/src/me/griffdragon/NewBaron/Events/WorldEvents.java | b2491ecf92464f3fac55269a2ca8a6a39c81e08d | [] | no_license | griffdragon7/Baron | https://github.com/griffdragon7/Baron | 7851cdbc547d0965cdcbab8eb73749a2d073ff70 | 2a499c027f10838dab49f96ce06ac475bc2e2f36 | refs/heads/master | 2022-12-16T06:07:59.077000 | 2020-09-17T19:00:00 | 2020-09-17T19:00:00 | 295,230,066 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.griffdragon.NewBaron.Events;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.scheduler.BukkitRunnable;
import me.griffdragon.NewBaron.BaronCore;
public class WorldEvents implements Listener {
private final BaronCore main;
public WorldEvents(BaronCore main) {
this.main = main;
}
int level1 = 100;
int level2 = 200;
int level3 = 300;
int level4 = 400;
int level5 = 500;
int level6 = 600;
int level7 = 700;
int level8 = 800;
int level9 = 900;
@EventHandler
public void setMobLevel(EntitySpawnEvent e) {
if (e.getEntity() instanceof LivingEntity) {
LivingEntity ent = (LivingEntity) e.getEntity();
Location spawn = ent.getLocation().getWorld().getSpawnLocation();
Location mobLocation = e.getLocation();
new BukkitRunnable() {
@Override
public void run() {
if (spawn.distance(mobLocation) < level1) {
ent.setMetadata("1", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 1");
} else if (spawn.distance(mobLocation) < level2 && spawn.distance(mobLocation) > level1) {
ent.setMetadata("2", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 2");
} else if (spawn.distance(mobLocation) < level3 && spawn.distance(mobLocation) > level2) {
ent.setMetadata("3", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 3");
} else if (spawn.distance(mobLocation) < level4 && spawn.distance(mobLocation) > level3) {
ent.setMetadata("4", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 4");
} else if (spawn.distance(mobLocation) < level5 && spawn.distance(mobLocation) > level4) {
ent.setMetadata("5", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 5");
} else if (spawn.distance(mobLocation) < level6 && spawn.distance(mobLocation) > level5) {
ent.setMetadata("6", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 6");
} else if (spawn.distance(mobLocation) < level7 && spawn.distance(mobLocation) > level6) {
ent.setMetadata("7", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 7");
} else if (spawn.distance(mobLocation) < level8 && spawn.distance(mobLocation) > level7) {
ent.setMetadata("8", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 8");
} else if (spawn.distance(mobLocation) > level8) {
ent.setMetadata("9", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 9");
}
}
}.runTaskLater(main, 1l);
}
}
}
| UTF-8 | Java | 3,207 | java | WorldEvents.java | Java | [] | null | [] | package me.griffdragon.NewBaron.Events;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.scheduler.BukkitRunnable;
import me.griffdragon.NewBaron.BaronCore;
public class WorldEvents implements Listener {
private final BaronCore main;
public WorldEvents(BaronCore main) {
this.main = main;
}
int level1 = 100;
int level2 = 200;
int level3 = 300;
int level4 = 400;
int level5 = 500;
int level6 = 600;
int level7 = 700;
int level8 = 800;
int level9 = 900;
@EventHandler
public void setMobLevel(EntitySpawnEvent e) {
if (e.getEntity() instanceof LivingEntity) {
LivingEntity ent = (LivingEntity) e.getEntity();
Location spawn = ent.getLocation().getWorld().getSpawnLocation();
Location mobLocation = e.getLocation();
new BukkitRunnable() {
@Override
public void run() {
if (spawn.distance(mobLocation) < level1) {
ent.setMetadata("1", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 1");
} else if (spawn.distance(mobLocation) < level2 && spawn.distance(mobLocation) > level1) {
ent.setMetadata("2", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 2");
} else if (spawn.distance(mobLocation) < level3 && spawn.distance(mobLocation) > level2) {
ent.setMetadata("3", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 3");
} else if (spawn.distance(mobLocation) < level4 && spawn.distance(mobLocation) > level3) {
ent.setMetadata("4", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 4");
} else if (spawn.distance(mobLocation) < level5 && spawn.distance(mobLocation) > level4) {
ent.setMetadata("5", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 5");
} else if (spawn.distance(mobLocation) < level6 && spawn.distance(mobLocation) > level5) {
ent.setMetadata("6", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 6");
} else if (spawn.distance(mobLocation) < level7 && spawn.distance(mobLocation) > level6) {
ent.setMetadata("7", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 7");
} else if (spawn.distance(mobLocation) < level8 && spawn.distance(mobLocation) > level7) {
ent.setMetadata("8", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 8");
} else if (spawn.distance(mobLocation) > level8) {
ent.setMetadata("9", new FixedMetadataValue(main, "level"));
ent.setCustomNameVisible(true);
ent.setCustomName("Level 9");
}
}
}.runTaskLater(main, 1l);
}
}
}
| 3,207 | 0.672591 | 0.650452 | 87 | 34.862068 | 26.842741 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.816092 | false | false | 4 |
56a30d5c26beaa1090cb578d31dad01b09fe5693 | 39,127,152,096,467 | 5cb4602b48dbeed7fee666626c616dc466baa110 | /src/test/java/MyFramework/date.java | 172aef480405b1da8b09ef5e9e34f0011374379e | [] | no_license | sushilkhuttan/Framework2 | https://github.com/sushilkhuttan/Framework2 | 2d6d0e143a28ac13ffd91ad2433d504553d86e4e | 7508ce9951b7363d985fecd14172f89850255567 | refs/heads/master | 2021-04-16T01:46:43.059000 | 2020-09-14T02:13:11 | 2020-09-14T02:13:11 | 249,317,549 | 0 | 0 | null | false | 2020-10-13T20:34:16 | 2020-03-23T02:30:56 | 2020-09-14T02:13:34 | 2020-10-13T20:34:15 | 4,248 | 0 | 0 | 1 | HTML | false | false | package MyFramework;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.testng.annotations.Test;
@Test
public class date {
public void datenow() {
//System.out.println("hello");
DateFormat df = new SimpleDateFormat("ddmmyyHHmmss");
//Date date = new Date();
System.out.print(df.format(new Date()));
//System.out.println(abc);
/*DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
//get current date time with Date()
Date date = new Date();
// Now format the date
String dateFormatted= dateFormat.format(date);
System.out.println(dateFormatted);*/
}
}
| UTF-8 | Java | 627 | java | date.java | Java | [] | null | [] | package MyFramework;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.testng.annotations.Test;
@Test
public class date {
public void datenow() {
//System.out.println("hello");
DateFormat df = new SimpleDateFormat("ddmmyyHHmmss");
//Date date = new Date();
System.out.print(df.format(new Date()));
//System.out.println(abc);
/*DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
//get current date time with Date()
Date date = new Date();
// Now format the date
String dateFormatted= dateFormat.format(date);
System.out.println(dateFormatted);*/
}
}
| 627 | 0.725678 | 0.725678 | 28 | 21.392857 | 17.917149 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
ce3b9902fb953ca970d075a6f0b2a8f42105e7c2 | 34,763,465,342,671 | 261c917f328df69ec4c789070d4212fdb16a81b6 | /src/main/java/com/kite/intellij/notifications/KiteServiceNotificationsListener.java | ea4b5a4b77c7650f496ff1b495deb8a55846d5f8 | [
"BSD-3-Clause"
] | permissive | aikozijlemans/intellij-plugin | https://github.com/aikozijlemans/intellij-plugin | d6383c10b97cc98e63c5232a11c5c898739a1e0b | dc1361bb3da33f4cc2e2b7ea8aeb9fa4c3b6e0ab | refs/heads/main | 2023-09-05T04:57:54.513000 | 2021-11-23T19:48:46 | 2021-11-23T19:50:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kite.intellij.notifications;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.startup.StartupManager;
import com.kite.intellij.KiteProjectLifecycleService;
import com.kite.intellij.backend.KiteApiService;
import com.kite.intellij.backend.json.KiteJsonParsing;
import com.kite.intellij.backend.model.KiteServiceNotification;
import com.kite.intellij.ui.notifications.KiteNotifications;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
/**
* Listens for HTTP responses with status 503 (service unavailable) and displays
* a notification if the HTTP response's body contained one.
*/
public class KiteServiceNotificationsListener implements ProjectManagerListener {
private static final Logger LOG = Logger.getInstance("#kite.notifications");
@Override
public void projectOpened(@NotNull Project project) {
if (project.isDefault()) {
return;
}
StartupManager.getInstance(project).runAfterOpened(() -> {
KiteApiService.getInstance().addHttpRequestStatusListener((statusCode, e, path, requestPath) -> {
if (statusCode == 503 && e != null) {
// whitelist paths for paywall notifications
// we must not show notifications for completions and signature panel
if (requestPath == null || requestPath.startsWith("/codenav/editor/related")) {
// show notification only for responses with a reason
String reason = KiteApiService.getInstance().getJsonParsing().parseReason(e.getBody());
if ("AllFeaturesProPaywallLocked".equals(reason)) {
handleKiteNotification(project, e.getBody());
return true;
}
return false;
}
}
return false;
}, KiteProjectLifecycleService.getInstance(project));
});
}
private void handleKiteNotification(@NotNull Project project, @Nullable String body) {
if (project.isDisposed()) {
return;
}
try {
KiteJsonParsing jsonParsing = KiteApiService.getInstance().getJsonParsing();
KiteServiceNotification notification = jsonParsing.parseKiteNotification(body);
KiteNotifications.showServiceNotification(project, notification);
} catch (Exception e) {
LOG.warn("error parsing Kite notification", e);
}
}
}
| UTF-8 | Java | 2,688 | java | KiteServiceNotificationsListener.java | Java | [] | null | [] | package com.kite.intellij.notifications;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.startup.StartupManager;
import com.kite.intellij.KiteProjectLifecycleService;
import com.kite.intellij.backend.KiteApiService;
import com.kite.intellij.backend.json.KiteJsonParsing;
import com.kite.intellij.backend.model.KiteServiceNotification;
import com.kite.intellij.ui.notifications.KiteNotifications;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
/**
* Listens for HTTP responses with status 503 (service unavailable) and displays
* a notification if the HTTP response's body contained one.
*/
public class KiteServiceNotificationsListener implements ProjectManagerListener {
private static final Logger LOG = Logger.getInstance("#kite.notifications");
@Override
public void projectOpened(@NotNull Project project) {
if (project.isDefault()) {
return;
}
StartupManager.getInstance(project).runAfterOpened(() -> {
KiteApiService.getInstance().addHttpRequestStatusListener((statusCode, e, path, requestPath) -> {
if (statusCode == 503 && e != null) {
// whitelist paths for paywall notifications
// we must not show notifications for completions and signature panel
if (requestPath == null || requestPath.startsWith("/codenav/editor/related")) {
// show notification only for responses with a reason
String reason = KiteApiService.getInstance().getJsonParsing().parseReason(e.getBody());
if ("AllFeaturesProPaywallLocked".equals(reason)) {
handleKiteNotification(project, e.getBody());
return true;
}
return false;
}
}
return false;
}, KiteProjectLifecycleService.getInstance(project));
});
}
private void handleKiteNotification(@NotNull Project project, @Nullable String body) {
if (project.isDisposed()) {
return;
}
try {
KiteJsonParsing jsonParsing = KiteApiService.getInstance().getJsonParsing();
KiteServiceNotification notification = jsonParsing.parseKiteNotification(body);
KiteNotifications.showServiceNotification(project, notification);
} catch (Exception e) {
LOG.warn("error parsing Kite notification", e);
}
}
}
| 2,688 | 0.653646 | 0.651414 | 64 | 41 | 32.248062 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 4 |
3f4029f59a8e34b181f1731cc40e3102d35b4a9a | 39,144,331,963,164 | 94ac686988dc685f560c0ca29a7965244cc623c1 | /TheLastDungeonEditor/src/beans/Cell.java | c539dd2e7403c011cf0978db37bca8bd71738c3d | [] | no_license | KaindorfProgCorner/the-last-dugeon2 | https://github.com/KaindorfProgCorner/the-last-dugeon2 | 228ca84fbd2d872f5561c19772fa62e5ebf044f6 | fb5393c4c9003d8c2504a9fd99835a68bd3b43a3 | refs/heads/master | 2016-09-13T10:34:29.936000 | 2016-05-23T19:18:58 | 2016-05-23T19:18:58 | 59,510,752 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 beans;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Robbo13
*/
public class Cell extends JLabel{
private boolean placed = false;
public boolean isAlreadyThere(JPanel graphic){
for (Object obj : graphic.getComponents()) {
Cell forcell = (Cell) obj;
if(forcell.equals(this)){
continue;
}
if(forcell.getLocation().equals(this.getLocation()) && forcell.getIcon().equals(this.getIcon())){
return true;
}
}
return false;
}
public Cell(String text, Icon icon, int horizontalAlignment) {
super(text, icon, horizontalAlignment);
}
public Cell(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
}
public Cell(String text) {
super(text);
}
public Cell(Icon image, int horizontalAlignment) {
super(image, horizontalAlignment);
}
public Cell(Icon image) {
super(image);
}
public Cell() {
}
public boolean isPlaced() {
return placed;
}
public void setPlaced(boolean placed) {
this.placed = placed;
}
}
| UTF-8 | Java | 1,489 | java | Cell.java | Java | [
{
"context": "\nimport javax.swing.JPanel;\r\n\r\n/**\r\n *\r\n * @author Robbo13\r\n */\r\npublic class Cell extends JLabel{\r\n \r\n ",
"end": 319,
"score": 0.9994693994522095,
"start": 312,
"tag": "USERNAME",
"value": "Robbo13"
}
] | null | [] | /*
* 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 beans;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Robbo13
*/
public class Cell extends JLabel{
private boolean placed = false;
public boolean isAlreadyThere(JPanel graphic){
for (Object obj : graphic.getComponents()) {
Cell forcell = (Cell) obj;
if(forcell.equals(this)){
continue;
}
if(forcell.getLocation().equals(this.getLocation()) && forcell.getIcon().equals(this.getIcon())){
return true;
}
}
return false;
}
public Cell(String text, Icon icon, int horizontalAlignment) {
super(text, icon, horizontalAlignment);
}
public Cell(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
}
public Cell(String text) {
super(text);
}
public Cell(Icon image, int horizontalAlignment) {
super(image, horizontalAlignment);
}
public Cell(Icon image) {
super(image);
}
public Cell() {
}
public boolean isPlaced() {
return placed;
}
public void setPlaced(boolean placed) {
this.placed = placed;
}
}
| 1,489 | 0.577569 | 0.576226 | 63 | 21.63492 | 22.477715 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
d741967c7c37669457ad157f101e153d34ed138f | 36,060,545,462,024 | 8c06be2e1932c781f0b351c90fd767172f9a4d48 | /fastFramework/src/main/java/com/tesla/framework/support/paging/timeline/TimeLinePaging.java | 37f07c154b83f199100ba4583c91bc788ebca689 | [] | no_license | bill-bil/FastAndroid | https://github.com/bill-bil/FastAndroid | f2ebd1c91bb662c290f087b184e101721859c153 | 3f89ad2f6f6dec0321bc4c52215c91e931931460 | refs/heads/master | 2023-04-02T16:47:02.528000 | 2021-04-17T03:35:45 | 2021-04-17T03:35:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tesla.framework.support.paging.timeline;
import android.text.TextUtils;
import com.tesla.framework.support.paging.IPaging;
import java.io.Serializable;
/**
* Created by jerryliu on 2017/3/31.
*/
public class TimeLinePaging<T extends TimelineResult,Ts extends Serializable> implements IPaging<T,Ts>{
private String firstId;
private String lastId;
@Override
public String getPreviousPage() {
return firstId;
}
@Override
public String getNextPage() {
if (TextUtils.isEmpty(lastId)){
return null;
}
return String.valueOf(Long.parseLong(lastId));
}
@Override
public void processData(Ts newDatas, T firstData, T lastData) {
if (firstData != null){
firstId = firstData.getId();
}
if (lastData != null){
lastId = lastData.getId();
}
}
}
| UTF-8 | Java | 896 | java | TimeLinePaging.java | Java | [
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by jerryliu on 2017/3/31.\n */\n\npublic class TimeLinePaging<T ",
"end": 194,
"score": 0.9995282888412476,
"start": 186,
"tag": "USERNAME",
"value": "jerryliu"
}
] | null | [] | package com.tesla.framework.support.paging.timeline;
import android.text.TextUtils;
import com.tesla.framework.support.paging.IPaging;
import java.io.Serializable;
/**
* Created by jerryliu on 2017/3/31.
*/
public class TimeLinePaging<T extends TimelineResult,Ts extends Serializable> implements IPaging<T,Ts>{
private String firstId;
private String lastId;
@Override
public String getPreviousPage() {
return firstId;
}
@Override
public String getNextPage() {
if (TextUtils.isEmpty(lastId)){
return null;
}
return String.valueOf(Long.parseLong(lastId));
}
@Override
public void processData(Ts newDatas, T firstData, T lastData) {
if (firstData != null){
firstId = firstData.getId();
}
if (lastData != null){
lastId = lastData.getId();
}
}
}
| 896 | 0.635045 | 0.627232 | 40 | 21.4 | 22.426323 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 4 |
511a23fc6cc6d756a6ee03488b7e29c29135f47f | 36,060,545,459,573 | 8be5be4632312684d562054b910a549871589c60 | /hugegraph-example/src/main/java/com/baidu/hugegraph/example/Example3.java | 53b174f40537a036b256b9f61586aa9064a0e6ff | [
"Apache-2.0"
] | permissive | imbaGeek/hugegraph | https://github.com/imbaGeek/hugegraph | dcb1dadf69fd24e6a7d036f2f107abb4cc015513 | 5fd484abd1c939c5d7d75eb8e4be1079b7b46417 | refs/heads/master | 2021-12-15T18:06:48.389000 | 2021-11-26T08:07:12 | 2021-11-26T08:07:12 | 172,666,653 | 2 | 0 | Apache-2.0 | true | 2021-11-10T08:04:32 | 2019-02-26T08:11:49 | 2021-11-09T06:44:30 | 2021-11-10T08:04:31 | 10,196 | 2 | 0 | 1 | Java | false | false | /*
* Copyright 2017 HugeGraph Authors
*
* 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.baidu.hugegraph.example;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import com.baidu.hugegraph.HugeFactory;
import com.baidu.hugegraph.HugeGraph;
import com.baidu.hugegraph.schema.SchemaManager;
import com.baidu.hugegraph.util.Log;
public class Example3 {
private static final Logger LOG = Log.logger(Example3.class);
public static void main(String[] args) throws Exception {
LOG.info("Example3 start!");
HugeGraph graph = ExampleUtil.loadGraph();
Example3.loadNeighborRankData(graph);
Example3.loadPersonalRankData(graph);
graph.close();
HugeFactory.shutdown(30L);
}
public static void loadNeighborRankData(final HugeGraph graph) {
SchemaManager schema = graph.schema();
schema.propertyKey("name").asText().ifNotExist().create();
schema.vertexLabel("person")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.vertexLabel("movie")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.edgeLabel("follow")
.sourceLabel("person")
.targetLabel("person")
.ifNotExist()
.create();
schema.edgeLabel("like")
.sourceLabel("person")
.targetLabel("movie")
.ifNotExist()
.create();
schema.edgeLabel("directedBy")
.sourceLabel("movie")
.targetLabel("person")
.ifNotExist()
.create();
graph.tx().open();
Vertex O = graph.addVertex(T.label, "person", T.id, "O", "name", "O");
Vertex A = graph.addVertex(T.label, "person", T.id, "A", "name", "A");
Vertex B = graph.addVertex(T.label, "person", T.id, "B", "name", "B");
Vertex C = graph.addVertex(T.label, "person", T.id, "C", "name", "C");
Vertex D = graph.addVertex(T.label, "person", T.id, "D", "name", "D");
Vertex E = graph.addVertex(T.label, "movie", T.id, "E", "name", "E");
Vertex F = graph.addVertex(T.label, "movie", T.id, "F", "name", "F");
Vertex G = graph.addVertex(T.label, "movie", T.id, "G", "name", "G");
Vertex H = graph.addVertex(T.label, "movie", T.id, "H", "name", "H");
Vertex I = graph.addVertex(T.label, "movie", T.id, "I", "name", "I");
Vertex J = graph.addVertex(T.label, "movie", T.id, "J", "name", "J");
Vertex K = graph.addVertex(T.label, "person", T.id, "K", "name", "K");
Vertex L = graph.addVertex(T.label, "person", T.id, "L", "name", "L");
Vertex M = graph.addVertex(T.label, "person", T.id, "M", "name", "M");
O.addEdge("follow", A);
O.addEdge("follow", B);
O.addEdge("follow", C);
D.addEdge("follow", O);
A.addEdge("follow", B);
A.addEdge("like", E);
A.addEdge("like", F);
B.addEdge("like", G);
B.addEdge("like", H);
C.addEdge("like", I);
C.addEdge("like", J);
E.addEdge("directedBy", K);
F.addEdge("directedBy", B);
F.addEdge("directedBy", L);
G.addEdge("directedBy", M);
graph.tx().commit();
}
public static void loadPersonalRankData(final HugeGraph graph) {
SchemaManager schema = graph.schema();
schema.propertyKey("name").asText().ifNotExist().create();
schema.vertexLabel("person")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.vertexLabel("movie")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.edgeLabel("like")
.sourceLabel("person")
.targetLabel("movie")
.ifNotExist()
.create();
graph.tx().open();
Vertex A = graph.addVertex(T.label, "person", T.id, "A", "name", "A");
Vertex B = graph.addVertex(T.label, "person", T.id, "B", "name", "B");
Vertex C = graph.addVertex(T.label, "person", T.id, "C", "name", "C");
Vertex a = graph.addVertex(T.label, "movie", T.id, "a", "name", "a");
Vertex b = graph.addVertex(T.label, "movie", T.id, "b", "name", "b");
Vertex c = graph.addVertex(T.label, "movie", T.id, "c", "name", "c");
Vertex d = graph.addVertex(T.label, "movie", T.id, "d", "name", "d");
A.addEdge("like", a);
A.addEdge("like", c);
B.addEdge("like", a);
B.addEdge("like", b);
B.addEdge("like", c);
B.addEdge("like", d);
C.addEdge("like", c);
C.addEdge("like", d);
graph.tx().commit();
}
}
| UTF-8 | Java | 5,761 | java | Example3.java | Java | [] | null | [] | /*
* Copyright 2017 HugeGraph Authors
*
* 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.baidu.hugegraph.example;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import com.baidu.hugegraph.HugeFactory;
import com.baidu.hugegraph.HugeGraph;
import com.baidu.hugegraph.schema.SchemaManager;
import com.baidu.hugegraph.util.Log;
public class Example3 {
private static final Logger LOG = Log.logger(Example3.class);
public static void main(String[] args) throws Exception {
LOG.info("Example3 start!");
HugeGraph graph = ExampleUtil.loadGraph();
Example3.loadNeighborRankData(graph);
Example3.loadPersonalRankData(graph);
graph.close();
HugeFactory.shutdown(30L);
}
public static void loadNeighborRankData(final HugeGraph graph) {
SchemaManager schema = graph.schema();
schema.propertyKey("name").asText().ifNotExist().create();
schema.vertexLabel("person")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.vertexLabel("movie")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.edgeLabel("follow")
.sourceLabel("person")
.targetLabel("person")
.ifNotExist()
.create();
schema.edgeLabel("like")
.sourceLabel("person")
.targetLabel("movie")
.ifNotExist()
.create();
schema.edgeLabel("directedBy")
.sourceLabel("movie")
.targetLabel("person")
.ifNotExist()
.create();
graph.tx().open();
Vertex O = graph.addVertex(T.label, "person", T.id, "O", "name", "O");
Vertex A = graph.addVertex(T.label, "person", T.id, "A", "name", "A");
Vertex B = graph.addVertex(T.label, "person", T.id, "B", "name", "B");
Vertex C = graph.addVertex(T.label, "person", T.id, "C", "name", "C");
Vertex D = graph.addVertex(T.label, "person", T.id, "D", "name", "D");
Vertex E = graph.addVertex(T.label, "movie", T.id, "E", "name", "E");
Vertex F = graph.addVertex(T.label, "movie", T.id, "F", "name", "F");
Vertex G = graph.addVertex(T.label, "movie", T.id, "G", "name", "G");
Vertex H = graph.addVertex(T.label, "movie", T.id, "H", "name", "H");
Vertex I = graph.addVertex(T.label, "movie", T.id, "I", "name", "I");
Vertex J = graph.addVertex(T.label, "movie", T.id, "J", "name", "J");
Vertex K = graph.addVertex(T.label, "person", T.id, "K", "name", "K");
Vertex L = graph.addVertex(T.label, "person", T.id, "L", "name", "L");
Vertex M = graph.addVertex(T.label, "person", T.id, "M", "name", "M");
O.addEdge("follow", A);
O.addEdge("follow", B);
O.addEdge("follow", C);
D.addEdge("follow", O);
A.addEdge("follow", B);
A.addEdge("like", E);
A.addEdge("like", F);
B.addEdge("like", G);
B.addEdge("like", H);
C.addEdge("like", I);
C.addEdge("like", J);
E.addEdge("directedBy", K);
F.addEdge("directedBy", B);
F.addEdge("directedBy", L);
G.addEdge("directedBy", M);
graph.tx().commit();
}
public static void loadPersonalRankData(final HugeGraph graph) {
SchemaManager schema = graph.schema();
schema.propertyKey("name").asText().ifNotExist().create();
schema.vertexLabel("person")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.vertexLabel("movie")
.properties("name")
.useCustomizeStringId()
.ifNotExist()
.create();
schema.edgeLabel("like")
.sourceLabel("person")
.targetLabel("movie")
.ifNotExist()
.create();
graph.tx().open();
Vertex A = graph.addVertex(T.label, "person", T.id, "A", "name", "A");
Vertex B = graph.addVertex(T.label, "person", T.id, "B", "name", "B");
Vertex C = graph.addVertex(T.label, "person", T.id, "C", "name", "C");
Vertex a = graph.addVertex(T.label, "movie", T.id, "a", "name", "a");
Vertex b = graph.addVertex(T.label, "movie", T.id, "b", "name", "b");
Vertex c = graph.addVertex(T.label, "movie", T.id, "c", "name", "c");
Vertex d = graph.addVertex(T.label, "movie", T.id, "d", "name", "d");
A.addEdge("like", a);
A.addEdge("like", c);
B.addEdge("like", a);
B.addEdge("like", b);
B.addEdge("like", c);
B.addEdge("like", d);
C.addEdge("like", c);
C.addEdge("like", d);
graph.tx().commit();
}
}
| 5,761 | 0.565353 | 0.562576 | 174 | 32.109196 | 26.241684 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.195402 | false | false | 4 |
5e6f5eac18ce718ae6f9e4b3f897b983a10507a6 | 37,546,604,125,152 | 02aa1579a2ef75d9d08c7fafde6b3d33885266ef | /ratpack-handlebars/src/main/java/ratpack/handlebars/HandlebarsModule.java | f086fbcdb7617bc57328a5eb16e93e39ec1ed2e1 | [
"Apache-2.0"
] | permissive | kristinclemens/ratpack | https://github.com/kristinclemens/ratpack | 9c749897f5ce79ad1143fb9d6ea12c3341b159d0 | 481263a1689397ea4d01ed72ad273f757aa36b64 | refs/heads/master | 2020-05-15T14:12:49.211000 | 2019-04-19T17:49:17 | 2019-04-19T17:49:17 | 182,327,915 | 1 | 0 | NOASSERTION | true | 2019-04-19T21:30:00 | 2019-04-19T21:29:59 | 2019-04-19T17:49:24 | 2019-04-19T17:49:18 | 23,202 | 0 | 0 | 0 | null | false | false | /*
* Copyright 2013 the original author or authors.
*
* 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 ratpack.handlebars;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.cache.ConcurrentMapTemplateCache;
import com.github.jknack.handlebars.cache.TemplateCache;
import com.github.jknack.handlebars.io.TemplateLoader;
import com.google.common.reflect.TypeToken;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import ratpack.file.FileSystemBinding;
import ratpack.guice.ConfigurableModule;
import ratpack.guice.internal.GuiceUtil;
import ratpack.handlebars.internal.FileSystemBindingTemplateLoader;
import ratpack.handlebars.internal.HandlebarsTemplateRenderer;
import ratpack.server.ServerConfig;
/**
* An extension module that provides support for Handlebars.java templating engine.
* <p>
* To use it one has to register the module and then render {@link ratpack.handlebars.Template} instances.
* Instances of {@code Template} can be created using one of the
* {@link ratpack.handlebars.Template#handlebarsTemplate(java.util.Map, String, String)}
* static methods.
* </p>
* <p>
* By default templates are looked up in the {@code handlebars} directory of the application root with a {@code .hbs} suffix.
* So {@code handlebarsTemplate("my/template/path")} maps to {@code handlebars/my/template/path.hbs} in the application root directory.
* This can be configured using {@link ratpack.handlebars.HandlebarsModule.Config#templatesPath(String)} and {@link ratpack.handlebars.HandlebarsModule.Config#templatesSuffix(String)}.
* </p>
* <p>
* The default template delimiters are {@code {{ }}} but can be configured using {@link ratpack.handlebars.HandlebarsModule.Config#delimiters(String, String)}.
* </p>
* <p>
* Response content type can be manually specified, i.e. {@code handlebarsTemplate("template", model, "text/html")} or can
* be detected based on the template extension. Mapping between file extensions and content types is performed using
* {@link ratpack.file.MimeTypes} contextual object so content type for {@code handlebarsTemplate("template.html")}
* would be {@code text/html} by default.
* </p>
* <p>Custom handlebars helpers can be registered by binding instances of {@link ratpack.handlebars.NamedHelper}.</p>
* <pre class="java">{@code
* import ratpack.guice.Guice;
* import ratpack.handlebars.HandlebarsModule;
* import ratpack.test.embed.EphemeralBaseDir;
* import ratpack.test.embed.EmbeddedApp;
* import java.nio.file.Path;
*
* import static ratpack.handlebars.Template.handlebarsTemplate;
* import static org.junit.Assert.*;
*
* public class Example {
* public static void main(String... args) throws Exception {
* EphemeralBaseDir.tmpDir().use(baseDir -> {
* baseDir.write("handlebars/myTemplate.html.hbs", "Hello {{name}}!");
* EmbeddedApp.of(s -> s
* .serverConfig(c -> c.baseDir(baseDir.getRoot()))
* .registry(Guice.registry(b -> b.module(HandlebarsModule.class)))
* .handlers(chain -> chain
* .get(ctx -> ctx.render(handlebarsTemplate("myTemplate.html", m -> m.put("name", "Ratpack"))))
* )
* ).test(httpClient -> {
* assertEquals("Hello Ratpack!", httpClient.getText());
* });
* });
* }
* }
* }</pre>
*
* @see <a href="http://jknack.github.io/handlebars.java/" target="_blank">Handlebars.java</a>
*/
public class HandlebarsModule extends ConfigurableModule<HandlebarsModule.Config> {
private static final TypeToken<NamedHelper<?>> NAMED_HELPER_TYPE = new TypeToken<NamedHelper<?>>() {
};
/**
* The configuration object for {@link HandlebarsModule}.
*/
public static class Config {
private String templatesPath = "handlebars";
private String templatesSuffix = ".hbs";
private String startDelimiter = Handlebars.DELIM_START;
private String endDelimiter = Handlebars.DELIM_END;
private int cacheSize = 100;
private Boolean reloadable;
public String getTemplatesPath() {
return templatesPath;
}
public Config templatesPath(String templatesPath) {
this.templatesPath = templatesPath;
return this;
}
public String getTemplatesSuffix() {
return templatesSuffix;
}
public Config templatesSuffix(String templatesSuffix) {
this.templatesSuffix = templatesSuffix;
return this;
}
public String getStartDelimiter() {
return startDelimiter;
}
public String getEndDelimiter() {
return endDelimiter;
}
public Config delimiters(String startDelimiter, String endDelimiter) {
this.startDelimiter = startDelimiter;
this.endDelimiter = endDelimiter;
return this;
}
public int getCacheSize() {
return cacheSize;
}
public Config cacheSize(int cacheSize) {
this.cacheSize = cacheSize;
return this;
}
public Boolean isReloadable() {
return reloadable;
}
public Config reloadable(boolean reloadable) {
this.reloadable = reloadable;
return this;
}
}
@Override
protected void configure() {
bind(HandlebarsTemplateRenderer.class).in(Singleton.class);
}
@SuppressWarnings("UnusedDeclaration")
@Provides
@Singleton
TemplateLoader provideTemplateLoader(Config config, FileSystemBinding fileSystemBinding) {
FileSystemBinding templatesBinding = fileSystemBinding.binding(config.getTemplatesPath());
return new FileSystemBindingTemplateLoader(templatesBinding, config.getTemplatesSuffix());
}
@SuppressWarnings("UnusedDeclaration")
@Provides
@Singleton
TemplateCache provideTemplateCache(Config config, ServerConfig serverConfig) {
boolean reloadable = config.isReloadable() == null ? serverConfig.isDevelopment() : config.isReloadable();
return new ConcurrentMapTemplateCache().setReload(reloadable);
}
@SuppressWarnings("UnusedDeclaration")
@Provides
@Singleton
Handlebars provideHandlebars(Config config, Injector injector, TemplateLoader templateLoader, TemplateCache templateCache) {
final Handlebars handlebars = new Handlebars()
.with(templateLoader)
.with(templateCache)
.startDelimiter(config.getStartDelimiter())
.endDelimiter(config.getEndDelimiter());
GuiceUtil.eachOfType(injector, NAMED_HELPER_TYPE, helper -> handlebars.registerHelper(helper.getName(), helper));
return handlebars;
}
}
| UTF-8 | Java | 6,996 | java | HandlebarsModule.java | Java | [
{
"context": "/\n\npackage ratpack.handlebars;\n\nimport com.github.jknack.handlebars.Handlebars;\nimport com.github.jknack.h",
"end": 668,
"score": 0.6925784945487976,
"start": 662,
"tag": "USERNAME",
"value": "jknack"
},
{
"context": "knack.handlebars.Handlebars;\nimport com.github.jknack.handlebars.cache.ConcurrentMapTemplateCache;\nimpo",
"end": 716,
"score": 0.6431266069412231,
"start": 713,
"tag": "USERNAME",
"value": "ack"
},
{
"context": "he.ConcurrentMapTemplateCache;\nimport com.github.jknack.handlebars.cache.TemplateCache;\nimport com.github",
"end": 786,
"score": 0.6287308931350708,
"start": 781,
"tag": "USERNAME",
"value": "knack"
},
{
"context": "andlebars.cache.TemplateCache;\nimport com.github.jknack.handlebars.io.TemplateLoader;\nimport com.google.c",
"end": 843,
"score": 0.5969263911247253,
"start": 838,
"tag": "USERNAME",
"value": "knack"
},
{
"context": "rsTemplate(\"myTemplate.html\", m -> m.put(\"name\", \"Ratpack\"))))\n * )\n * ).test(httpClient -> {",
"end": 3718,
"score": 0.9842492341995239,
"start": 3711,
"tag": "NAME",
"value": "Ratpack"
}
] | null | [] | /*
* Copyright 2013 the original author or authors.
*
* 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 ratpack.handlebars;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.cache.ConcurrentMapTemplateCache;
import com.github.jknack.handlebars.cache.TemplateCache;
import com.github.jknack.handlebars.io.TemplateLoader;
import com.google.common.reflect.TypeToken;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import ratpack.file.FileSystemBinding;
import ratpack.guice.ConfigurableModule;
import ratpack.guice.internal.GuiceUtil;
import ratpack.handlebars.internal.FileSystemBindingTemplateLoader;
import ratpack.handlebars.internal.HandlebarsTemplateRenderer;
import ratpack.server.ServerConfig;
/**
* An extension module that provides support for Handlebars.java templating engine.
* <p>
* To use it one has to register the module and then render {@link ratpack.handlebars.Template} instances.
* Instances of {@code Template} can be created using one of the
* {@link ratpack.handlebars.Template#handlebarsTemplate(java.util.Map, String, String)}
* static methods.
* </p>
* <p>
* By default templates are looked up in the {@code handlebars} directory of the application root with a {@code .hbs} suffix.
* So {@code handlebarsTemplate("my/template/path")} maps to {@code handlebars/my/template/path.hbs} in the application root directory.
* This can be configured using {@link ratpack.handlebars.HandlebarsModule.Config#templatesPath(String)} and {@link ratpack.handlebars.HandlebarsModule.Config#templatesSuffix(String)}.
* </p>
* <p>
* The default template delimiters are {@code {{ }}} but can be configured using {@link ratpack.handlebars.HandlebarsModule.Config#delimiters(String, String)}.
* </p>
* <p>
* Response content type can be manually specified, i.e. {@code handlebarsTemplate("template", model, "text/html")} or can
* be detected based on the template extension. Mapping between file extensions and content types is performed using
* {@link ratpack.file.MimeTypes} contextual object so content type for {@code handlebarsTemplate("template.html")}
* would be {@code text/html} by default.
* </p>
* <p>Custom handlebars helpers can be registered by binding instances of {@link ratpack.handlebars.NamedHelper}.</p>
* <pre class="java">{@code
* import ratpack.guice.Guice;
* import ratpack.handlebars.HandlebarsModule;
* import ratpack.test.embed.EphemeralBaseDir;
* import ratpack.test.embed.EmbeddedApp;
* import java.nio.file.Path;
*
* import static ratpack.handlebars.Template.handlebarsTemplate;
* import static org.junit.Assert.*;
*
* public class Example {
* public static void main(String... args) throws Exception {
* EphemeralBaseDir.tmpDir().use(baseDir -> {
* baseDir.write("handlebars/myTemplate.html.hbs", "Hello {{name}}!");
* EmbeddedApp.of(s -> s
* .serverConfig(c -> c.baseDir(baseDir.getRoot()))
* .registry(Guice.registry(b -> b.module(HandlebarsModule.class)))
* .handlers(chain -> chain
* .get(ctx -> ctx.render(handlebarsTemplate("myTemplate.html", m -> m.put("name", "Ratpack"))))
* )
* ).test(httpClient -> {
* assertEquals("Hello Ratpack!", httpClient.getText());
* });
* });
* }
* }
* }</pre>
*
* @see <a href="http://jknack.github.io/handlebars.java/" target="_blank">Handlebars.java</a>
*/
public class HandlebarsModule extends ConfigurableModule<HandlebarsModule.Config> {
private static final TypeToken<NamedHelper<?>> NAMED_HELPER_TYPE = new TypeToken<NamedHelper<?>>() {
};
/**
* The configuration object for {@link HandlebarsModule}.
*/
public static class Config {
private String templatesPath = "handlebars";
private String templatesSuffix = ".hbs";
private String startDelimiter = Handlebars.DELIM_START;
private String endDelimiter = Handlebars.DELIM_END;
private int cacheSize = 100;
private Boolean reloadable;
public String getTemplatesPath() {
return templatesPath;
}
public Config templatesPath(String templatesPath) {
this.templatesPath = templatesPath;
return this;
}
public String getTemplatesSuffix() {
return templatesSuffix;
}
public Config templatesSuffix(String templatesSuffix) {
this.templatesSuffix = templatesSuffix;
return this;
}
public String getStartDelimiter() {
return startDelimiter;
}
public String getEndDelimiter() {
return endDelimiter;
}
public Config delimiters(String startDelimiter, String endDelimiter) {
this.startDelimiter = startDelimiter;
this.endDelimiter = endDelimiter;
return this;
}
public int getCacheSize() {
return cacheSize;
}
public Config cacheSize(int cacheSize) {
this.cacheSize = cacheSize;
return this;
}
public Boolean isReloadable() {
return reloadable;
}
public Config reloadable(boolean reloadable) {
this.reloadable = reloadable;
return this;
}
}
@Override
protected void configure() {
bind(HandlebarsTemplateRenderer.class).in(Singleton.class);
}
@SuppressWarnings("UnusedDeclaration")
@Provides
@Singleton
TemplateLoader provideTemplateLoader(Config config, FileSystemBinding fileSystemBinding) {
FileSystemBinding templatesBinding = fileSystemBinding.binding(config.getTemplatesPath());
return new FileSystemBindingTemplateLoader(templatesBinding, config.getTemplatesSuffix());
}
@SuppressWarnings("UnusedDeclaration")
@Provides
@Singleton
TemplateCache provideTemplateCache(Config config, ServerConfig serverConfig) {
boolean reloadable = config.isReloadable() == null ? serverConfig.isDevelopment() : config.isReloadable();
return new ConcurrentMapTemplateCache().setReload(reloadable);
}
@SuppressWarnings("UnusedDeclaration")
@Provides
@Singleton
Handlebars provideHandlebars(Config config, Injector injector, TemplateLoader templateLoader, TemplateCache templateCache) {
final Handlebars handlebars = new Handlebars()
.with(templateLoader)
.with(templateCache)
.startDelimiter(config.getStartDelimiter())
.endDelimiter(config.getEndDelimiter());
GuiceUtil.eachOfType(injector, NAMED_HELPER_TYPE, helper -> handlebars.registerHelper(helper.getName(), helper));
return handlebars;
}
}
| 6,996 | 0.727416 | 0.725843 | 194 | 35.061855 | 35.745033 | 184 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.427835 | false | false | 4 |
7b4537f1649ba750aab9b21616343479ddba1a6f | 37,546,604,125,679 | e2043dd85b065f4a5d451bd9a2cf314860596dca | /src/main/java/com/glogger/automation/constants/Constants.java | 0203f09aec3273e39817d0a645640667b1045792 | [] | no_license | chiefmonks/glogger-automation | https://github.com/chiefmonks/glogger-automation | 1c536e04fdbf895b39fb9653502e9f26069b21f1 | 0707dace15c2df0da07dedd6d52375b35b8eabf6 | refs/heads/master | 2022-10-29T07:58:57.229000 | 2019-11-25T09:54:39 | 2019-11-25T09:54:39 | 223,468,443 | 0 | 0 | null | false | 2022-10-05T19:37:53 | 2019-11-22T19:05:05 | 2019-11-25T09:54:42 | 2022-10-05T19:37:50 | 83 | 0 | 0 | 5 | Java | false | false | package com.glogger.automation.constants;
import java.util.Calendar;
import java.util.GregorianCalendar;
import com.glogger.automation.util.PropertyUtil;
public interface Constants {
public static final Calendar START_TIME = GregorianCalendar.getInstance();
static final String URL = PropertyUtil.getInstance().getProperty("url");
static final String USERNAME = PropertyUtil.getInstance().getProperty("username");
static final String PASSWORD = PropertyUtil.getInstance().getProperty("password");
static final String MEAL_TIME = PropertyUtil.getInstance().getProperty("meal-time");
static final String MEAL_DURATION = PropertyUtil.getInstance().getProperty("meal-duration");
static final String TIME_BUFFER = PropertyUtil.getInstance().getProperty("time-buffer");
static final String TIME_OUT = PropertyUtil.getInstance().getProperty("time-out");
static final String SUB_GROUP_NAME = PropertyUtil.getInstance().getProperty("sub-group");
static final String OFFICE_LOCATION = PropertyUtil.getInstance().getProperty("office-location");
static final String REMOTE_ADDRESS = PropertyUtil.getInstance().getProperty("remoteAddress");
static final String PROXY_HOST = PropertyUtil.getInstance().getProperty("http.proxyHost");
static final String PROXY_PORT = PropertyUtil.getInstance().getProperty("http.proxyPort");
static final String FIX_LOGIN = PropertyUtil.getInstance().getProperty("fix-login");
static final String FIX_MEAL = PropertyUtil.getInstance().getProperty("fix-meal");
static final String FIX_CLOCKIN = PropertyUtil.getInstance().getProperty("fix-clockin");
static final String FIX_LOGOUT = PropertyUtil.getInstance().getProperty("fix-logout");
static final Boolean IS_DYNAMIC = new Boolean(PropertyUtil.getInstance().getProperty("dynamic-schedule"));
static final int RETRIES = 3;
static final int SUB_GROUP_ID = 222;
static final int REAL_DIFFERENCE = 4;
static final int LOCATION_ID = 4;
static final String HOME = URL + "user_home";
static final String LOGIN = URL + "loggin/loggin";
static final String VERIFY_SESSION = URL + "loggin/VerifySession";
static final String CHANGE_STATUS = URL + "user_home/changeStatus";
static final String END_SHIFT = URL + "user_home/endShift";
static final String VERIFY_CREDENTIALS = URL + "loggin/VerifyCredentials";
static final String GET_LOCATION = URL + "loggin/getInstance";
static final String SUB_GROUP = URL + "loggin/getSubgroup";
static final String GET_LAST_SHIFT = URL + "loggin/GetLastShift";
static final String SIGN_OUT = URL + "loggin/Logout";
static final String RECENT_ACTIVITIES = URL + "user_home/GetRecentActivities";
static final String KEY_USERNAME = "username";
static final String KEY_PASSWORD = "password";
static final String KEY_WINDOWS_LOGIN = "windows_login";
static final String KEY_SUB_GROUP = "subgroup_id";
static final String KEY_STATUS_ID = "status_id";
static final String KEY_USER_IP = "user_ip";
static final String KEY_INSTANCE_ID = "instance_id";
static final String KEY_EMP_ID = "emp_id";
static final String KEY_REAL_DIFFERENCE = "realDiference";
static final String KEY_LOGIN_EMP_ID = "EmpId";
static final String JSON_SUB_GROUP_LIST = "subgroups";
}
| UTF-8 | Java | 3,286 | java | Constants.java | Java | [
{
"context": "SERNAME = PropertyUtil.getInstance().getProperty(\"username\");\n\t\n\tstatic final String PASSWORD = PropertyUtil",
"end": 422,
"score": 0.9424902200698853,
"start": 414,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ities\";\n\n\t\n\t\n\tstatic final String KEY_USERNAME = \"username\";\n\t\n\tstatic final String KEY_PASSWORD = \"password",
"end": 2742,
"score": 0.9990754127502441,
"start": 2734,
"tag": "USERNAME",
"value": "username"
},
{
"context": "username\";\n\t\n\tstatic final String KEY_PASSWORD = \"password\";\n\t\n\tstatic final String KEY_WINDOWS_LOGIN = \"win",
"end": 2792,
"score": 0.9992607235908508,
"start": 2784,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package com.glogger.automation.constants;
import java.util.Calendar;
import java.util.GregorianCalendar;
import com.glogger.automation.util.PropertyUtil;
public interface Constants {
public static final Calendar START_TIME = GregorianCalendar.getInstance();
static final String URL = PropertyUtil.getInstance().getProperty("url");
static final String USERNAME = PropertyUtil.getInstance().getProperty("username");
static final String PASSWORD = PropertyUtil.getInstance().getProperty("password");
static final String MEAL_TIME = PropertyUtil.getInstance().getProperty("meal-time");
static final String MEAL_DURATION = PropertyUtil.getInstance().getProperty("meal-duration");
static final String TIME_BUFFER = PropertyUtil.getInstance().getProperty("time-buffer");
static final String TIME_OUT = PropertyUtil.getInstance().getProperty("time-out");
static final String SUB_GROUP_NAME = PropertyUtil.getInstance().getProperty("sub-group");
static final String OFFICE_LOCATION = PropertyUtil.getInstance().getProperty("office-location");
static final String REMOTE_ADDRESS = PropertyUtil.getInstance().getProperty("remoteAddress");
static final String PROXY_HOST = PropertyUtil.getInstance().getProperty("http.proxyHost");
static final String PROXY_PORT = PropertyUtil.getInstance().getProperty("http.proxyPort");
static final String FIX_LOGIN = PropertyUtil.getInstance().getProperty("fix-login");
static final String FIX_MEAL = PropertyUtil.getInstance().getProperty("fix-meal");
static final String FIX_CLOCKIN = PropertyUtil.getInstance().getProperty("fix-clockin");
static final String FIX_LOGOUT = PropertyUtil.getInstance().getProperty("fix-logout");
static final Boolean IS_DYNAMIC = new Boolean(PropertyUtil.getInstance().getProperty("dynamic-schedule"));
static final int RETRIES = 3;
static final int SUB_GROUP_ID = 222;
static final int REAL_DIFFERENCE = 4;
static final int LOCATION_ID = 4;
static final String HOME = URL + "user_home";
static final String LOGIN = URL + "loggin/loggin";
static final String VERIFY_SESSION = URL + "loggin/VerifySession";
static final String CHANGE_STATUS = URL + "user_home/changeStatus";
static final String END_SHIFT = URL + "user_home/endShift";
static final String VERIFY_CREDENTIALS = URL + "loggin/VerifyCredentials";
static final String GET_LOCATION = URL + "loggin/getInstance";
static final String SUB_GROUP = URL + "loggin/getSubgroup";
static final String GET_LAST_SHIFT = URL + "loggin/GetLastShift";
static final String SIGN_OUT = URL + "loggin/Logout";
static final String RECENT_ACTIVITIES = URL + "user_home/GetRecentActivities";
static final String KEY_USERNAME = "username";
static final String KEY_PASSWORD = "<PASSWORD>";
static final String KEY_WINDOWS_LOGIN = "windows_login";
static final String KEY_SUB_GROUP = "subgroup_id";
static final String KEY_STATUS_ID = "status_id";
static final String KEY_USER_IP = "user_ip";
static final String KEY_INSTANCE_ID = "instance_id";
static final String KEY_EMP_ID = "emp_id";
static final String KEY_REAL_DIFFERENCE = "realDiference";
static final String KEY_LOGIN_EMP_ID = "EmpId";
static final String JSON_SUB_GROUP_LIST = "subgroups";
}
| 3,288 | 0.748022 | 0.746196 | 101 | 31.534653 | 34.872204 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.366337 | false | false | 4 |
9a5543fbd5d36d6f564f8663fb2d64df938c087d | 36,129,264,928,578 | fa2ce8b6f2d320810a1d9d465588837705abcb32 | /app/src/main/java/com/maxkrass/appreciate/Team.java | bcbd1fad1daa1327c8d698efef59c697c7e869df | [] | no_license | maxkrass/chAPPreciate | https://github.com/maxkrass/chAPPreciate | ce04f00e128d501ac3f28d9b1c629074ce07243d | 736da9ddcf17c1247f2e07c3df066b753602efa4 | refs/heads/master | 2021-01-25T07:35:00.958000 | 2016-10-01T02:20:32 | 2016-10-01T02:20:32 | 31,043,554 | 4 | 5 | null | false | 2016-02-27T05:18:07 | 2015-02-19T23:59:18 | 2016-02-13T20:04:01 | 2016-02-24T22:27:20 | 2,216 | 4 | 5 | 2 | Java | null | null | package com.maxkrass.appreciate;
import android.support.annotation.NonNull;
//TODO replace this class's usages piece by piece with MatchRecord
public class Team implements Comparable<Team> {
public String teamNumber;
public Team(String teamNumber) {
this.teamNumber = teamNumber;
}
@Override
public int compareTo(@NonNull Team another) {
return this.teamNumber.compareTo(another.teamNumber);
}
@Override
public String toString() {
return teamNumber;
}
}
| UTF-8 | Java | 475 | java | Team.java | Java | [] | null | [] | package com.maxkrass.appreciate;
import android.support.annotation.NonNull;
//TODO replace this class's usages piece by piece with MatchRecord
public class Team implements Comparable<Team> {
public String teamNumber;
public Team(String teamNumber) {
this.teamNumber = teamNumber;
}
@Override
public int compareTo(@NonNull Team another) {
return this.teamNumber.compareTo(another.teamNumber);
}
@Override
public String toString() {
return teamNumber;
}
}
| 475 | 0.766316 | 0.766316 | 23 | 19.652174 | 20.514277 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.913043 | false | false | 4 |
12e463d50b0a672d58191776d2be17b27e25439f | 39,032,662,819,429 | 0371807684cacdbbbc85084cd28212b1470fe0f0 | /src/main/java/me/exerosis/gameengine/component/simple/NoBlockBreak.java | a12c68c153bdf128e6192bc57d19970bd441ad9b | [] | no_license | TheExerosisGaming/GameEngine2 | https://github.com/TheExerosisGaming/GameEngine2 | 17ab50069a0f4c17550886ebb7ea6ace570bcef6 | 34bd2ba134c7b6ba222d49a6952c2470f0746c29 | refs/heads/master | 2021-01-10T15:10:03.555000 | 2017-07-24T19:16:14 | 2017-07-24T19:16:14 | 54,095,435 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.exerosis.gameengine.component.simple;
import me.exerosis.gameengine.common.item.DefaultPredicate;
import me.exerosis.gameengine.common.utils.BlockUtilities;
import me.exerosis.gameengine.component.ComponentListener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.ItemStack;
import java.util.function.Predicate;
/**
* Durpped in to existence by Exerosis on 3/24/2016.
*/
public class NoBlockBreak extends ComponentListener {
private Predicate<Player> playerPredicate;
private Predicate<ItemStack> itemPredicate;
public NoBlockBreak(Predicate<Player> playerPredicate)
{
this(playerPredicate, new DefaultPredicate<>());
}
public NoBlockBreak(Predicate<Player> playerPredicate, Predicate<ItemStack> itemPredicate)
{
this.playerPredicate = playerPredicate;
this.itemPredicate = itemPredicate;
}
@EventHandler
public void onBreak(BlockBreakEvent event)
{
if (playerPredicate.test(event.getPlayer()) && itemPredicate.test(BlockUtilities.toItemStack(event.getBlock())))
event.setCancelled(true);
}
}
| UTF-8 | Java | 1,205 | java | NoBlockBreak.java | Java | [
{
"context": "tion.Predicate;\n\n/**\n * Durpped in to existence by Exerosis on 3/24/2016.\n */\npublic class NoBlockBreak exten",
"end": 466,
"score": 0.9923245310783386,
"start": 458,
"tag": "USERNAME",
"value": "Exerosis"
}
] | null | [] | package me.exerosis.gameengine.component.simple;
import me.exerosis.gameengine.common.item.DefaultPredicate;
import me.exerosis.gameengine.common.utils.BlockUtilities;
import me.exerosis.gameengine.component.ComponentListener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.ItemStack;
import java.util.function.Predicate;
/**
* Durpped in to existence by Exerosis on 3/24/2016.
*/
public class NoBlockBreak extends ComponentListener {
private Predicate<Player> playerPredicate;
private Predicate<ItemStack> itemPredicate;
public NoBlockBreak(Predicate<Player> playerPredicate)
{
this(playerPredicate, new DefaultPredicate<>());
}
public NoBlockBreak(Predicate<Player> playerPredicate, Predicate<ItemStack> itemPredicate)
{
this.playerPredicate = playerPredicate;
this.itemPredicate = itemPredicate;
}
@EventHandler
public void onBreak(BlockBreakEvent event)
{
if (playerPredicate.test(event.getPlayer()) && itemPredicate.test(BlockUtilities.toItemStack(event.getBlock())))
event.setCancelled(true);
}
}
| 1,205 | 0.755187 | 0.749378 | 40 | 29.125 | 28.899124 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.425 | false | false | 4 |
377cfd2fc3962dc0c3040fa05eaf85a5d4a6e82a | 39,264,591,029,385 | 135a8e9f342633121e119ea319c474af1a967749 | /BM-core/src/main/java/bm/main/modules/RegistrationModule.java | 70cd9783b330b5d45cbe72d4eda6a5fb2f768172 | [] | no_license | MirasCarlo934/projects | https://github.com/MirasCarlo934/projects | c66524f6b54959d428fda98ea80b1d4d3c7c7368 | c0a9d1472ed4317da6d9eea3e69b75a1c0bfbb9a | refs/heads/master | 2023-04-30T14:50:44.854000 | 2019-08-23T12:52:57 | 2019-08-23T12:52:57 | 132,343,612 | 0 | 0 | null | false | 2023-04-14T17:25:04 | 2018-05-06T13:59:34 | 2019-08-23T12:54:17 | 2023-04-14T17:25:04 | 26,055 | 0 | 0 | 4 | Java | false | false | package bm.main.modules;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import javax.xml.ws.http.HTTPException;
import org.json.JSONObject;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bm.jeep.ReqRegister;
import bm.jeep.ReqRequest;
import bm.jeep.ResError;
import bm.jeep.ResPOOP;
import bm.jeep.ResRegister;
import bm.main.Maestro;
import bm.main.ConfigLoader;
import bm.main.engines.DBEngine;
import bm.main.engines.exceptions.EngineException;
import bm.main.engines.requests.DBEngine.InsertDBEReq;
import bm.main.engines.requests.DBEngine.RawDBEReq;
import bm.main.engines.requests.DBEngine.SelectDBEReq;
import bm.main.engines.requests.DBEngine.UpdateDBEReq;
import bm.main.repositories.DeviceRepository;
import bm.main.repositories.ProductRepository;
import bm.main.repositories.RoomRepository;
import bm.mqtt.MQTTListener;
import bm.mqtt.MQTTPublisher;
import bm.smarthome.adaptors.exceptions.AdaptorException;
import bm.smarthome.devices.Device;
import bm.smarthome.devices.factories.AbstDeviceFactory;
import bm.smarthome.devices.products.AbstProduct;
import bm.smarthome.devices.products.Product;
import bm.smarthome.properties.AbstProperty;
import bm.smarthome.properties.Property;
import bm.smarthome.rooms.Room;
import bm.tools.IDGenerator;
public class RegistrationModule extends AbstModule {
private String nameParam;
private String roomIDParam;
private String propsParam;
private String poopRTY;
private ProductRepository pr;
private RoomRepository rr;
private IDGenerator idg;
public RegistrationModule(String logDomain, String errorLogDomain, String RTY, String poopRTY,
String nameParam, String roomIDParam, String propsParam, MQTTPublisher mp, DeviceRepository components,
ProductRepository pr, RoomRepository rr, IDGenerator idg) {
super(logDomain, errorLogDomain, "RegistrationModule", RTY, new String[]{nameParam, roomIDParam}, mp, components);
this.pr = pr;
this.rr = rr;
this.nameParam = nameParam;
this.roomIDParam = roomIDParam;
this.propsParam = propsParam;
this.poopRTY = poopRTY;
this.idg = idg;
}
/**
* Registers component into system.
*/
@Override
protected void process(ReqRequest request) {
ReqRegister reg = new ReqRegister(request.getJSON(), nameParam, roomIDParam, propsParam);
if(request.getJSON().has("exists")) {
if(checkCredentialChanges(reg)) {
updateComponent(reg);
} else {
returnExistingComponent(reg);
}
return;
}
mainLOG.info("Registering device " + reg.mac + " to system...");
mainLOG.debug("Creating device ID...");
String[] existingIDs = new String[dr.getAllDevices().length];
for(int i = 0; i < existingIDs.length; i++) {
existingIDs[i] = dr.getAllDevices()[i].getSSID();
}
String ssid = idg.generateCID(existingIDs);
mainLOG.debug("Creating Device object...");
String topic = ssid + "_topic";
AbstProduct product = pr.getProduct(reg.cid);
Device c = product.createDevice(ssid, reg.mac, reg.name, topic, rr.getRoom(reg.room), true);
if(reg.properties != null) {
JSONObject props = reg.properties;
Iterator<String> propIDs = props.keys();
while(propIDs.hasNext()) {
String propID = propIDs.next();
AbstProperty prop = c.getProperty(propID);
mainLOG.debug("Setting property " + propID + " (" + prop.getDisplayName() + ")");
prop.setValue(props.get(propID));
}
}
dr.addDevice(c);
mainLOG.info("Device " + c.getSSID() + " created!");
//persisting device to peripheral systems
try {
c.persist(logDomain, true);
} catch (AdaptorException e) {
error("Error in persisting device to DB! This device may not exist after "
+ "the BM restarts!", e);
return;
}
//publishing of Component credentials to default topic
mainLOG.debug("Publishing Component credentials to default topic...");
c.publishCredentials(mp, requestType, logDomain);
mainLOG.info("Registration complete!");
}
private void returnExistingComponent(ReqRegister request) {
// ReqRegister reg = new ReqRegister(request.getJSON(), nameParam, roomIDParam, propsParam);
Device c = dr.getDevice(request.mac);
mainLOG.info("Component already exists in system as " + c.getSSID() + "! "
+ "Returning existing credentials and property states.");
c.publishCredentials(mp, requestType, logDomain);
c.publishPropertyValues(mp, poopRTY, logDomain);
mainLOG.info("Activating component " + c.getSSID() + "...");
try {
c.setActive(true, logDomain, true);
mainLOG.info("Component activated!");
} catch (AdaptorException e) {
error("Cannot activate component" + c.getSSID() + "!", e);
}
}
private void updateComponent(ReqRegister request) {
Device c = dr.getDevice(request.mac);
mainLOG.info("Updating component " + c.getSSID() + " credentials...");
mainLOG.fatal(c.getProperties()[0].getStandardID());
try {
c.setName(request.name);
c.setRoom(rr.getRoom(request.room));
c.update(logDomain, true);
c.setActive(true, logDomain, true);
mainLOG.info("Component updated!");
} catch (AdaptorException e) {
error("Cannot update component " + c.getSSID() + " credentials!", e);
}
}
/**
* After confirming that the registering component already exists, another check is made to see if the registration
* request contains different credentials from persisted data. Changes signify component credential update. No
* changes signify component activation. <br><br>
*
* <b><i>NOTE:</b></i> The request parameter <i>properties</i> will not be checked here.
*
* @param request The registration request sent by the registering component
* @return <b>true</b> if the request contains changes in credentials, <b>false</b> otherwise
*/
private boolean checkCredentialChanges(ReqRegister request) {
Device c = dr.getDevice(request.mac);
String[] reqCreds = new String[]{request.name, request.room};
String[] comCreds = new String[] {c.getName(), c.getRoom().getSSID()};
for(int i = 0; i < reqCreds.length; i++) {
if(!reqCreds[i].equals(comCreds[i])) {
return true;
}
}
return false;
}
/**
* Checks for the following deficiencies in the request (done in a step-by-step manner):
* <ol>
* <li>CID already exists</li>
* <li>Invalid product ID</li>
* <li>Invalid room ID</li>
* <li>Invalid set properties block <i>(<b>Optional:</b> a register request does not have to include a set
* properties block)</i>
* <ul>
* <li>Property does not exist in the requested component product</li>
* <li>Invalid property value</li>
* </ul>
* </li>
*
* </ol>
*/
@Override
protected boolean additionalRequestChecking(ReqRequest request) {
mainLOG.trace("Additional secondary request parameter checking...");
ReqRegister reg = new ReqRegister(request.getJSON(), nameParam, roomIDParam, propsParam);
mainLOG.trace("Checking productID validity...");
if(!pr.containsProduct(reg.cid)) {
ResError error = new ResError(reg, "Request contains invalid product ID! (" + reg.cid + ")");
error(error);
return false;
}
mainLOG.trace("Checking roomID validity...");
if(!rr.containsRoom(reg.room)) {
ResError error = new ResError(reg, "Request contains invalid room ID!");
error(error);
return false;
}
mainLOG.trace("Checking set property block validity...");
AbstProduct prod = pr.getProduct(reg.cid);
if(reg.properties != null) { //it's okay if the request does not have a set properties block
JSONObject props = reg.properties;
Iterator<String> propIDs = props.keys();
while(propIDs.hasNext()) {
String propID = propIDs.next();
if(prod.containsProperty(propID)) {
if(!prod.getProperty(propID).checkValueTypeValidity(props.get(propID))) {
ResError error = new ResError(request, "Invalid property value for PID " +
propID);
error(error);
mp.publish(error);
return false;
}
} else {
ResError error = new ResError(request, "Invalid PID " + propID);
error(error);
mp.publish(error);
return false;
}
}
}
mainLOG.trace("Checking MAC validity...");
if(dr.containsComponent(reg.mac)) {
mainLOG.warn("Request contains a preexisting MAC address!");
request.getJSON().put("exists", true);
return true;
}
return true;
}
}
| UTF-8 | Java | 8,643 | java | RegistrationModule.java | Java | [] | null | [] | package bm.main.modules;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import javax.xml.ws.http.HTTPException;
import org.json.JSONObject;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bm.jeep.ReqRegister;
import bm.jeep.ReqRequest;
import bm.jeep.ResError;
import bm.jeep.ResPOOP;
import bm.jeep.ResRegister;
import bm.main.Maestro;
import bm.main.ConfigLoader;
import bm.main.engines.DBEngine;
import bm.main.engines.exceptions.EngineException;
import bm.main.engines.requests.DBEngine.InsertDBEReq;
import bm.main.engines.requests.DBEngine.RawDBEReq;
import bm.main.engines.requests.DBEngine.SelectDBEReq;
import bm.main.engines.requests.DBEngine.UpdateDBEReq;
import bm.main.repositories.DeviceRepository;
import bm.main.repositories.ProductRepository;
import bm.main.repositories.RoomRepository;
import bm.mqtt.MQTTListener;
import bm.mqtt.MQTTPublisher;
import bm.smarthome.adaptors.exceptions.AdaptorException;
import bm.smarthome.devices.Device;
import bm.smarthome.devices.factories.AbstDeviceFactory;
import bm.smarthome.devices.products.AbstProduct;
import bm.smarthome.devices.products.Product;
import bm.smarthome.properties.AbstProperty;
import bm.smarthome.properties.Property;
import bm.smarthome.rooms.Room;
import bm.tools.IDGenerator;
public class RegistrationModule extends AbstModule {
private String nameParam;
private String roomIDParam;
private String propsParam;
private String poopRTY;
private ProductRepository pr;
private RoomRepository rr;
private IDGenerator idg;
public RegistrationModule(String logDomain, String errorLogDomain, String RTY, String poopRTY,
String nameParam, String roomIDParam, String propsParam, MQTTPublisher mp, DeviceRepository components,
ProductRepository pr, RoomRepository rr, IDGenerator idg) {
super(logDomain, errorLogDomain, "RegistrationModule", RTY, new String[]{nameParam, roomIDParam}, mp, components);
this.pr = pr;
this.rr = rr;
this.nameParam = nameParam;
this.roomIDParam = roomIDParam;
this.propsParam = propsParam;
this.poopRTY = poopRTY;
this.idg = idg;
}
/**
* Registers component into system.
*/
@Override
protected void process(ReqRequest request) {
ReqRegister reg = new ReqRegister(request.getJSON(), nameParam, roomIDParam, propsParam);
if(request.getJSON().has("exists")) {
if(checkCredentialChanges(reg)) {
updateComponent(reg);
} else {
returnExistingComponent(reg);
}
return;
}
mainLOG.info("Registering device " + reg.mac + " to system...");
mainLOG.debug("Creating device ID...");
String[] existingIDs = new String[dr.getAllDevices().length];
for(int i = 0; i < existingIDs.length; i++) {
existingIDs[i] = dr.getAllDevices()[i].getSSID();
}
String ssid = idg.generateCID(existingIDs);
mainLOG.debug("Creating Device object...");
String topic = ssid + "_topic";
AbstProduct product = pr.getProduct(reg.cid);
Device c = product.createDevice(ssid, reg.mac, reg.name, topic, rr.getRoom(reg.room), true);
if(reg.properties != null) {
JSONObject props = reg.properties;
Iterator<String> propIDs = props.keys();
while(propIDs.hasNext()) {
String propID = propIDs.next();
AbstProperty prop = c.getProperty(propID);
mainLOG.debug("Setting property " + propID + " (" + prop.getDisplayName() + ")");
prop.setValue(props.get(propID));
}
}
dr.addDevice(c);
mainLOG.info("Device " + c.getSSID() + " created!");
//persisting device to peripheral systems
try {
c.persist(logDomain, true);
} catch (AdaptorException e) {
error("Error in persisting device to DB! This device may not exist after "
+ "the BM restarts!", e);
return;
}
//publishing of Component credentials to default topic
mainLOG.debug("Publishing Component credentials to default topic...");
c.publishCredentials(mp, requestType, logDomain);
mainLOG.info("Registration complete!");
}
private void returnExistingComponent(ReqRegister request) {
// ReqRegister reg = new ReqRegister(request.getJSON(), nameParam, roomIDParam, propsParam);
Device c = dr.getDevice(request.mac);
mainLOG.info("Component already exists in system as " + c.getSSID() + "! "
+ "Returning existing credentials and property states.");
c.publishCredentials(mp, requestType, logDomain);
c.publishPropertyValues(mp, poopRTY, logDomain);
mainLOG.info("Activating component " + c.getSSID() + "...");
try {
c.setActive(true, logDomain, true);
mainLOG.info("Component activated!");
} catch (AdaptorException e) {
error("Cannot activate component" + c.getSSID() + "!", e);
}
}
private void updateComponent(ReqRegister request) {
Device c = dr.getDevice(request.mac);
mainLOG.info("Updating component " + c.getSSID() + " credentials...");
mainLOG.fatal(c.getProperties()[0].getStandardID());
try {
c.setName(request.name);
c.setRoom(rr.getRoom(request.room));
c.update(logDomain, true);
c.setActive(true, logDomain, true);
mainLOG.info("Component updated!");
} catch (AdaptorException e) {
error("Cannot update component " + c.getSSID() + " credentials!", e);
}
}
/**
* After confirming that the registering component already exists, another check is made to see if the registration
* request contains different credentials from persisted data. Changes signify component credential update. No
* changes signify component activation. <br><br>
*
* <b><i>NOTE:</b></i> The request parameter <i>properties</i> will not be checked here.
*
* @param request The registration request sent by the registering component
* @return <b>true</b> if the request contains changes in credentials, <b>false</b> otherwise
*/
private boolean checkCredentialChanges(ReqRegister request) {
Device c = dr.getDevice(request.mac);
String[] reqCreds = new String[]{request.name, request.room};
String[] comCreds = new String[] {c.getName(), c.getRoom().getSSID()};
for(int i = 0; i < reqCreds.length; i++) {
if(!reqCreds[i].equals(comCreds[i])) {
return true;
}
}
return false;
}
/**
* Checks for the following deficiencies in the request (done in a step-by-step manner):
* <ol>
* <li>CID already exists</li>
* <li>Invalid product ID</li>
* <li>Invalid room ID</li>
* <li>Invalid set properties block <i>(<b>Optional:</b> a register request does not have to include a set
* properties block)</i>
* <ul>
* <li>Property does not exist in the requested component product</li>
* <li>Invalid property value</li>
* </ul>
* </li>
*
* </ol>
*/
@Override
protected boolean additionalRequestChecking(ReqRequest request) {
mainLOG.trace("Additional secondary request parameter checking...");
ReqRegister reg = new ReqRegister(request.getJSON(), nameParam, roomIDParam, propsParam);
mainLOG.trace("Checking productID validity...");
if(!pr.containsProduct(reg.cid)) {
ResError error = new ResError(reg, "Request contains invalid product ID! (" + reg.cid + ")");
error(error);
return false;
}
mainLOG.trace("Checking roomID validity...");
if(!rr.containsRoom(reg.room)) {
ResError error = new ResError(reg, "Request contains invalid room ID!");
error(error);
return false;
}
mainLOG.trace("Checking set property block validity...");
AbstProduct prod = pr.getProduct(reg.cid);
if(reg.properties != null) { //it's okay if the request does not have a set properties block
JSONObject props = reg.properties;
Iterator<String> propIDs = props.keys();
while(propIDs.hasNext()) {
String propID = propIDs.next();
if(prod.containsProperty(propID)) {
if(!prod.getProperty(propID).checkValueTypeValidity(props.get(propID))) {
ResError error = new ResError(request, "Invalid property value for PID " +
propID);
error(error);
mp.publish(error);
return false;
}
} else {
ResError error = new ResError(request, "Invalid PID " + propID);
error(error);
mp.publish(error);
return false;
}
}
}
mainLOG.trace("Checking MAC validity...");
if(dr.containsComponent(reg.mac)) {
mainLOG.warn("Request contains a preexisting MAC address!");
request.getJSON().put("exists", true);
return true;
}
return true;
}
}
| 8,643 | 0.716418 | 0.716071 | 247 | 33.991901 | 27.047865 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.668016 | false | false | 4 |
c519ee260bdf0e0447bfed0d5430c9fd94d4eb74 | 34,660,386,135,465 | 3cb6def23e4212d510a8ea8e0d297856817a9aac | /app/src/main/java/com/redefine/welike/common/LifeListener.java | d13a44b8a65f6244c38bdc1ce3bcf375beac21ef | [] | no_license | ttppt/welike | https://github.com/ttppt/welike | 5082bcd4d189e60418f7770a27b91bdac03129b1 | 5ac7433371a631a1de9d3fd2e7cd4cdd8cebe2ec | refs/heads/master | 2022-01-06T21:15:36.682000 | 2019-07-05T15:41:02 | 2019-07-05T15:41:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.redefine.welike.common;
import android.support.annotation.WorkerThread;
/**
* Created by daining on 2018/4/17.
*/
public interface LifeListener {
@WorkerThread
void onFire(@Life.LifeEvent int event);
}
| UTF-8 | Java | 228 | java | LifeListener.java | Java | [
{
"context": "upport.annotation.WorkerThread;\n\n/**\n * Created by daining on 2018/4/17.\n */\n\npublic interface LifeListener ",
"end": 111,
"score": 0.9995507597923279,
"start": 104,
"tag": "USERNAME",
"value": "daining"
}
] | null | [] | package com.redefine.welike.common;
import android.support.annotation.WorkerThread;
/**
* Created by daining on 2018/4/17.
*/
public interface LifeListener {
@WorkerThread
void onFire(@Life.LifeEvent int event);
}
| 228 | 0.732456 | 0.701754 | 13 | 16.538462 | 18.019712 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 4 |
63742fd6dd8350c5fde470ddcf5928171306631f | 36,369,783,103,370 | 22e2c703bc78b88aabd5d1bc2cef21b355f8878c | /municipal-services/ws-services/src/main/java/org/egov/waterconnection/web/models/BillingCycle.java | 634c035f0cdedef4e7949c6275278e06901cf8e1 | [
"MIT"
] | permissive | krishnaji-eGov/duplicate | https://github.com/krishnaji-eGov/duplicate | 1ad8fa306d5a1d085ecf7cde79f1626610b67632 | 2a80047f7992c53a0939a05940965b962142adbe | refs/heads/main | 2023-09-06T04:58:12.668000 | 2021-11-24T09:47:50 | 2021-11-24T09:47:50 | 431,424,473 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.egov.waterconnection.web.models;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class BillingCycle {
long fromperiod;
long toperiod;
}
| UTF-8 | Java | 282 | java | BillingCycle.java | Java | [] | null | [] | package org.egov.waterconnection.web.models;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class BillingCycle {
long fromperiod;
long toperiod;
}
| 282 | 0.812057 | 0.812057 | 18 | 14.666667 | 13.097921 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 4 |
505a42ed1f2c7125ad0e049f313480cc44df09e8 | 37,744,172,625,415 | 992ae2e5050828e59d25b58328396ee7f2a698b4 | /app/src/main/java/com/example/android/new_nds_study/adapter/LeaguerAdapter.java | c939ab009cbdef75adf50465bf2fcd943a53769d | [] | no_license | ffwc/team | https://github.com/ffwc/team | 3a8985744c9c089bbd05e7dd317ef6bfbd22ef78 | 6415fcff0d21cd273c6cd4ae9ccea0eaca2adc11 | HEAD | 2018-10-09T18:48:34.608000 | 2018-06-27T05:40:25 | 2018-06-27T05:40:25 | 137,427,139 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.new_nds_study.adapter;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.android.new_nds_study.R;
import com.example.android.new_nds_study.m_v_p.bean.UnitBean;
import com.example.android.new_nds_study.util.GlideRoundTransform;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
import okhttp3.Interceptor;
/**
* Created by dell on 2018/6/19.
*/
public class LeaguerAdapter extends RecyclerView.Adapter<LeaguerAdapter.MyLearguerHolder> {
Context context;
List<UnitBean.DataBean.ListBean> list;
public LeaguerAdapter(Context context, List<UnitBean.DataBean.ListBean> list) {
this.context = context;
this.list = list;
}
@Override
public MyLearguerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.leagueritem_layout, parent, false);
MyLearguerHolder holder = new MyLearguerHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyLearguerHolder holder, int position) {
holder.icon.setImageURI(Uri.parse(list.get(position).getAvatar()));
holder.nickNmae.setText(list.get(position).getNickname());
Glide.with(context).load(list.get(position).getAvatar())
.transform(new GlideRoundTransform(context, 60))
.into(holder.icon);
if (Integer.parseInt(list.get(position).getUid()) % 2 == 0) {
holder.connect.setImageResource(R.drawable.ic_men);
} else {
holder.connect.setImageResource(R.drawable.ic_women);
}
}
@Override
public int getItemCount() {
return list.size();
}
class MyLearguerHolder extends RecyclerView.ViewHolder {
private final SimpleDraweeView icon;
private final TextView nickNmae;
private final TextView teacher;
private final ImageView connect;
public MyLearguerHolder(View itemView) {
super(itemView);
icon = itemView.findViewById(R.id.leagueritem_icon);
nickNmae = itemView.findViewById(R.id.leaguer_nickNmae);
teacher = itemView.findViewById(R.id.leaguer_teacher);
connect = itemView.findViewById(R.id.leaguer_connect);
}
}
}
| UTF-8 | Java | 2,567 | java | LeaguerAdapter.java | Java | [
{
"context": "t;\n\nimport okhttp3.Interceptor;\n\n/**\n * Created by dell on 2018/6/19.\n */\n\npublic class LeaguerAdapter ex",
"end": 646,
"score": 0.9986223578453064,
"start": 642,
"tag": "USERNAME",
"value": "dell"
}
] | null | [] | package com.example.android.new_nds_study.adapter;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.android.new_nds_study.R;
import com.example.android.new_nds_study.m_v_p.bean.UnitBean;
import com.example.android.new_nds_study.util.GlideRoundTransform;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
import okhttp3.Interceptor;
/**
* Created by dell on 2018/6/19.
*/
public class LeaguerAdapter extends RecyclerView.Adapter<LeaguerAdapter.MyLearguerHolder> {
Context context;
List<UnitBean.DataBean.ListBean> list;
public LeaguerAdapter(Context context, List<UnitBean.DataBean.ListBean> list) {
this.context = context;
this.list = list;
}
@Override
public MyLearguerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.leagueritem_layout, parent, false);
MyLearguerHolder holder = new MyLearguerHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyLearguerHolder holder, int position) {
holder.icon.setImageURI(Uri.parse(list.get(position).getAvatar()));
holder.nickNmae.setText(list.get(position).getNickname());
Glide.with(context).load(list.get(position).getAvatar())
.transform(new GlideRoundTransform(context, 60))
.into(holder.icon);
if (Integer.parseInt(list.get(position).getUid()) % 2 == 0) {
holder.connect.setImageResource(R.drawable.ic_men);
} else {
holder.connect.setImageResource(R.drawable.ic_women);
}
}
@Override
public int getItemCount() {
return list.size();
}
class MyLearguerHolder extends RecyclerView.ViewHolder {
private final SimpleDraweeView icon;
private final TextView nickNmae;
private final TextView teacher;
private final ImageView connect;
public MyLearguerHolder(View itemView) {
super(itemView);
icon = itemView.findViewById(R.id.leagueritem_icon);
nickNmae = itemView.findViewById(R.id.leaguer_nickNmae);
teacher = itemView.findViewById(R.id.leaguer_teacher);
connect = itemView.findViewById(R.id.leaguer_connect);
}
}
}
| 2,567 | 0.698481 | 0.693416 | 76 | 32.776318 | 27.078638 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 4 |
953b5f9272c8f5def679510d9139cef84b576c95 | 35,897,336,704,120 | 968605b3f3bad78f87ffec98b1f057759af4c4f4 | /abstraction/src/abstraction/shape.java | 547686359ac6326695c380a4558b0e3c383c1474 | [] | no_license | joniyed/java_netbeans_project | https://github.com/joniyed/java_netbeans_project | 45c4a96f8fa432989ff82665d7e569e77ba4ce5c | 985b1b004e1b297262426d59800b954a8e5aa762 | refs/heads/master | 2022-03-03T19:12:15.677000 | 2019-11-21T15:45:33 | 2019-11-21T15:45:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package abstraction;
/**
*
* @author JONIYED
*/
public abstract class shape {
double x,y;
shape(double x,double y)
{
this.x=x;
this.y=y;
}
abstract void area();
}
| UTF-8 | Java | 204 | java | shape.java | Java | [
{
"context": "\npackage abstraction;\n\n/**\n *\n * @author JONIYED\n */\npublic abstract class shape {\n double x,y;",
"end": 48,
"score": 0.9966645836830139,
"start": 41,
"tag": "NAME",
"value": "JONIYED"
}
] | null | [] |
package abstraction;
/**
*
* @author JONIYED
*/
public abstract class shape {
double x,y;
shape(double x,double y)
{
this.x=x;
this.y=y;
}
abstract void area();
}
| 204 | 0.539216 | 0.539216 | 15 | 12.533334 | 9.979089 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 4 |
984fbabf7c533a47633d2c038cfa712272f1f2ff | 39,230,231,308,917 | ef1b546539004dc7f1c82b29283801737ced3057 | /module-shop/src/main/java/com/mcgrady/xproject/shop/app/AppLifecyclesImpl.java | 7ef99b1c9597d35c82b889c4493ae30b83d0eeaa | [] | no_license | mcgrady-dev/xproject-mvp | https://github.com/mcgrady-dev/xproject-mvp | d6dd30647193eccb06787b5000df8e05ac85efc7 | 141a9c0d2eda9505207e43a58be707c6baf4f911 | refs/heads/master | 2023-08-30T02:37:00.944000 | 2021-10-15T03:36:41 | 2021-10-15T03:36:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mcgrady.xproject.shop.app;
/**
* <p>类说明</p>
*
* @author: mcgrady
* @date: 2019/3/5
*/
/*public class AppLifecyclesImpl implements AppLifecycles {
@Override
public void attachBaseContext(@NonNull Context base) {
}
@Override
public void onCreate(@NonNull Application application) {
MultiDex.install(application);
if (LeakCanary.isInAnalyzerProcess(application)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
//使用 RetrofitUrlManager 切换 BaseUrl
//RetrofitUrlManager.getInstance().putDomain(ZHIHU_DOMAIN_NAME, ZHIHU_DOMAIN);
*//**
* 当所有模块集成到宿主 App 时, 在{@link com.mcgrady.common_core.app.GlobalConfig}中已经执行了以下代码
*//*
if (BuildConfig.IS_BUILD_MODULE) {
//leakCanary内存泄露检查
Utils.obtainAppComponentFromContext(application).extras()
.put(IntelligentCache.getKeyOfKeep(RefWatcher.class.getName())
, BuildConfig.USE_CANARY ? LeakCanary.install(application) : RefWatcher.DISABLED);
//启用矢量图兼容
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
}
@Override
public void onTerminate(@NonNull Application application) {
}
}*/
| UTF-8 | Java | 1,457 | java | AppLifecyclesImpl.java | Java | [
{
"context": "roject.shop.app;\n\n/**\n * <p>类说明</p>\n *\n * @author: mcgrady\n * @date: 2019/3/5\n */\n\n/*public class AppLifecyc",
"end": 80,
"score": 0.9996244311332703,
"start": 73,
"tag": "USERNAME",
"value": "mcgrady"
}
] | null | [] | package com.mcgrady.xproject.shop.app;
/**
* <p>类说明</p>
*
* @author: mcgrady
* @date: 2019/3/5
*/
/*public class AppLifecyclesImpl implements AppLifecycles {
@Override
public void attachBaseContext(@NonNull Context base) {
}
@Override
public void onCreate(@NonNull Application application) {
MultiDex.install(application);
if (LeakCanary.isInAnalyzerProcess(application)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
//使用 RetrofitUrlManager 切换 BaseUrl
//RetrofitUrlManager.getInstance().putDomain(ZHIHU_DOMAIN_NAME, ZHIHU_DOMAIN);
*//**
* 当所有模块集成到宿主 App 时, 在{@link com.mcgrady.common_core.app.GlobalConfig}中已经执行了以下代码
*//*
if (BuildConfig.IS_BUILD_MODULE) {
//leakCanary内存泄露检查
Utils.obtainAppComponentFromContext(application).extras()
.put(IntelligentCache.getKeyOfKeep(RefWatcher.class.getName())
, BuildConfig.USE_CANARY ? LeakCanary.install(application) : RefWatcher.DISABLED);
//启用矢量图兼容
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
}
@Override
public void onTerminate(@NonNull Application application) {
}
}*/
| 1,457 | 0.632192 | 0.627822 | 46 | 28.847826 | 30.367292 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.195652 | false | false | 4 |
60fa73f3de5a86e891f35368e057aaa28c90bd99 | 36,670,430,815,102 | 173729c64eb464b3ed8b776dbc16bacca03bc5c7 | /bookstore/src/main/java/com/zzti/bookstore/mapper/OrdersMapper.java | 4d89b55cea6b51875fcd1919b64cc22cee5a88ac | [] | no_license | jackjyz/jack_jyz | https://github.com/jackjyz/jack_jyz | 55885f22787ba2b13b05346935c2221a74a6d193 | aed752128e066e55cd56f41d9ff35c6bf0e8ccba | refs/heads/master | 2022-12-22T15:56:33.002000 | 2019-09-29T01:09:45 | 2019-09-29T01:09:45 | 188,751,224 | 0 | 0 | null | false | 2022-12-16T04:52:29 | 2019-05-27T01:33:42 | 2019-09-29T01:11:28 | 2022-12-16T04:52:27 | 787 | 0 | 0 | 12 | JavaScript | false | false | package com.zzti.bookstore.mapper;
import com.zzti.bookstore.pojo.OrderVo;
import com.zzti.bookstore.pojo.Orders;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
public interface OrdersMapper extends Mapper<Orders> {
/**
* 查询用户购物车内的商品
*
* @param username
* @return
*/
List<OrderVo> selectShopppingOrders(String username);
}
| UTF-8 | Java | 399 | java | OrdersMapper.java | Java | [] | null | [] | package com.zzti.bookstore.mapper;
import com.zzti.bookstore.pojo.OrderVo;
import com.zzti.bookstore.pojo.Orders;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
public interface OrdersMapper extends Mapper<Orders> {
/**
* 查询用户购物车内的商品
*
* @param username
* @return
*/
List<OrderVo> selectShopppingOrders(String username);
}
| 399 | 0.708223 | 0.708223 | 19 | 18.842106 | 18.75679 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 4 |
ed56654896db6d2fd66cbeece29a98f50ea8ba5e | 34,909,494,241,295 | 269bc44e58b7516be2999759367194f18afdd76a | /aliyun-spring-boot-starters/aliyun-rds-spring-boot-starter/src/main/java/com/alibaba/cloud/spring/boot/rds/actuate/endpoint/RdsSlowEndpoint.java | 6f3cb3f7f47b236a13fadca059618a0bd3de6e0c | [
"Apache-2.0"
] | permissive | alibaba/aliyun-spring-boot | https://github.com/alibaba/aliyun-spring-boot | d3782f53f05e3a4fb673a820510d48a38bb69da0 | 425a36d149f082919fb3c41bd042c8615b426ad9 | refs/heads/master | 2023-08-20T04:45:25.125000 | 2023-03-08T06:58:56 | 2023-03-08T06:58:56 | 247,595,825 | 436 | 122 | Apache-2.0 | false | 2023-03-08T06:58:58 | 2020-03-16T02:46:07 | 2023-02-25T06:57:43 | 2023-03-08T06:58:57 | 230 | 386 | 101 | 11 | Java | false | false | /*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.spring.boot.rds.actuate.endpoint;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstancesResponse;
import com.aliyuncs.rds.model.v20140815.DescribeSlowLogsRequest;
import com.aliyuncs.rds.model.v20140815.DescribeSlowLogsResponse;
/**
* show top 100 slow sql in rdb.
*
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
*/
@Endpoint(id = "rdsSlow100")
public class RdsSlowEndpoint extends AbstractInvoker {
private static final String TIME_PATTEN = "yyyy-MM-dd'Z'";
private static final Long TIME_RANGE = 7L * 24 * 60 * 60 * 1000;
@ReadOperation
public Map<String, List<DescribeSlowLogsResponse.SQLSlowLog>> describeSlowLogsWithInstances() {
List<DescribeDBInstancesResponse.DBInstance> instances = getInstances();
Map<String, List<DescribeSlowLogsResponse.SQLSlowLog>> map = instances.stream()
.collect(Collectors.toMap(
DescribeDBInstancesResponse.DBInstance::getDBInstanceId,
this::slow));
return map;
}
@ReadOperation
public List<DescribeSlowLogsResponse.SQLSlowLog> describeSlowLogsWithInstance(@Selector String instanceId) {
DescribeDBInstancesResponse.DBInstance instance = getInstance(instanceId);
return slow(instance);
}
@ReadOperation
public List<DescribeSlowLogsResponse.SQLSlowLog> describeSlowLogsWithInstanceAndTimeRange(@Selector String instanceId,
@Selector String start, @Selector String end) {
DescribeDBInstancesResponse.DBInstance instance = getInstance(instanceId);
return describeSlowLogs(instance, start, end);
}
private List<DescribeSlowLogsResponse.SQLSlowLog> slow(
DescribeDBInstancesResponse.DBInstance instance) {
SimpleDateFormat format = new SimpleDateFormat(TIME_PATTEN);
Date end = new Date();
Date start = new Date(end.getTime() - TIME_RANGE);
return describeSlowLogs(instance, format.format(start), format.format(end));
}
private List<DescribeSlowLogsResponse.SQLSlowLog> describeSlowLogs(
DescribeDBInstancesResponse.DBInstance instance, @Selector String start,
@Selector String end) {
DescribeSlowLogsRequest request = new DescribeSlowLogsRequest();
request.setDBInstanceId(instance.getDBInstanceId());
request.setSysRegionId(instance.getRegionId());
request.setStartTime(start);
request.setEndTime(end);
request.setPageNumber(1);
request.setPageSize(100);
DescribeSlowLogsResponse resp = invoke(request);
if (resp == null) {
return Collections.emptyList();
} else {
return resp.getItems();
}
}
}
| UTF-8 | Java | 3,820 | java | RdsSlowEndpoint.java | Java | [
{
"context": "00 slow sql in rdb.\n *\n * @author <a href=\"mailto:chenxilzx1@gmail.com\">theonefx</a>\n */\n@Endpoint(id = \"rdsSlow100\")\npu",
"end": 1358,
"score": 0.9999191761016846,
"start": 1338,
"tag": "EMAIL",
"value": "chenxilzx1@gmail.com"
},
{
"context": "\n * @author <a href=\"mailto:chenxilzx1@gmail.com\">theonefx</a>\n */\n@Endpoint(id = \"rdsSlow100\")\npublic class",
"end": 1368,
"score": 0.9995152354240417,
"start": 1360,
"tag": "USERNAME",
"value": "theonefx"
}
] | null | [] | /*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.spring.boot.rds.actuate.endpoint;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import com.aliyuncs.rds.model.v20140815.DescribeDBInstancesResponse;
import com.aliyuncs.rds.model.v20140815.DescribeSlowLogsRequest;
import com.aliyuncs.rds.model.v20140815.DescribeSlowLogsResponse;
/**
* show top 100 slow sql in rdb.
*
* @author <a href="mailto:<EMAIL>">theonefx</a>
*/
@Endpoint(id = "rdsSlow100")
public class RdsSlowEndpoint extends AbstractInvoker {
private static final String TIME_PATTEN = "yyyy-MM-dd'Z'";
private static final Long TIME_RANGE = 7L * 24 * 60 * 60 * 1000;
@ReadOperation
public Map<String, List<DescribeSlowLogsResponse.SQLSlowLog>> describeSlowLogsWithInstances() {
List<DescribeDBInstancesResponse.DBInstance> instances = getInstances();
Map<String, List<DescribeSlowLogsResponse.SQLSlowLog>> map = instances.stream()
.collect(Collectors.toMap(
DescribeDBInstancesResponse.DBInstance::getDBInstanceId,
this::slow));
return map;
}
@ReadOperation
public List<DescribeSlowLogsResponse.SQLSlowLog> describeSlowLogsWithInstance(@Selector String instanceId) {
DescribeDBInstancesResponse.DBInstance instance = getInstance(instanceId);
return slow(instance);
}
@ReadOperation
public List<DescribeSlowLogsResponse.SQLSlowLog> describeSlowLogsWithInstanceAndTimeRange(@Selector String instanceId,
@Selector String start, @Selector String end) {
DescribeDBInstancesResponse.DBInstance instance = getInstance(instanceId);
return describeSlowLogs(instance, start, end);
}
private List<DescribeSlowLogsResponse.SQLSlowLog> slow(
DescribeDBInstancesResponse.DBInstance instance) {
SimpleDateFormat format = new SimpleDateFormat(TIME_PATTEN);
Date end = new Date();
Date start = new Date(end.getTime() - TIME_RANGE);
return describeSlowLogs(instance, format.format(start), format.format(end));
}
private List<DescribeSlowLogsResponse.SQLSlowLog> describeSlowLogs(
DescribeDBInstancesResponse.DBInstance instance, @Selector String start,
@Selector String end) {
DescribeSlowLogsRequest request = new DescribeSlowLogsRequest();
request.setDBInstanceId(instance.getDBInstanceId());
request.setSysRegionId(instance.getRegionId());
request.setStartTime(start);
request.setEndTime(end);
request.setPageNumber(1);
request.setPageSize(100);
DescribeSlowLogsResponse resp = invoke(request);
if (resp == null) {
return Collections.emptyList();
} else {
return resp.getItems();
}
}
}
| 3,807 | 0.712827 | 0.697644 | 100 | 37.200001 | 32.023117 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 4 |
2cf3229b869878a71151ad685e9e302888e43ef0 | 39,453,569,614,065 | 9a70821814cc83696d84bea2f28187563c65777b | /src/main/java/me/drexhd/itsmine/claim/Claim.java | bd71f4b92a715c29bf9f2190691eb92e99a2abcb | [
"Apache-2.0"
] | permissive | DrexHD/ItsMine | https://github.com/DrexHD/ItsMine | 7ce31788cd7f81cb8f6219cb31eefbb5c4eed4be | a967d725e0b8588fcdf53e43699ee03e402dac5f | refs/heads/master | 2023-01-28T00:03:04.893000 | 2020-12-08T17:28:05 | 2020-12-08T17:28:05 | 266,211,826 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.drexhd.itsmine.claim;
import me.drexhd.itsmine.ClaimManager;
import me.drexhd.itsmine.ItsMineConfig;
import me.drexhd.itsmine.Messages;
import me.drexhd.itsmine.claim.flag.FlagManager;
import me.drexhd.itsmine.claim.permission.PermissionManager;
import me.drexhd.itsmine.util.ClaimUtil;
import me.drexhd.itsmine.util.WorldUtil;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.dimension.DimensionType;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author Indigo Amann
*/
public class Claim {
public String name;
public BlockPos min, max;
public @Nullable
BlockPos tpPos;
public DimensionType dimension;
public List<Claim> subzones = new ArrayList<>();
public FlagManager flagManager = new FlagManager();
public PermissionManager permissionManager = new PermissionManager();
public RentManager rentManager = new RentManager();
public BanManager banManager = new BanManager();
public UUID claimBlockOwner = new UUID(0, 0);
public String customOwnerName, enterMessage, leaveMessage;
public boolean isChild = false;
public Claim() {
}
public Claim(UUID uuid, CompoundTag tag) {
fromTag(uuid, tag);
}
public Claim(String name, UUID claimBlockOwner, BlockPos min, BlockPos max, DimensionType dimension) {
this(name, claimBlockOwner, min, max, dimension, null, false);
}
public Claim(String name, UUID claimBlockOwner, BlockPos min, BlockPos max, DimensionType dimension, @Nullable BlockPos tpPos, boolean isChild) {
this.claimBlockOwner = claimBlockOwner;
this.min = min;
this.max = max;
this.name = name;
this.dimension = dimension;
this.tpPos = tpPos;
this.isChild = isChild;
}
public boolean includesPosition(BlockPos pos) {
return pos.getX() >= min.getX() && pos.getY() >= min.getY() && pos.getZ() >= min.getZ() &&
pos.getX() <= max.getX() && pos.getY() <= max.getY() && pos.getZ() <= max.getZ();
}
public boolean isInside(Claim claim) {
BlockPos a = min,
b = max,
c = new BlockPos(max.getX(), min.getY(), min.getZ()),
d = new BlockPos(min.getX(), max.getY(), min.getZ()),
e = new BlockPos(min.getX(), min.getY(), max.getZ()),
f = new BlockPos(max.getX(), max.getY(), min.getZ()),
g = new BlockPos(max.getX(), min.getY(), max.getZ()),
h = new BlockPos(min.getX(), max.getY(), max.getZ());
return claim.includesPosition(a) && claim.includesPosition(b) && claim.includesPosition(c) && claim.includesPosition(d) && claim.includesPosition(e) && claim.includesPosition(f) && claim.includesPosition(g) && claim.includesPosition(h);
}
public String getName() {
String name;
if (isChild) {
String pName = ClaimUtil.getParentClaim(this).name;
name = pName + "." + this.name;
} else {
name = this.name;
}
return name;
}
public boolean intersects(Claim claim) {
return intersects(claim, false);
}
/* public int getEntities(ServerWorld world) {
AtomicReference<Integer> entities = new AtomicReference<>();
entities.set(0);
MonitorableWorld monitorableWorld = (MonitorableWorld) world;
monitorableWorld.EntityList().forEach((uuid, entity) -> {
if (includesPosition(entity.getBlockPos())) {
entities.set(entities.get() + 1);
}
});
return entities.get();
}*/
public boolean intersects(Claim claim, boolean checkforsubzone) {
if (claim == null) return false;
if (!claim.dimension.equals(dimension)) return false;
BlockPos a = min,
b = max,
c = new BlockPos(max.getX(), min.getY(), min.getZ()),
d = new BlockPos(min.getX(), max.getY(), min.getZ()),
e = new BlockPos(min.getX(), min.getY(), max.getZ()),
f = new BlockPos(max.getX(), max.getY(), min.getZ()),
g = new BlockPos(max.getX(), min.getY(), max.getZ()),
h = new BlockPos(min.getX(), max.getY(), max.getZ());
if (claim.isChild && checkforsubzone || !claim.isChild && !checkforsubzone) {
return claim.includesPosition(a) ||
claim.includesPosition(b) ||
claim.includesPosition(c) ||
claim.includesPosition(d) ||
claim.includesPosition(e) ||
claim.includesPosition(f) ||
claim.includesPosition(g) ||
claim.includesPosition(h);
//If the claim is a subzone and checking for subzone is disabled or if the claim isnt a subzone and checking is enabled, instantly return false
} else {
return false;
}
}
/**
* This method checks whether or not a player is allowed to perform the action linked to the passed permission node
*
* @param player the uuid of the player, who's permission you want to check
* @param parent the permission node (eg: break)
* @param child the child node (eg: stone)
* @return true if the player has the permission, false if the doesn't
*/
public boolean hasPermission(UUID player, String parent, @Nullable String child) {
String permission = child == null ? parent : parent + "." + child;
if (player == null) return false;
UUID tenant = this.rentManager.getTenant();
if (tenant != null && tenant.equals(player) && !parent.equalsIgnoreCase("modify")) {
return true;
}
if (claimBlockOwner != null && claimBlockOwner.equals(player)) return true;
return ClaimManager.INSTANCE.ignoringClaims.contains(player) ||
permissionManager.hasPermission(player, parent, child);
}
public boolean isPermissionDenied(UUID player, String parent, @Nullable String child) {
String permission = child == null ? parent : parent + "." + child;
if (player == null) return false;
UUID tenant = this.rentManager.getTenant();
if (tenant != null && tenant.equals(player) && !parent.equalsIgnoreCase("modify")) {
return false;
}
if (claimBlockOwner != null && claimBlockOwner.equals(player) || ClaimManager.INSTANCE.ignoringClaims.contains(player))
return false;
return permissionManager.isPermissionDenied(player, permission);
}
public boolean canModifySettings(UUID uuid) {
return hasPermission(uuid, "modify", "permissions");
}
public void addSubzone(Claim claim) {
subzones.add(claim);
}
public void removeSubzone(Claim claim) {
subzones.remove(claim);
}
public BlockPos getSize() {
return max.subtract(min);
}
public void expand(BlockPos modifier) {
if (modifier.getX() > 0) {
max = max.add(modifier.getX(), 0, 0);
} else {
min = min.add(modifier.getX(), 0, 0);
}
if (modifier.getY() > 0) {
max = max.add(0, modifier.getY(), 0);
} else {
min = min.add(0, modifier.getY(), 0);
}
if (modifier.getZ() > 0) {
max = max.add(0, 0, modifier.getZ());
} else {
min = min.add(0, 0, modifier.getZ());
}
}
public void shrink(BlockPos modifier) {
if (modifier.getX() < 0) {
min = min.add(-modifier.getX(), 0, 0);
} else {
max = max.add(-modifier.getX(), 0, 0);
}
if (modifier.getY() < 0) {
min = min.add(0, -modifier.getY(), 0);
} else {
max = max.add(0, -modifier.getY(), 0);
}
if (modifier.getZ() < 0) {
min = min.add(0, 0, -modifier.getZ());
} else {
max = max.add(0, 0, -modifier.getZ());
}
}
public boolean canShrink(BlockPos modifier) {
if (modifier.getX() < 0) {
if (min.getX() - modifier.getX() > max.getX()) return false;
} else {
if (max.getX() - modifier.getX() < min.getX()) return false;
}
if (modifier.getY() < 0) {
if (min.getY() - modifier.getY() > max.getY()) return false;
} else {
if (max.getY() - modifier.getY() < min.getY()) return false;
}
if (modifier.getZ() < 0) {
return min.getZ() - modifier.getZ() <= max.getZ();
} else {
return max.getZ() - modifier.getZ() >= min.getZ();
}
}
public void expand(Direction direction, int distance) {
expand(new BlockPos(direction.getOffsetX() * distance, direction.getOffsetY() * distance, direction.getOffsetZ() * distance));
}
public void shrink(Direction direction, int distance) {
shrink(new BlockPos(direction.getOffsetX() * distance, direction.getOffsetY() * distance, direction.getOffsetZ() * distance));
}
public int getArea() {
return getSize().getX() * (ItsMineConfig.main().claims2d ? 1 : getSize().getY()) * getSize().getZ();
}
public CompoundTag toNBT() {
CompoundTag tag = new CompoundTag();
{
CompoundTag pos = new CompoundTag();
pos.putInt("minX", min.getX());
pos.putInt("minY", min.getY());
pos.putInt("minZ", min.getZ());
pos.putInt("maxX", max.getX());
pos.putInt("maxY", max.getY());
pos.putInt("maxZ", max.getZ());
pos.putString("dimension", WorldUtil.getDimensionNameWithNameSpace(dimension));
if (tpPos != null) {
pos.putInt("tpX", this.tpPos.getX());
pos.putInt("tpY", this.tpPos.getY());
pos.putInt("tpZ", this.tpPos.getZ());
}
tag.put("position", pos);
}
{
if (!isChild) {
ListTag subzoneList = new ListTag();
subzones.forEach(it -> subzoneList.add(it.toNBT()));
tag.put("subzones", subzoneList);
}
}
{
tag.put("rent", rentManager.toTag());
}
{
tag.put("flags", flagManager.toNBT());
tag.put("permissions", permissionManager.toNBT());
tag.put("bans", banManager.toNBT());
}
{
CompoundTag meta = new CompoundTag();
if (this.enterMessage != null) meta.putString("enterMsg", this.enterMessage);
if (this.leaveMessage != null) meta.putString("leaveMsg", this.leaveMessage);
tag.put("meta", meta);
}
if (this.customOwnerName != null) tag.putString("cOwnerName", this.customOwnerName);
tag.putString("name", name);
return tag;
}
public void fromTag(UUID uuid, CompoundTag tag) {
{
CompoundTag pos = tag.getCompound("position");
int minX = pos.getInt("minX");
int minY = pos.getInt("minY");
int minZ = pos.getInt("minZ");
int maxX = pos.getInt("maxX");
int maxY = pos.getInt("maxY");
int maxZ = pos.getInt("maxZ");
if (maxY == 0) maxY = 255;
this.min = new BlockPos(minX, minY, minZ);
this.max = new BlockPos(maxX, maxY, maxZ);
if (pos.contains("tpX") && pos.contains("tpY") && pos.contains("tpZ")) {
this.tpPos = new BlockPos(pos.getInt("tpX"), pos.getInt("tpY"), pos.getInt("tpZ"));
}
this.dimension = WorldUtil.getWorldType(pos.getString("dimension")).getDimension();
}
{
if (!isChild) {
subzones = new ArrayList<>();
ListTag subzoneList = (ListTag) tag.get("subzones");
if (subzoneList != null) {
subzoneList.forEach(it -> {
Claim claim = new Claim(uuid, (CompoundTag) it);
claim.isChild = true;
subzones.add(claim);
});
}
}
}
{
CompoundTag rent = tag.getCompound("rent");
if (!(rent.getSize() == 0)) {
rentManager = new RentManager();
rentManager.fromTag(rent);
}
}
{
CompoundTag flags = tag.getCompound("flags");
flagManager = new FlagManager();
flagManager.fromNBT(flags);
CompoundTag permission = tag.getCompound("permissions");
permissionManager = new PermissionManager();
permissionManager.fromNBT(permission);
ListTag bans = tag.getList("bans", 8);
banManager = new BanManager();
banManager.fromNBT(bans);
claimBlockOwner = uuid;
}
{
CompoundTag meta = tag.getCompound("meta");
if (meta.contains("enterMsg")) this.enterMessage = meta.getString("enterMsg");
if (meta.contains("leaveMsg")) this.leaveMessage = meta.getString("leaveMsg");
}
if (tag.contains("cOwnerName")) this.customOwnerName = tag.getString("cOwnerName");
name = tag.getString("name");
}
public boolean is2d() {
return min.getY() == 0 && max.getY() == 255;
}
public enum Event {
ENTER_CLAIM("enter", ItsMineConfig.main().message().enterDefault),
LEAVE_CLAIM("leave", ItsMineConfig.main().message().leaveDefault);
public String id;
String defaultValue;
Event(String id, String defaultValue) {
this.id = id;
this.defaultValue = defaultValue;
}
@Nullable
public static Event getById(String id) {
for (Event value : values()) {
if (value.id.equalsIgnoreCase(id)) {
return value;
}
}
return null;
}
}
public enum HelpBook {
GET_STARTED("getStarted", Messages.GET_STARTED, "Get Started"),
COMMAND("commands", Messages.HELP, "Claim Commands"),
PERMS_AND_SETTINGS("perms_and_flags", Messages.SETTINGS_AND_PERMISSIONS, "Claim Permissions and Flags");
public String id;
public String title;
public Text[] texts;
HelpBook(String id, Text[] texts, String title) {
this.id = id;
this.title = title;
this.texts = texts;
}
@Nullable
public static HelpBook getById(String id) {
for (HelpBook value : values()) {
if (value.id.equalsIgnoreCase(id)) {
return value;
}
}
return null;
}
public String getCommand() {
return "/claim help " + this.id + " %page%";
}
}
}
| UTF-8 | Java | 15,199 | java | Claim.java | Java | [
{
"context": ".util.List;\nimport java.util.UUID;\n\n/**\n * @author Indigo Amann\n */\npublic class Claim {\n public String name;\n",
"end": 725,
"score": 0.9998393058776855,
"start": 713,
"tag": "NAME",
"value": "Indigo Amann"
}
] | null | [] | package me.drexhd.itsmine.claim;
import me.drexhd.itsmine.ClaimManager;
import me.drexhd.itsmine.ItsMineConfig;
import me.drexhd.itsmine.Messages;
import me.drexhd.itsmine.claim.flag.FlagManager;
import me.drexhd.itsmine.claim.permission.PermissionManager;
import me.drexhd.itsmine.util.ClaimUtil;
import me.drexhd.itsmine.util.WorldUtil;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.dimension.DimensionType;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author <NAME>
*/
public class Claim {
public String name;
public BlockPos min, max;
public @Nullable
BlockPos tpPos;
public DimensionType dimension;
public List<Claim> subzones = new ArrayList<>();
public FlagManager flagManager = new FlagManager();
public PermissionManager permissionManager = new PermissionManager();
public RentManager rentManager = new RentManager();
public BanManager banManager = new BanManager();
public UUID claimBlockOwner = new UUID(0, 0);
public String customOwnerName, enterMessage, leaveMessage;
public boolean isChild = false;
public Claim() {
}
public Claim(UUID uuid, CompoundTag tag) {
fromTag(uuid, tag);
}
public Claim(String name, UUID claimBlockOwner, BlockPos min, BlockPos max, DimensionType dimension) {
this(name, claimBlockOwner, min, max, dimension, null, false);
}
public Claim(String name, UUID claimBlockOwner, BlockPos min, BlockPos max, DimensionType dimension, @Nullable BlockPos tpPos, boolean isChild) {
this.claimBlockOwner = claimBlockOwner;
this.min = min;
this.max = max;
this.name = name;
this.dimension = dimension;
this.tpPos = tpPos;
this.isChild = isChild;
}
public boolean includesPosition(BlockPos pos) {
return pos.getX() >= min.getX() && pos.getY() >= min.getY() && pos.getZ() >= min.getZ() &&
pos.getX() <= max.getX() && pos.getY() <= max.getY() && pos.getZ() <= max.getZ();
}
public boolean isInside(Claim claim) {
BlockPos a = min,
b = max,
c = new BlockPos(max.getX(), min.getY(), min.getZ()),
d = new BlockPos(min.getX(), max.getY(), min.getZ()),
e = new BlockPos(min.getX(), min.getY(), max.getZ()),
f = new BlockPos(max.getX(), max.getY(), min.getZ()),
g = new BlockPos(max.getX(), min.getY(), max.getZ()),
h = new BlockPos(min.getX(), max.getY(), max.getZ());
return claim.includesPosition(a) && claim.includesPosition(b) && claim.includesPosition(c) && claim.includesPosition(d) && claim.includesPosition(e) && claim.includesPosition(f) && claim.includesPosition(g) && claim.includesPosition(h);
}
public String getName() {
String name;
if (isChild) {
String pName = ClaimUtil.getParentClaim(this).name;
name = pName + "." + this.name;
} else {
name = this.name;
}
return name;
}
public boolean intersects(Claim claim) {
return intersects(claim, false);
}
/* public int getEntities(ServerWorld world) {
AtomicReference<Integer> entities = new AtomicReference<>();
entities.set(0);
MonitorableWorld monitorableWorld = (MonitorableWorld) world;
monitorableWorld.EntityList().forEach((uuid, entity) -> {
if (includesPosition(entity.getBlockPos())) {
entities.set(entities.get() + 1);
}
});
return entities.get();
}*/
public boolean intersects(Claim claim, boolean checkforsubzone) {
if (claim == null) return false;
if (!claim.dimension.equals(dimension)) return false;
BlockPos a = min,
b = max,
c = new BlockPos(max.getX(), min.getY(), min.getZ()),
d = new BlockPos(min.getX(), max.getY(), min.getZ()),
e = new BlockPos(min.getX(), min.getY(), max.getZ()),
f = new BlockPos(max.getX(), max.getY(), min.getZ()),
g = new BlockPos(max.getX(), min.getY(), max.getZ()),
h = new BlockPos(min.getX(), max.getY(), max.getZ());
if (claim.isChild && checkforsubzone || !claim.isChild && !checkforsubzone) {
return claim.includesPosition(a) ||
claim.includesPosition(b) ||
claim.includesPosition(c) ||
claim.includesPosition(d) ||
claim.includesPosition(e) ||
claim.includesPosition(f) ||
claim.includesPosition(g) ||
claim.includesPosition(h);
//If the claim is a subzone and checking for subzone is disabled or if the claim isnt a subzone and checking is enabled, instantly return false
} else {
return false;
}
}
/**
* This method checks whether or not a player is allowed to perform the action linked to the passed permission node
*
* @param player the uuid of the player, who's permission you want to check
* @param parent the permission node (eg: break)
* @param child the child node (eg: stone)
* @return true if the player has the permission, false if the doesn't
*/
public boolean hasPermission(UUID player, String parent, @Nullable String child) {
String permission = child == null ? parent : parent + "." + child;
if (player == null) return false;
UUID tenant = this.rentManager.getTenant();
if (tenant != null && tenant.equals(player) && !parent.equalsIgnoreCase("modify")) {
return true;
}
if (claimBlockOwner != null && claimBlockOwner.equals(player)) return true;
return ClaimManager.INSTANCE.ignoringClaims.contains(player) ||
permissionManager.hasPermission(player, parent, child);
}
public boolean isPermissionDenied(UUID player, String parent, @Nullable String child) {
String permission = child == null ? parent : parent + "." + child;
if (player == null) return false;
UUID tenant = this.rentManager.getTenant();
if (tenant != null && tenant.equals(player) && !parent.equalsIgnoreCase("modify")) {
return false;
}
if (claimBlockOwner != null && claimBlockOwner.equals(player) || ClaimManager.INSTANCE.ignoringClaims.contains(player))
return false;
return permissionManager.isPermissionDenied(player, permission);
}
public boolean canModifySettings(UUID uuid) {
return hasPermission(uuid, "modify", "permissions");
}
public void addSubzone(Claim claim) {
subzones.add(claim);
}
public void removeSubzone(Claim claim) {
subzones.remove(claim);
}
public BlockPos getSize() {
return max.subtract(min);
}
public void expand(BlockPos modifier) {
if (modifier.getX() > 0) {
max = max.add(modifier.getX(), 0, 0);
} else {
min = min.add(modifier.getX(), 0, 0);
}
if (modifier.getY() > 0) {
max = max.add(0, modifier.getY(), 0);
} else {
min = min.add(0, modifier.getY(), 0);
}
if (modifier.getZ() > 0) {
max = max.add(0, 0, modifier.getZ());
} else {
min = min.add(0, 0, modifier.getZ());
}
}
public void shrink(BlockPos modifier) {
if (modifier.getX() < 0) {
min = min.add(-modifier.getX(), 0, 0);
} else {
max = max.add(-modifier.getX(), 0, 0);
}
if (modifier.getY() < 0) {
min = min.add(0, -modifier.getY(), 0);
} else {
max = max.add(0, -modifier.getY(), 0);
}
if (modifier.getZ() < 0) {
min = min.add(0, 0, -modifier.getZ());
} else {
max = max.add(0, 0, -modifier.getZ());
}
}
public boolean canShrink(BlockPos modifier) {
if (modifier.getX() < 0) {
if (min.getX() - modifier.getX() > max.getX()) return false;
} else {
if (max.getX() - modifier.getX() < min.getX()) return false;
}
if (modifier.getY() < 0) {
if (min.getY() - modifier.getY() > max.getY()) return false;
} else {
if (max.getY() - modifier.getY() < min.getY()) return false;
}
if (modifier.getZ() < 0) {
return min.getZ() - modifier.getZ() <= max.getZ();
} else {
return max.getZ() - modifier.getZ() >= min.getZ();
}
}
public void expand(Direction direction, int distance) {
expand(new BlockPos(direction.getOffsetX() * distance, direction.getOffsetY() * distance, direction.getOffsetZ() * distance));
}
public void shrink(Direction direction, int distance) {
shrink(new BlockPos(direction.getOffsetX() * distance, direction.getOffsetY() * distance, direction.getOffsetZ() * distance));
}
public int getArea() {
return getSize().getX() * (ItsMineConfig.main().claims2d ? 1 : getSize().getY()) * getSize().getZ();
}
public CompoundTag toNBT() {
CompoundTag tag = new CompoundTag();
{
CompoundTag pos = new CompoundTag();
pos.putInt("minX", min.getX());
pos.putInt("minY", min.getY());
pos.putInt("minZ", min.getZ());
pos.putInt("maxX", max.getX());
pos.putInt("maxY", max.getY());
pos.putInt("maxZ", max.getZ());
pos.putString("dimension", WorldUtil.getDimensionNameWithNameSpace(dimension));
if (tpPos != null) {
pos.putInt("tpX", this.tpPos.getX());
pos.putInt("tpY", this.tpPos.getY());
pos.putInt("tpZ", this.tpPos.getZ());
}
tag.put("position", pos);
}
{
if (!isChild) {
ListTag subzoneList = new ListTag();
subzones.forEach(it -> subzoneList.add(it.toNBT()));
tag.put("subzones", subzoneList);
}
}
{
tag.put("rent", rentManager.toTag());
}
{
tag.put("flags", flagManager.toNBT());
tag.put("permissions", permissionManager.toNBT());
tag.put("bans", banManager.toNBT());
}
{
CompoundTag meta = new CompoundTag();
if (this.enterMessage != null) meta.putString("enterMsg", this.enterMessage);
if (this.leaveMessage != null) meta.putString("leaveMsg", this.leaveMessage);
tag.put("meta", meta);
}
if (this.customOwnerName != null) tag.putString("cOwnerName", this.customOwnerName);
tag.putString("name", name);
return tag;
}
public void fromTag(UUID uuid, CompoundTag tag) {
{
CompoundTag pos = tag.getCompound("position");
int minX = pos.getInt("minX");
int minY = pos.getInt("minY");
int minZ = pos.getInt("minZ");
int maxX = pos.getInt("maxX");
int maxY = pos.getInt("maxY");
int maxZ = pos.getInt("maxZ");
if (maxY == 0) maxY = 255;
this.min = new BlockPos(minX, minY, minZ);
this.max = new BlockPos(maxX, maxY, maxZ);
if (pos.contains("tpX") && pos.contains("tpY") && pos.contains("tpZ")) {
this.tpPos = new BlockPos(pos.getInt("tpX"), pos.getInt("tpY"), pos.getInt("tpZ"));
}
this.dimension = WorldUtil.getWorldType(pos.getString("dimension")).getDimension();
}
{
if (!isChild) {
subzones = new ArrayList<>();
ListTag subzoneList = (ListTag) tag.get("subzones");
if (subzoneList != null) {
subzoneList.forEach(it -> {
Claim claim = new Claim(uuid, (CompoundTag) it);
claim.isChild = true;
subzones.add(claim);
});
}
}
}
{
CompoundTag rent = tag.getCompound("rent");
if (!(rent.getSize() == 0)) {
rentManager = new RentManager();
rentManager.fromTag(rent);
}
}
{
CompoundTag flags = tag.getCompound("flags");
flagManager = new FlagManager();
flagManager.fromNBT(flags);
CompoundTag permission = tag.getCompound("permissions");
permissionManager = new PermissionManager();
permissionManager.fromNBT(permission);
ListTag bans = tag.getList("bans", 8);
banManager = new BanManager();
banManager.fromNBT(bans);
claimBlockOwner = uuid;
}
{
CompoundTag meta = tag.getCompound("meta");
if (meta.contains("enterMsg")) this.enterMessage = meta.getString("enterMsg");
if (meta.contains("leaveMsg")) this.leaveMessage = meta.getString("leaveMsg");
}
if (tag.contains("cOwnerName")) this.customOwnerName = tag.getString("cOwnerName");
name = tag.getString("name");
}
public boolean is2d() {
return min.getY() == 0 && max.getY() == 255;
}
public enum Event {
ENTER_CLAIM("enter", ItsMineConfig.main().message().enterDefault),
LEAVE_CLAIM("leave", ItsMineConfig.main().message().leaveDefault);
public String id;
String defaultValue;
Event(String id, String defaultValue) {
this.id = id;
this.defaultValue = defaultValue;
}
@Nullable
public static Event getById(String id) {
for (Event value : values()) {
if (value.id.equalsIgnoreCase(id)) {
return value;
}
}
return null;
}
}
public enum HelpBook {
GET_STARTED("getStarted", Messages.GET_STARTED, "Get Started"),
COMMAND("commands", Messages.HELP, "Claim Commands"),
PERMS_AND_SETTINGS("perms_and_flags", Messages.SETTINGS_AND_PERMISSIONS, "Claim Permissions and Flags");
public String id;
public String title;
public Text[] texts;
HelpBook(String id, Text[] texts, String title) {
this.id = id;
this.title = title;
this.texts = texts;
}
@Nullable
public static HelpBook getById(String id) {
for (HelpBook value : values()) {
if (value.id.equalsIgnoreCase(id)) {
return value;
}
}
return null;
}
public String getCommand() {
return "/claim help " + this.id + " %page%";
}
}
}
| 15,193 | 0.558195 | 0.554905 | 416 | 35.536057 | 30.389517 | 244 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.831731 | false | false | 4 |
f70a3945c1173ca7b95acc9694f6b7d3a8c498ff | 10,617,159,183,952 | 2a1f1fdf25ada7a07ceed634be69bbcb76f63b2c | /studentManager/src/dao/StudentDao.java | 1f16cb4206f108287e16027d363eb4f1572c9193 | [] | no_license | sharkinxu/project | https://github.com/sharkinxu/project | 37fe71654d5548c2c015cff897d3938587c986c4 | bd717908f25af34c7bf330dc20b4cd366dea6780 | refs/heads/master | 2021-05-16T11:12:44.079000 | 2017-09-28T01:56:16 | 2017-09-28T01:56:16 | 104,960,106 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import entity.Banji;
import entity.Student;
/**
* (1)本类是从ConnectionSql类继承下来的子类 (2)Connection用来连接数据库域关闭 (3)本类主要是实现数据库中的增删改查
*
* @author lenovo
*
*/
public class StudentDao extends BaseDao {
List<Student> stus;
List<Banji> banjis;
@SuppressWarnings("finally")
public int addOne(Student stu) {
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
String photo = stu.getPhoto();
int result = 0;
String sql = "insert into student(name,sex,age,bj_id,photo) values('"
+ name + "','" + sex + "'," + age + "," + bj_id + ",'" + photo
+ "')";
try {
getStatement();
result = stat.executeUpdate(sql);
System.out.println(result);
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
/**
* (1)本方法是对数据的修改利用的是sql语句中的update
* (2)方法传入的是一个studnet,这个student的信息是由文本框输入和从文本框输入后换算的
* (3)定义四个变量用于接收有用的传入的student中的信息 (4)根据这四个变量的值拼接修改学生的sql语句
* (5)接收一个int类型的值,这个是用来返回修改成功的行数 (6)将接收的int类型的值作为返回值
*
* @param stu
* @return
*/
@SuppressWarnings("finally")
public int motify(Student stu) {
int id = stu.getId();
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
String photo = stu.getPhoto();
int result = 0;
String sql = "update student set name = '" + name + "',sex='" + sex
+ "' ,age = " + age + ",bj_id=" + bj_id + ",photo='" + photo
+ "' where id =" + id;
System.out.println(sql);
try {
getStatement();
result = stat.executeUpdate(sql);
System.out.println(result);
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
/**
* (1)本方法用于删除信息,由于删除信息只需要一个唯一索引所以只传入一个id作为删除依据 定义删除sql语句关键字是dalete
* (5)接收一个int类型的值,这个是用来返回删除成功的行数 (6)将接收的int类型的值作为返回值
*
* @param id
* @return
*/
@SuppressWarnings("finally")
public int dalete(int id) {
int result = 0;
String sql = "delete from student where id=" + id;
try {
Class.forName("com.mysql.jdbc.Driver");
// 建立链接
getStatement();
result = stat.executeUpdate(sql);
System.out.println(result);
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
/**
* (1)本方法主要是实现数据库的查找参数是sql(String)语句 (3)创建ResultSet实例,用来接受查询出的信息
* (4)将查询的信息放入到一个student,并利用while循环将student放入集合
* (5)因为在student中的一个属性是banji的类,所以我们要创建一个banji的实例化给它赋值并加入到student中完善student
* (6)完成之后返回集合,用来填入主界面的表中.
*
* @param sql
* @return
*/
// @SuppressWarnings("finally")
// public List<Student> search(String sql) {
// stus = new ArrayList<Student>();
// try {
// stat = getStatement();
// rs = stat.executeQuery(sql);
// while (rs.next()) {
// Student s = new Student();
// s.setId(rs.getInt("s.id"));
// s.setName(rs.getString("s.name"));
// s.setSex(rs.getString("s.sex"));
// s.setAge(rs.getInt("s.age"));
// // s.setClassName(rs.getString("b.name"));
// Banji bj = new Banji();
// bj.setId(rs.getInt("bj_id"));
// bj.setName(rs.getString("b.name"));
// bj.setStuNums(rs.getInt("b.stuNums"));
// s.setBj(bj);
// stus.add(s);
// }
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// closeAll(con, stat, null, rs);
// return stus;
// }
// }
// public int searchVCount() {
// List<Student> list = new ArrayList<Student>();
// int count = 0;
// try {
// Class.forName("com.mysql.jdbc.Driver");
//
// Connection con = DriverManager
// .getConnection(
// "jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
// "root", "123456");
// Statement stat = con.createStatement();
// ResultSet rs = stat
// .executeQuery("select count(*) as c from student");
// System.out.println("select count(*) from student");
// while (rs.next()) {
// count = rs.getInt("c");
// }
// rs.close();
// stat.close();
// con.close();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return count;
// }
public int searchCount(Student stu) {
List<Student> list = new ArrayList<Student>();
int count = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
"root", "123456");
Statement stat = con.createStatement();
String sql = "";
String where = " where 1=1 ";
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
if (!name.equals("")) {
where += "and name like '%" + name + "%'";
}
if (!sex.equals("")) {
where += " and sex ='" + sex + "'";
}
if (age != 0) {
where += " and age =" + age;
}
if (bj_id != 0) {
where += " and bj_id=" + bj_id;
}
sql = "select count(*) as c from student " + where;
System.out.println(sql);
ResultSet rs = stat.executeQuery(sql);
System.out.println(sql);
System.out.println("select count(*) as c from student");
while (rs.next()) {
count = rs.getInt("c");
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
// public List<Student> searchAll() {
// List<Student> list = new ArrayList<Student>();
// try {
// Class.forName("com.mysql.jdbc.Driver");
//
// Connection con = DriverManager
// .getConnection(
// "jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
// "root", "123456");
// Statement stat = con.createStatement();
// ResultSet rs = stat.executeQuery("select * from student");
// System.out.println("select * from student");
// while (rs.next()) {
// Student stu = new Student();
// stu.setId(rs.getInt("id"));
// stu.setName(rs.getString("name"));
// stu.setSex(rs.getString("sex"));
// stu.setAge(rs.getInt("age"));
// list.add(stu);
// }
// rs.close();
// stat.close();
// con.close();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return list;
// }
// public List<Student> searchPage(int number, int num) {
// List<Student> list = new ArrayList<Student>();
// try {
// Class.forName("com.mysql.jdbc.Driver");
//
// Connection con = DriverManager
// .getConnection(
// "jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
// "root", "123456");
// Statement stat = con.createStatement();
// // SELECT * FROM table LIMIT 5;
// String sql = "select * from student limit "
// + number + "," + num;
// ResultSet rs = stat.executeQuery(sql);
//
// while (rs.next()) {
// Student stu = new Student();
// stu.setId(rs.getInt("id"));
// stu.setName(rs.getString("name"));
// stu.setSex(rs.getString("sex"));
// stu.setAge(rs.getInt("age"));
// list.add(stu);
// }
// rs.close();
// stat.close();
// con.close();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return list;
// }
public List<Student> searchPageOne(int number, int num, Student stu) {
List<Student> list = new ArrayList<Student>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
"root", "123456");
Statement stat = con.createStatement();
// SELECT * FROM table LIMIT 5;
String sql = "";
String where = " where 1=1 ";
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
if (!name.equals("")) {
where += " and s.name like '%" + name + "%'";
}
if (!sex.equals("")) {
where += " and s.sex ='" + sex + "'";
}
if (age != 0) {
where += " and s.age =" + age;
}
/*
* 添加班级的判断
*/
if (bj_id != 0) {
where += " and bj_id=" + bj_id;
}
sql = "select s.*,b.name,b.stuNums ,b.id FROM student as s left join banji as b on b.id=s.bj_id "
+ where + " limit " + number + "," + num;
System.out.println(sql);
ResultSet rs = stat.executeQuery(sql);
while (rs.next()) {
Student stu1 = new Student();
stu1.setId(rs.getInt("s.id"));
stu1.setName(rs.getString("s.name"));
stu1.setSex(rs.getString("s.sex"));
stu1.setAge(rs.getInt("s.age"));
stu1.setPhoto(rs.getString("s.photo"));
Banji banji = new Banji();
banji.setId(rs.getInt("b.id"));
banji.setName(rs.getString("b.name"));
banji.setStuNums(rs.getInt("b.stuNums"));
stu1.setBj(banji);
list.add(stu1);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@SuppressWarnings({ "finally", "null" })
public Student searchByid(int id) {
Student stu1 = new Student();
String sql = "select s.*,b.id,b.name,b.stuNums FROM student as s left join banji as b on b.id=s.bj_id where s.id="
+ id;
System.out.println(sql);
try {
getStatement();
ResultSet rs = stat.executeQuery(sql);
// System.out.println( "1111111");
while (rs.next()) {
stu1.setId(rs.getInt("s.id"));
stu1.setName(rs.getString("s.name"));
stu1.setSex(rs.getString("s.sex"));
stu1.setAge(rs.getInt("s.age"));
stu1.setPhoto(rs.getString("s.photo"));
Banji banji = new Banji();
banji.setId(rs.getInt("b.id"));
banji.setName(rs.getString("b.name"));
banji.setStuNums(rs.getInt("b.stuNums"));
stu1.setBj(banji);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stu1;
}
}
}
| GB18030 | Java | 11,592 | java | StudentDao.java | Java | [
{
"context": "ction用来连接数据库域关闭 (3)本类主要是实现数据库中的增删改查\n * \n * @author lenovo\n * \n */\npublic class StudentDao extends BaseDao {",
"end": 355,
"score": 0.999481737613678,
"start": 349,
"tag": "USERNAME",
"value": "lenovo"
},
{
"context": "iverManager\n\t// .getConnection(\n\t// \"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8\",\n\t// \"root\",",
"end": 4177,
"score": 0.9935896992683411,
"start": 4168,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "306/school?characterEncoding=utf-8\",\n\t// \"root\", \"123456\");\n\t// Statement stat = con.createStatement();\n\t/",
"end": 4235,
"score": 0.9403090476989746,
"start": 4229,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "Manager\n\t\t\t\t\t.getConnection(\n\t\t\t\t\t\t\t\"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8\",\n\t\t\t\t\t\t\t\"roo",
"end": 5001,
"score": 0.9945253729820251,
"start": 4992,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "/school?characterEncoding=utf-8\",\n\t\t\t\t\t\t\t\"root\", \"123456\");\n\t\t\tStatement stat = con.createStatement();\n\t\t\t",
"end": 5062,
"score": 0.8954651951789856,
"start": 5056,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "iverManager\n\t// .getConnection(\n\t// \"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8\",\n\t// \"root\",",
"end": 6314,
"score": 0.999579131603241,
"start": 6305,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "306/school?characterEncoding=utf-8\",\n\t// \"root\", \"123456\");\n\t// Statement stat = con.createStatement();\n\t/",
"end": 6372,
"score": 0.9796896576881409,
"start": 6366,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "iverManager\n\t// .getConnection(\n\t// \"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8\",\n\t// \"root\",",
"end": 7287,
"score": 0.9963819980621338,
"start": 7278,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "306/school?characterEncoding=utf-8\",\n\t// \"root\", \"123456\");\n\t// Statement stat = con.createStatement();\n\t/",
"end": 7345,
"score": 0.9806573390960693,
"start": 7339,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "Manager\n\t\t\t\t\t.getConnection(\n\t\t\t\t\t\t\t\"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8\",\n\t\t\t\t\t\t\t\"roo",
"end": 8313,
"score": 0.9974639415740967,
"start": 8304,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "/school?characterEncoding=utf-8\",\n\t\t\t\t\t\t\t\"root\", \"123456\");\n\t\t\tStatement stat = con.createStatement();\n\t\t\t",
"end": 8374,
"score": 0.9352501034736633,
"start": 8368,
"tag": "PASSWORD",
"value": "123456"
}
] | null | [] | package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import entity.Banji;
import entity.Student;
/**
* (1)本类是从ConnectionSql类继承下来的子类 (2)Connection用来连接数据库域关闭 (3)本类主要是实现数据库中的增删改查
*
* @author lenovo
*
*/
public class StudentDao extends BaseDao {
List<Student> stus;
List<Banji> banjis;
@SuppressWarnings("finally")
public int addOne(Student stu) {
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
String photo = stu.getPhoto();
int result = 0;
String sql = "insert into student(name,sex,age,bj_id,photo) values('"
+ name + "','" + sex + "'," + age + "," + bj_id + ",'" + photo
+ "')";
try {
getStatement();
result = stat.executeUpdate(sql);
System.out.println(result);
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
/**
* (1)本方法是对数据的修改利用的是sql语句中的update
* (2)方法传入的是一个studnet,这个student的信息是由文本框输入和从文本框输入后换算的
* (3)定义四个变量用于接收有用的传入的student中的信息 (4)根据这四个变量的值拼接修改学生的sql语句
* (5)接收一个int类型的值,这个是用来返回修改成功的行数 (6)将接收的int类型的值作为返回值
*
* @param stu
* @return
*/
@SuppressWarnings("finally")
public int motify(Student stu) {
int id = stu.getId();
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
String photo = stu.getPhoto();
int result = 0;
String sql = "update student set name = '" + name + "',sex='" + sex
+ "' ,age = " + age + ",bj_id=" + bj_id + ",photo='" + photo
+ "' where id =" + id;
System.out.println(sql);
try {
getStatement();
result = stat.executeUpdate(sql);
System.out.println(result);
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
/**
* (1)本方法用于删除信息,由于删除信息只需要一个唯一索引所以只传入一个id作为删除依据 定义删除sql语句关键字是dalete
* (5)接收一个int类型的值,这个是用来返回删除成功的行数 (6)将接收的int类型的值作为返回值
*
* @param id
* @return
*/
@SuppressWarnings("finally")
public int dalete(int id) {
int result = 0;
String sql = "delete from student where id=" + id;
try {
Class.forName("com.mysql.jdbc.Driver");
// 建立链接
getStatement();
result = stat.executeUpdate(sql);
System.out.println(result);
stat.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
/**
* (1)本方法主要是实现数据库的查找参数是sql(String)语句 (3)创建ResultSet实例,用来接受查询出的信息
* (4)将查询的信息放入到一个student,并利用while循环将student放入集合
* (5)因为在student中的一个属性是banji的类,所以我们要创建一个banji的实例化给它赋值并加入到student中完善student
* (6)完成之后返回集合,用来填入主界面的表中.
*
* @param sql
* @return
*/
// @SuppressWarnings("finally")
// public List<Student> search(String sql) {
// stus = new ArrayList<Student>();
// try {
// stat = getStatement();
// rs = stat.executeQuery(sql);
// while (rs.next()) {
// Student s = new Student();
// s.setId(rs.getInt("s.id"));
// s.setName(rs.getString("s.name"));
// s.setSex(rs.getString("s.sex"));
// s.setAge(rs.getInt("s.age"));
// // s.setClassName(rs.getString("b.name"));
// Banji bj = new Banji();
// bj.setId(rs.getInt("bj_id"));
// bj.setName(rs.getString("b.name"));
// bj.setStuNums(rs.getInt("b.stuNums"));
// s.setBj(bj);
// stus.add(s);
// }
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// closeAll(con, stat, null, rs);
// return stus;
// }
// }
// public int searchVCount() {
// List<Student> list = new ArrayList<Student>();
// int count = 0;
// try {
// Class.forName("com.mysql.jdbc.Driver");
//
// Connection con = DriverManager
// .getConnection(
// "jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
// "root", "<PASSWORD>");
// Statement stat = con.createStatement();
// ResultSet rs = stat
// .executeQuery("select count(*) as c from student");
// System.out.println("select count(*) from student");
// while (rs.next()) {
// count = rs.getInt("c");
// }
// rs.close();
// stat.close();
// con.close();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return count;
// }
public int searchCount(Student stu) {
List<Student> list = new ArrayList<Student>();
int count = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
"root", "<PASSWORD>");
Statement stat = con.createStatement();
String sql = "";
String where = " where 1=1 ";
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
if (!name.equals("")) {
where += "and name like '%" + name + "%'";
}
if (!sex.equals("")) {
where += " and sex ='" + sex + "'";
}
if (age != 0) {
where += " and age =" + age;
}
if (bj_id != 0) {
where += " and bj_id=" + bj_id;
}
sql = "select count(*) as c from student " + where;
System.out.println(sql);
ResultSet rs = stat.executeQuery(sql);
System.out.println(sql);
System.out.println("select count(*) as c from student");
while (rs.next()) {
count = rs.getInt("c");
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
// public List<Student> searchAll() {
// List<Student> list = new ArrayList<Student>();
// try {
// Class.forName("com.mysql.jdbc.Driver");
//
// Connection con = DriverManager
// .getConnection(
// "jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
// "root", "<PASSWORD>");
// Statement stat = con.createStatement();
// ResultSet rs = stat.executeQuery("select * from student");
// System.out.println("select * from student");
// while (rs.next()) {
// Student stu = new Student();
// stu.setId(rs.getInt("id"));
// stu.setName(rs.getString("name"));
// stu.setSex(rs.getString("sex"));
// stu.setAge(rs.getInt("age"));
// list.add(stu);
// }
// rs.close();
// stat.close();
// con.close();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return list;
// }
// public List<Student> searchPage(int number, int num) {
// List<Student> list = new ArrayList<Student>();
// try {
// Class.forName("com.mysql.jdbc.Driver");
//
// Connection con = DriverManager
// .getConnection(
// "jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
// "root", "<PASSWORD>");
// Statement stat = con.createStatement();
// // SELECT * FROM table LIMIT 5;
// String sql = "select * from student limit "
// + number + "," + num;
// ResultSet rs = stat.executeQuery(sql);
//
// while (rs.next()) {
// Student stu = new Student();
// stu.setId(rs.getInt("id"));
// stu.setName(rs.getString("name"));
// stu.setSex(rs.getString("sex"));
// stu.setAge(rs.getInt("age"));
// list.add(stu);
// }
// rs.close();
// stat.close();
// con.close();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return list;
// }
public List<Student> searchPageOne(int number, int num, Student stu) {
List<Student> list = new ArrayList<Student>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8",
"root", "<PASSWORD>");
Statement stat = con.createStatement();
// SELECT * FROM table LIMIT 5;
String sql = "";
String where = " where 1=1 ";
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
int bj_id = stu.getBjId();
if (!name.equals("")) {
where += " and s.name like '%" + name + "%'";
}
if (!sex.equals("")) {
where += " and s.sex ='" + sex + "'";
}
if (age != 0) {
where += " and s.age =" + age;
}
/*
* 添加班级的判断
*/
if (bj_id != 0) {
where += " and bj_id=" + bj_id;
}
sql = "select s.*,b.name,b.stuNums ,b.id FROM student as s left join banji as b on b.id=s.bj_id "
+ where + " limit " + number + "," + num;
System.out.println(sql);
ResultSet rs = stat.executeQuery(sql);
while (rs.next()) {
Student stu1 = new Student();
stu1.setId(rs.getInt("s.id"));
stu1.setName(rs.getString("s.name"));
stu1.setSex(rs.getString("s.sex"));
stu1.setAge(rs.getInt("s.age"));
stu1.setPhoto(rs.getString("s.photo"));
Banji banji = new Banji();
banji.setId(rs.getInt("b.id"));
banji.setName(rs.getString("b.name"));
banji.setStuNums(rs.getInt("b.stuNums"));
stu1.setBj(banji);
list.add(stu1);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@SuppressWarnings({ "finally", "null" })
public Student searchByid(int id) {
Student stu1 = new Student();
String sql = "select s.*,b.id,b.name,b.stuNums FROM student as s left join banji as b on b.id=s.bj_id where s.id="
+ id;
System.out.println(sql);
try {
getStatement();
ResultSet rs = stat.executeQuery(sql);
// System.out.println( "1111111");
while (rs.next()) {
stu1.setId(rs.getInt("s.id"));
stu1.setName(rs.getString("s.name"));
stu1.setSex(rs.getString("s.sex"));
stu1.setAge(rs.getInt("s.age"));
stu1.setPhoto(rs.getString("s.photo"));
Banji banji = new Banji();
banji.setId(rs.getInt("b.id"));
banji.setName(rs.getString("b.name"));
banji.setStuNums(rs.getInt("b.stuNums"));
stu1.setBj(banji);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
closeAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stu1;
}
}
}
| 11,612 | 0.611316 | 0.598436 | 422 | 24.758293 | 17.567968 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.530806 | false | false | 4 |
6058e89ca6ec551d77b9f729990963d029a2b5d6 | 22,033,182,249,185 | 7d5e60126870b541716b5caf3e11665865a2872b | /DataStructures/src/main/java/com/algorithms/sorting/insertionsort/InsertionSort.java | 2da33567c34e8bfba9956d921ca2fafd579f45a8 | [] | no_license | ashesh1105/java-projects | https://github.com/ashesh1105/java-projects | 6c1838ddc69f5b7ea0d7a586ebd11cb828a1c03d | 19cc7a273db1729373fee356097f3db681ae87ca | refs/heads/master | 2022-11-26T04:55:13.995000 | 2021-02-24T21:44:04 | 2021-02-24T21:44:04 | 158,235,169 | 0 | 1 | null | false | 2022-11-16T01:57:25 | 2018-11-19T14:16:11 | 2021-02-24T21:44:15 | 2022-11-16T01:57:22 | 1,578 | 0 | 0 | 6 | Java | false | false | package com.algorithms.sorting.insertionsort;
public class InsertionSort {
public static void main(String[] args) {
int size = 10;
int[] data = new int[size];
// Populate the array
for (int i = 0; i < size; i++) {
data[i] = (int) (Math.random() * 100);
}
// Print unsorted array
System.out.print("Unsored array is: ");
for (int i = 0; i < size; i++) {
System.out.print(data[i] + " ");
}
// Sort the array using Insertion sort
for (int i = 0; i < size; i++) {
for (int j = i; j > 0; j--) {
if (data[j - 1] > data[j]) {
// swap data[j] with data [j-1]
int temp = data[j];
data[j] = data[j - 1];
data[j - 1] = temp;
}
}
}
// Print the sorted array
System.out.print("\nSored array is: ");
for (int i = 0; i < size; i++) {
System.out.print(data[i] + " ");
}
}
}
| UTF-8 | Java | 838 | java | InsertionSort.java | Java | [] | null | [] | package com.algorithms.sorting.insertionsort;
public class InsertionSort {
public static void main(String[] args) {
int size = 10;
int[] data = new int[size];
// Populate the array
for (int i = 0; i < size; i++) {
data[i] = (int) (Math.random() * 100);
}
// Print unsorted array
System.out.print("Unsored array is: ");
for (int i = 0; i < size; i++) {
System.out.print(data[i] + " ");
}
// Sort the array using Insertion sort
for (int i = 0; i < size; i++) {
for (int j = i; j > 0; j--) {
if (data[j - 1] > data[j]) {
// swap data[j] with data [j-1]
int temp = data[j];
data[j] = data[j - 1];
data[j - 1] = temp;
}
}
}
// Print the sorted array
System.out.print("\nSored array is: ");
for (int i = 0; i < size; i++) {
System.out.print(data[i] + " ");
}
}
}
| 838 | 0.5358 | 0.519093 | 36 | 22.277779 | 15.480474 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.722222 | false | false | 4 |
3eafef44989b38836e426f9de488443d767ad674 | 23,940,147,723,044 | 26b86e0921fec335c852d739bbf8d0051299f75b | /Creational/builder-design-pattern/src/main/java/com/jahnelgroup/sandwichbuilder/PrepStation.java | 0035b2bf95170f1b83c0863d4eca16380a26e8d9 | [
"MIT"
] | permissive | JahnelGroup/design-patterns | https://github.com/JahnelGroup/design-patterns | 6834876965d186a93c2f639abbee6785bf13ef5b | 2a601aded31bf758e6c9412038f7fa7e2417f944 | refs/heads/master | 2021-03-16T09:50:32.182000 | 2018-05-14T21:39:48 | 2018-05-14T21:39:48 | 117,125,241 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jahnelgroup.sandwichbuilder;
import com.jahnelgroup.sandwich.Ingredient;
import com.jahnelgroup.sandwich.Sandwich;
import java.util.ArrayList;
import java.util.List;
/*
Concrete implementation of a SandwichBuilder.
This class knows how to build a sandwich and will build one with the ingredients that are requested.
*/
public class PrepStation implements SandwichBuilder {
private Ingredient bread;
private List<Ingredient> meats = new ArrayList<>();
private List<Ingredient> vegs = new ArrayList<Ingredient>();
private List<Ingredient> conds = new ArrayList<Ingredient>();
@Override
public SandwichBuilder bread(Ingredient bread) {
this.bread = bread;
return this;
}
@Override
public SandwichBuilder meat(Ingredient meat) {
meats.add(meat);
return this;
}
@Override
public SandwichBuilder veg(Ingredient veg) {
vegs.add(veg);
return this;
}
@Override
public SandwichBuilder cond(Ingredient cond) {
conds.add(cond);
return this;
}
/*
This method will build the sandwich with all the ingredients specified by the Customer.
*/
@Override
public Sandwich build() {
Sandwich s = new Sandwich();
if(this.bread != null){
s.addLayer(this.bread);
}
for(Ingredient m : this.meats) { s.addLayer(m);}
for(Ingredient v : this.vegs) { s.addLayer(v);}
for(Ingredient c : this.conds) { s.addLayer(c);}
if(this.bread != null){
s.addLayer(this.bread);
}
return s;
}
}
| UTF-8 | Java | 1,634 | java | PrepStation.java | Java | [] | null | [] | package com.jahnelgroup.sandwichbuilder;
import com.jahnelgroup.sandwich.Ingredient;
import com.jahnelgroup.sandwich.Sandwich;
import java.util.ArrayList;
import java.util.List;
/*
Concrete implementation of a SandwichBuilder.
This class knows how to build a sandwich and will build one with the ingredients that are requested.
*/
public class PrepStation implements SandwichBuilder {
private Ingredient bread;
private List<Ingredient> meats = new ArrayList<>();
private List<Ingredient> vegs = new ArrayList<Ingredient>();
private List<Ingredient> conds = new ArrayList<Ingredient>();
@Override
public SandwichBuilder bread(Ingredient bread) {
this.bread = bread;
return this;
}
@Override
public SandwichBuilder meat(Ingredient meat) {
meats.add(meat);
return this;
}
@Override
public SandwichBuilder veg(Ingredient veg) {
vegs.add(veg);
return this;
}
@Override
public SandwichBuilder cond(Ingredient cond) {
conds.add(cond);
return this;
}
/*
This method will build the sandwich with all the ingredients specified by the Customer.
*/
@Override
public Sandwich build() {
Sandwich s = new Sandwich();
if(this.bread != null){
s.addLayer(this.bread);
}
for(Ingredient m : this.meats) { s.addLayer(m);}
for(Ingredient v : this.vegs) { s.addLayer(v);}
for(Ingredient c : this.conds) { s.addLayer(c);}
if(this.bread != null){
s.addLayer(this.bread);
}
return s;
}
}
| 1,634 | 0.637699 | 0.637699 | 62 | 25.354839 | 23.76708 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387097 | false | false | 4 |
0188e93114a77b1e674717c5a01b611fbcf85ff6 | 8,418,135,919,089 | e2783e75655bc137af2028e3a539a8657211de1f | /src/test/java/com/genericconf/bbbgateway/TestXStream.java | ee3e16da38eb158331fec56a5bb24896f8b680e7 | [] | no_license | jthomerson/bigbluebutton-gateway | https://github.com/jthomerson/bigbluebutton-gateway | c423d561b68cb85387164ec8ef06d25eaa4033ef | 9a08407afb93a0062c1f1b686362003903f600cf | refs/heads/master | 2020-05-30T18:25:52.855000 | 2010-11-18T03:03:53 | 2010-11-18T03:03:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright 2010 Generic Conferencing, LLC
*
* 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.genericconf.bbbgateway;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import com.genericconf.bbbgateway.services.ApiCallExecution;
import com.thoughtworks.xstream.XStream;
public class TestXStream {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
XStream xs = ApiCallExecution.XSTREAM;
File file = new File("/home/jrthomerson/Desktop/xml-with-attendees.xml");
file = new File("/home/jrthomerson/Desktop/xml-without-attendees.xml");
final Map<String, Object> res = (Map<String, Object>) xs.fromXML(new FileInputStream(file));
System.out.println(res);
System.out.println("list = " + res.get("attendees").getClass() + " = " + res.get("attendees"));
System.out.println("date = " + res.get("startTime").getClass() + " = " + res.get("startTime"));
System.out.println("bool = " + res.get("running").getClass() + " = " + res.get("running"));
System.out.println("int = " + res.get("moderatorCount").getClass() + " = " + res.get("moderatorCount"));
}
}
| UTF-8 | Java | 1,663 | java | TestXStream.java | Java | [
{
"context": "lExecution.XSTREAM;\n\t\tFile file = new File(\"/home/jrthomerson/Desktop/xml-with-attendees.xml\");\n\t\tfile = new Fi",
"end": 1029,
"score": 0.9982631206512451,
"start": 1018,
"tag": "USERNAME",
"value": "jrthomerson"
},
{
"context": "ml-with-attendees.xml\");\n\t\tfile = new File(\"/home/jrthomerson/Desktop/xml-without-attendees.xml\");\n\t\tfinal Map<",
"end": 1100,
"score": 0.9985051155090332,
"start": 1089,
"tag": "USERNAME",
"value": "jrthomerson"
}
] | null | [] | /**
* Copyright 2010 Generic Conferencing, LLC
*
* 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.genericconf.bbbgateway;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import com.genericconf.bbbgateway.services.ApiCallExecution;
import com.thoughtworks.xstream.XStream;
public class TestXStream {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
XStream xs = ApiCallExecution.XSTREAM;
File file = new File("/home/jrthomerson/Desktop/xml-with-attendees.xml");
file = new File("/home/jrthomerson/Desktop/xml-without-attendees.xml");
final Map<String, Object> res = (Map<String, Object>) xs.fromXML(new FileInputStream(file));
System.out.println(res);
System.out.println("list = " + res.get("attendees").getClass() + " = " + res.get("attendees"));
System.out.println("date = " + res.get("startTime").getClass() + " = " + res.get("startTime"));
System.out.println("bool = " + res.get("running").getClass() + " = " + res.get("running"));
System.out.println("int = " + res.get("moderatorCount").getClass() + " = " + res.get("moderatorCount"));
}
}
| 1,663 | 0.716176 | 0.711365 | 41 | 39.560974 | 33.522507 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.073171 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.