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
list
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
list
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
15853587ac6089370e92405f7bad4420bccdcc57
29,807,073,048,845
d0bb77a7d8a6a14649c884228ca3a344250a41c0
/State.java
ea7fcb398d6767b9dbe9438c815c3544877df133
[]
no_license
GLPconquest/datas
https://github.com/GLPconquest/datas
77a44645250801898a061dffd2a19bae22ae1a0a
20347cdc01e38c03585e19c0ca7609c09cec3440
refs/heads/master
2021-05-09T22:05:27.809000
2018-02-07T09:10:23
2018-02-07T09:10:23
118,743,265
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package datas; import Resources; public class State { public State() { super(resources money, resources food, resources oil, resources electricity); } public int spentUnit(resources money, resources food, resources oil, resources electricity) { if (/*Unit buying*/) { this.money=money-/*Unit price*/; } if (/*Unit buying*/) { this.food=food-/*Unit price*/; } if (/*Unit buying*/) { this.oil=oil-/*Unit price*/; } if (/*Unit buying*/) { this.electricity=electricité-/*Unit price*/; } } public int spentLap(resources money, resources food, resources oil, resources electricity) { this.money=money-/*Cost Unit*/; this.food=food-/*Cost Unit*/; this.oil=oil-/*Cost Unit*/; this.electricity=electricity-/*Cost Unit*/; } public int gainMoney(resources money) { switch(level.mine){ case '0': this.money=money+0; break; case '1': this.money=money+2; break; case '2': this.money=money+4; break; case '3': this.money=money+6; break; case '4': this.money=money+8; break; } } public int gainFood(resources money, resources food) { switch(level.farm){ case '0': this.money=money+0; this.food=food+0; break; case '1': this.money=money+1; this.food=food+1; break; case '2': this.money=money+2; this.food=food+2; break; case '3': this.money=money+3; this.food=food+3; break; case '4': this.money=money+4; this.food=food+4; break; } } public int gainOil(resources money, resources oil) { switch(level.oilWell){ case '0': this.money=money+0; this.oil=oil+0; break; case '1': this.money=money+1; this.oil=oil+1; break; case '2': this.money=money+2; this.oil=oil+2; break; case '3': this.money=money+3; this.oil=oil+3; break; case '4': this.money=money+4; this.oil=oil+4; break; } } public int gainElectricity(resources money, resources electricity) { switch(level.nuclearPlant){ case '0': this.money=money+0; this.electricity=electricity+0; break; case '1': this.money=money+1; this.electricity=electricity+1; break; case '2': this.money=money+2; this.electricity=electricity+2; break; case '3': this.money=money+3; this.electricity=electricity+3; break; case '4': this.money=money+4; this.electricity=electricity+4; break; } } }
WINDOWS-1250
Java
3,360
java
State.java
Java
[]
null
[]
package datas; import Resources; public class State { public State() { super(resources money, resources food, resources oil, resources electricity); } public int spentUnit(resources money, resources food, resources oil, resources electricity) { if (/*Unit buying*/) { this.money=money-/*Unit price*/; } if (/*Unit buying*/) { this.food=food-/*Unit price*/; } if (/*Unit buying*/) { this.oil=oil-/*Unit price*/; } if (/*Unit buying*/) { this.electricity=electricité-/*Unit price*/; } } public int spentLap(resources money, resources food, resources oil, resources electricity) { this.money=money-/*Cost Unit*/; this.food=food-/*Cost Unit*/; this.oil=oil-/*Cost Unit*/; this.electricity=electricity-/*Cost Unit*/; } public int gainMoney(resources money) { switch(level.mine){ case '0': this.money=money+0; break; case '1': this.money=money+2; break; case '2': this.money=money+4; break; case '3': this.money=money+6; break; case '4': this.money=money+8; break; } } public int gainFood(resources money, resources food) { switch(level.farm){ case '0': this.money=money+0; this.food=food+0; break; case '1': this.money=money+1; this.food=food+1; break; case '2': this.money=money+2; this.food=food+2; break; case '3': this.money=money+3; this.food=food+3; break; case '4': this.money=money+4; this.food=food+4; break; } } public int gainOil(resources money, resources oil) { switch(level.oilWell){ case '0': this.money=money+0; this.oil=oil+0; break; case '1': this.money=money+1; this.oil=oil+1; break; case '2': this.money=money+2; this.oil=oil+2; break; case '3': this.money=money+3; this.oil=oil+3; break; case '4': this.money=money+4; this.oil=oil+4; break; } } public int gainElectricity(resources money, resources electricity) { switch(level.nuclearPlant){ case '0': this.money=money+0; this.electricity=electricity+0; break; case '1': this.money=money+1; this.electricity=electricity+1; break; case '2': this.money=money+2; this.electricity=electricity+2; break; case '3': this.money=money+3; this.electricity=electricity+3; break; case '4': this.money=money+4; this.electricity=electricity+4; break; } } }
3,360
0.450432
0.434058
128
24.257813
16.864925
94
false
false
0
0
0
0
0
0
1.992188
false
false
15
76e114b810c073e5d2413aba2080f2291fd9111f
24,352,464,618,053
78cb86452df1ef0270de114684533c078a6f1b7d
/junior_001/src/main/java/ru/job4j/iterator/package-info.java
dbd7c3178f2fdff8ec8f370181b9d647af857e78
[ "Apache-2.0" ]
permissive
kholcold/junior-java4j
https://github.com/kholcold/junior-java4j
b799469f74836a33f39715930e2a75d18ec44c86
aab4fda5731d988d8665428f1885eeedd46bba2b
refs/heads/master
2021-09-26T18:08:05.896000
2018-11-01T09:10:59
2018-11-01T09:10:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Package for iterator task. * * @author Alexandr Kholodov (alexandr.khol@gmail.com) on 11.10.2018. * @version 1.0. * @since 0.1. */ package ru.job4j.iterator;
UTF-8
Java
170
java
package-info.java
Java
[ { "context": "/**\n * Package for iterator task.\n *\n * @author Alexandr Kholodov (alexandr.khol@gmail.com) on 11.10.2018.\n * @vers", "end": 65, "score": 0.9998887181282043, "start": 48, "tag": "NAME", "value": "Alexandr Kholodov" }, { "context": "r iterator task.\n *\n * @author Alexandr Kholodov (alexandr.khol@gmail.com) on 11.10.2018.\n * @version 1.0.\n * @since 0.1.\n ", "end": 90, "score": 0.9999332427978516, "start": 67, "tag": "EMAIL", "value": "alexandr.khol@gmail.com" } ]
null
[]
/** * Package for iterator task. * * @author <NAME> (<EMAIL>) on 11.10.2018. * @version 1.0. * @since 0.1. */ package ru.job4j.iterator;
143
0.658824
0.582353
8
20.25
20.831167
69
false
false
0
0
0
0
0
0
0.125
false
false
4
b9478ac318e8aed4a75be08a4cf0f3ef9cd019d7
24,352,464,619,269
9c4450e31bbd822c3d5af2f76ae734c85f2129da
/src/main/java/com/aurospaces/neighbourhood/dao/OrderPackageDao.java
f8fbc9b451b056f9fa99795f7dcf8173ec3613ce
[]
no_license
kotaiahandraju/School
https://github.com/kotaiahandraju/School
9f074879a353fd4fe3af0bc4514fbd687b2bbcb7
61d132f0c4ba5a806ef95db9855793adc37989bc
refs/heads/master
2021-04-29T11:42:35.653000
2018-07-19T10:17:22
2018-07-19T10:17:22
121,827,789
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aurospaces.neighbourhood.dao; import com.aurospaces.neighbourhood.bean.PathologyOrderInfoBean; public interface OrderPackageDao { boolean insertOrderPackage(PathologyOrderInfoBean objPathologyOrderInfoBean); }
UTF-8
Java
225
java
OrderPackageDao.java
Java
[]
null
[]
package com.aurospaces.neighbourhood.dao; import com.aurospaces.neighbourhood.bean.PathologyOrderInfoBean; public interface OrderPackageDao { boolean insertOrderPackage(PathologyOrderInfoBean objPathologyOrderInfoBean); }
225
0.871111
0.871111
7
31.142857
29.830132
78
false
false
0
0
0
0
0
0
0.571429
false
false
4
044415e30f7be07fdcf5fd214baf145686e006c1
10,788,957,899,622
05e454259b44882a1bfff0ba82475374b36b74f0
/client/src/taco/agent/model/worldmodel/odometry/Odometry.java
1aaa894fcde770677e9c22db28fab64c6e063924
[ "BSD-3-Clause" ]
permissive
TeamAutonomousCarOffenburg/TACO_2017
https://github.com/TeamAutonomousCarOffenburg/TACO_2017
ec49f539528388f28114cca9787c1ab7db880e64
724c37188209818c22046d2229f67d882c36e2f4
refs/heads/master
2021-08-14T18:33:24.203000
2017-11-16T13:48:57
2017-11-16T13:48:57
110,350,009
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package taco.agent.model.worldmodel.odometry; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import hso.autonomy.util.geometry.IPose2D; import hso.autonomy.util.geometry.Pose2D; /** * Base class for all odometry classes that are able to keep track of our pose. */ public class Odometry { /** the current pose estimation */ protected IPose2D pose; /** the start pose to start with */ protected IPose2D startPose; public Odometry(IPose2D startPose) { this.startPose = startPose; pose = startPose; } public IPose2D getPose() { return pose; } public void init() { pose = startPose; } public void setPose(IPose2D pose) { this.pose = pose; } public void setPosition(Vector2D position) { this.pose = new Pose2D(position, pose.getAngle()); } }
UTF-8
Java
797
java
Odometry.java
Java
[]
null
[]
package taco.agent.model.worldmodel.odometry; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import hso.autonomy.util.geometry.IPose2D; import hso.autonomy.util.geometry.Pose2D; /** * Base class for all odometry classes that are able to keep track of our pose. */ public class Odometry { /** the current pose estimation */ protected IPose2D pose; /** the start pose to start with */ protected IPose2D startPose; public Odometry(IPose2D startPose) { this.startPose = startPose; pose = startPose; } public IPose2D getPose() { return pose; } public void init() { pose = startPose; } public void setPose(IPose2D pose) { this.pose = pose; } public void setPosition(Vector2D position) { this.pose = new Pose2D(position, pose.getAngle()); } }
797
0.720201
0.706399
44
17.113636
19.959295
79
false
false
0
0
0
0
0
0
1
false
false
4
1ba5506261edef0f703617314fd8f49ac3078e92
20,409,684,629,892
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/15/15_8e8838c14dd25a16f2c73fd8506396d8e5866f7e/ErgebnisKombination/15_8e8838c14dd25a16f2c73fd8506396d8e5866f7e_ErgebnisKombination_s.java
8344d534c2dc861e0aabee437615b72f40b7d413
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/** * */ package org.hitzemann.mms.model; /** * @author simon * */ public class ErgebnisKombination implements Comparable<ErgebnisKombination> { /** * Anzahl der korrekten Steine. */ private final int schwarz; /** * Anzahl der Steine mit korrekten Farben und falschen Positionen. */ private final int weiss; /** * Konstruktor für ein ErgebnisKombination Objekt. * * @param paramSchwarz * Anzahl der korrekten Steine * @param paramWeiss * Anzahl der Steine mit korrekten Farben und falschen Positionen */ public ErgebnisKombination(final int paramSchwarz, final int paramWeiss) { this.schwarz = paramSchwarz; this.weiss = paramWeiss; } /** * Standard Getter für Attribut schwarz. * * @return Anzahl der korrekten Steine. */ public final int getSchwarz() { return schwarz; } /** * Standard Geter für Attribut weiss. * * @return Anzahl der Steine mit korrekten Farben und falschen Positionen. */ public final int getWeiss() { return weiss; } @Override public final int hashCode() { final int prime = 31; int result = 1; result = prime * result + schwarz; result = prime * result + weiss; return result; } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ErgebnisKombination other = (ErgebnisKombination) obj; if (schwarz != other.schwarz) { return false; } if (weiss != other.weiss) { return false; } return true; } @Override public final String toString() { return "ErgebnisKombination [schwarz=" + schwarz + ", weiss=" + weiss + "]"; } @Override public final int compareTo(final ErgebnisKombination o) { return (this.getSchwarz() * 10 + this.getWeiss()) - (o.getSchwarz() * 10 + o.getWeiss()); } }
UTF-8
Java
2,006
java
15_8e8838c14dd25a16f2c73fd8506396d8e5866f7e_ErgebnisKombination_s.java
Java
[ { "context": "ackage org.hitzemann.mms.model;\n \n /**\n * @author simon\n * \n */\n public class ErgebnisKombination imple", "end": 73, "score": 0.9373078942298889, "start": 68, "tag": "USERNAME", "value": "simon" } ]
null
[]
/** * */ package org.hitzemann.mms.model; /** * @author simon * */ public class ErgebnisKombination implements Comparable<ErgebnisKombination> { /** * Anzahl der korrekten Steine. */ private final int schwarz; /** * Anzahl der Steine mit korrekten Farben und falschen Positionen. */ private final int weiss; /** * Konstruktor für ein ErgebnisKombination Objekt. * * @param paramSchwarz * Anzahl der korrekten Steine * @param paramWeiss * Anzahl der Steine mit korrekten Farben und falschen Positionen */ public ErgebnisKombination(final int paramSchwarz, final int paramWeiss) { this.schwarz = paramSchwarz; this.weiss = paramWeiss; } /** * Standard Getter für Attribut schwarz. * * @return Anzahl der korrekten Steine. */ public final int getSchwarz() { return schwarz; } /** * Standard Geter für Attribut weiss. * * @return Anzahl der Steine mit korrekten Farben und falschen Positionen. */ public final int getWeiss() { return weiss; } @Override public final int hashCode() { final int prime = 31; int result = 1; result = prime * result + schwarz; result = prime * result + weiss; return result; } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ErgebnisKombination other = (ErgebnisKombination) obj; if (schwarz != other.schwarz) { return false; } if (weiss != other.weiss) { return false; } return true; } @Override public final String toString() { return "ErgebnisKombination [schwarz=" + schwarz + ", weiss=" + weiss + "]"; } @Override public final int compareTo(final ErgebnisKombination o) { return (this.getSchwarz() * 10 + this.getWeiss()) - (o.getSchwarz() * 10 + o.getWeiss()); } }
2,006
0.624064
0.620569
96
19.854166
20.894566
78
false
false
0
0
0
0
0
0
1.427083
false
false
4
6b19d5b2ad07fbca98917b04c1bf7d7522b07f8a
29,240,137,404,924
7e4c6b59024ec85ad74292c72662cfa3a1eeef8a
/src/main/java/uk/ac/ebi/ddi/service/db/service/dataset/IDatasetSimilarsService.java
0f137b927c7e6703900dbafca147e2d009e798d7
[ "Apache-2.0" ]
permissive
OmicsDI/ddi-service-db
https://github.com/OmicsDI/ddi-service-db
af8e6ff31e034c294b1244dfc6765088fa5247da
6eb8670d1173e997e02c29ffe556f9b75ff1a188
refs/heads/master
2022-12-10T01:28:32.307000
2021-07-06T11:38:31
2021-07-06T11:38:31
34,675,976
0
1
Apache-2.0
false
2022-11-16T02:53:27
2015-04-27T15:51:58
2021-07-06T11:38:39
2022-11-16T02:53:26
535
0
2
3
Java
false
false
package uk.ac.ebi.ddi.service.db.service.dataset; import org.bson.types.ObjectId; import org.springframework.data.domain.Page; import uk.ac.ebi.ddi.service.db.model.dataset.Dataset; import uk.ac.ebi.ddi.service.db.model.dataset.DatasetShort; import uk.ac.ebi.ddi.service.db.model.dataset.DatasetSimilars; import java.util.List; /** * Created by yperez on 13/06/2016. */ public interface IDatasetSimilarsService { /** * Create a new DatasetAccess in the MongoDB * @param dataset The new datset access to be save in the database * @return the inserted dataset */ DatasetSimilars save(DatasetSimilars dataset); /** * Read a datasetAccess entry from the database * @param id of the datasetaccess entry * @return A DatasetAccess */ DatasetSimilars read(ObjectId id); /** * Read all the datasetAccess from the database * @return A list of datasetAccess */ Page<DatasetSimilars> readAll(int pageStart, int size); /** * Update a datasetAccess entry in the database using the information of the new datasetAccess * @param dataset the new datasetSimilars information * @return the updated datasetAccess. */ DatasetSimilars update(ObjectId id, DatasetSimilars dataset); /** * Remove a Dataset in the Database using the id. * @param id Identifier of the datasetAccess to be removed from the database * @return the removed datatsetAccess */ void delete(DatasetSimilars dataset); /** * Read a DatasetAccess from the database using the accession and the database * @param acc Accession of the DatasetAccess * @param database Database of the DatasetAceess * @return Return the entry for the dataset */ DatasetSimilars read(String acc, String database); /** * Find all datasets by an specific accession * @param accession * @return * * * List<DatasetSimilars> findByAccession(String accession); */ List<DatasetSimilars> readAll(); void addDatasetSimilars(Dataset dataset, List<DatasetShort> similars, String relationtype); void addDatasetSim(Dataset dataset, List<DatasetShort> similars, String relationtype); }
UTF-8
Java
2,231
java
IDatasetSimilarsService.java
Java
[ { "context": "milars;\n\nimport java.util.List;\n\n/**\n * Created by yperez on 13/06/2016.\n */\npublic interface IDatasetSimil", "end": 355, "score": 0.9996841549873352, "start": 349, "tag": "USERNAME", "value": "yperez" } ]
null
[]
package uk.ac.ebi.ddi.service.db.service.dataset; import org.bson.types.ObjectId; import org.springframework.data.domain.Page; import uk.ac.ebi.ddi.service.db.model.dataset.Dataset; import uk.ac.ebi.ddi.service.db.model.dataset.DatasetShort; import uk.ac.ebi.ddi.service.db.model.dataset.DatasetSimilars; import java.util.List; /** * Created by yperez on 13/06/2016. */ public interface IDatasetSimilarsService { /** * Create a new DatasetAccess in the MongoDB * @param dataset The new datset access to be save in the database * @return the inserted dataset */ DatasetSimilars save(DatasetSimilars dataset); /** * Read a datasetAccess entry from the database * @param id of the datasetaccess entry * @return A DatasetAccess */ DatasetSimilars read(ObjectId id); /** * Read all the datasetAccess from the database * @return A list of datasetAccess */ Page<DatasetSimilars> readAll(int pageStart, int size); /** * Update a datasetAccess entry in the database using the information of the new datasetAccess * @param dataset the new datasetSimilars information * @return the updated datasetAccess. */ DatasetSimilars update(ObjectId id, DatasetSimilars dataset); /** * Remove a Dataset in the Database using the id. * @param id Identifier of the datasetAccess to be removed from the database * @return the removed datatsetAccess */ void delete(DatasetSimilars dataset); /** * Read a DatasetAccess from the database using the accession and the database * @param acc Accession of the DatasetAccess * @param database Database of the DatasetAceess * @return Return the entry for the dataset */ DatasetSimilars read(String acc, String database); /** * Find all datasets by an specific accession * @param accession * @return * * * List<DatasetSimilars> findByAccession(String accession); */ List<DatasetSimilars> readAll(); void addDatasetSimilars(Dataset dataset, List<DatasetShort> similars, String relationtype); void addDatasetSim(Dataset dataset, List<DatasetShort> similars, String relationtype); }
2,231
0.701927
0.698342
73
29.561644
27.461548
98
false
false
0
0
0
0
0
0
0.328767
false
false
4
dcb3880ed11bd22473b6b1152aefcfafece2dd1e
7,602,092,178,909
298eafce75c9b2f2b7ef82ee64a258844ef4fbb9
/src/main/java/com/codegym/music/service/impl/SongServiceImpl.java
3e6b51f76bd0e93b897fd77da49639be2bd1ca96
[]
no_license
anhnbt/zingmp3
https://github.com/anhnbt/zingmp3
0f1e69c2ea6860778e402a64e9848c9b1a064a75
63103990ad7d61125eaf975c35ea53e15c257ea1
refs/heads/master
2023-05-31T11:09:06.860000
2021-06-15T09:29:29
2021-06-15T09:29:29
328,293,554
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codegym.music.service.impl; import com.codegym.music.model.Album; import com.codegym.music.model.Category; import com.codegym.music.model.Singer; import com.codegym.music.model.Song; import com.codegym.music.repository.SongRepository; import com.codegym.music.service.SongService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class SongServiceImpl implements SongService { @Autowired private SongRepository songRepository; @Override public Page<Song> findAll(Integer pageNo, Integer pageSize, String sortBy) { Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(Sort.Direction.ASC, sortBy)); return songRepository.findAll(paging); } @Override public Page<Song> findAllByNameContains(String name, Integer pageNo, Integer pageSize, String sortBy) { Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(Sort.Direction.ASC, sortBy)); return songRepository.findAllByNameContains(name, paging); } @Override public Page<Song> findAll(Pageable pageable) { return songRepository.findAll(pageable); } @Override public Iterable<Song> findAll() { return songRepository.findAll(); } @Override public Optional<Song> findById(Long id) { return songRepository.findById(id); } @Override public Song save(Song song) { return songRepository.save(song); } @Override public void deleteById(Long id) { songRepository.deleteById(id); } @Override public long count() { return songRepository.count(); } @Override public Iterable<Song> findAllBySingerId(Long id) { return songRepository.findAllBySingerId(id); } @Override public Iterable<Song> findAllBy5BySingerId(Long singer_id, Long id) { return songRepository.findFirst5BySingerIdAndIdNot(singer_id, id); } @Override public Iterable<Song> findAllByAlbums(Album album) { return songRepository.findAllByAlbums(album); } @Override public Page<Song> findAllByAlbums(Album album, Pageable pageable) { return songRepository.findAllByAlbums(album, pageable); } @Override public Page<Song> findAllByNameContainsOrAlbumsContainsSingerNameContains(String name, Album album, String singer, Pageable pageable) { return songRepository.findAllByNameContainsOrAlbumsContainsOrSingerContains(name, album, singer, pageable); } @Override public Page<Song> findAllByStatusTrue(Pageable pageable) { return songRepository.findAllByStatusTrue(pageable); } @Override public Page<Song> findAllByNameContainsOrAlbumsContains(String name, Album album, Pageable pageable) { return songRepository.findAllByNameContainsOrAlbumsContains(name, album, pageable); } @Override public Page<Song> findAllByNameContainsOrSingerNameContains(String name, String singer, Pageable pageable) { return songRepository.findAllByNameContainsOrSingerNameContains(name, singer, pageable); } @Override public Page<Song> findAllByNameContains(String name, Pageable pageable) { return songRepository.findAllByNameContains(name, pageable); } @Override public Optional<Song> findByNameContains(String name) { return songRepository.findByNameContains(name); } }
UTF-8
Java
3,668
java
SongServiceImpl.java
Java
[]
null
[]
package com.codegym.music.service.impl; import com.codegym.music.model.Album; import com.codegym.music.model.Category; import com.codegym.music.model.Singer; import com.codegym.music.model.Song; import com.codegym.music.repository.SongRepository; import com.codegym.music.service.SongService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class SongServiceImpl implements SongService { @Autowired private SongRepository songRepository; @Override public Page<Song> findAll(Integer pageNo, Integer pageSize, String sortBy) { Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(Sort.Direction.ASC, sortBy)); return songRepository.findAll(paging); } @Override public Page<Song> findAllByNameContains(String name, Integer pageNo, Integer pageSize, String sortBy) { Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(Sort.Direction.ASC, sortBy)); return songRepository.findAllByNameContains(name, paging); } @Override public Page<Song> findAll(Pageable pageable) { return songRepository.findAll(pageable); } @Override public Iterable<Song> findAll() { return songRepository.findAll(); } @Override public Optional<Song> findById(Long id) { return songRepository.findById(id); } @Override public Song save(Song song) { return songRepository.save(song); } @Override public void deleteById(Long id) { songRepository.deleteById(id); } @Override public long count() { return songRepository.count(); } @Override public Iterable<Song> findAllBySingerId(Long id) { return songRepository.findAllBySingerId(id); } @Override public Iterable<Song> findAllBy5BySingerId(Long singer_id, Long id) { return songRepository.findFirst5BySingerIdAndIdNot(singer_id, id); } @Override public Iterable<Song> findAllByAlbums(Album album) { return songRepository.findAllByAlbums(album); } @Override public Page<Song> findAllByAlbums(Album album, Pageable pageable) { return songRepository.findAllByAlbums(album, pageable); } @Override public Page<Song> findAllByNameContainsOrAlbumsContainsSingerNameContains(String name, Album album, String singer, Pageable pageable) { return songRepository.findAllByNameContainsOrAlbumsContainsOrSingerContains(name, album, singer, pageable); } @Override public Page<Song> findAllByStatusTrue(Pageable pageable) { return songRepository.findAllByStatusTrue(pageable); } @Override public Page<Song> findAllByNameContainsOrAlbumsContains(String name, Album album, Pageable pageable) { return songRepository.findAllByNameContainsOrAlbumsContains(name, album, pageable); } @Override public Page<Song> findAllByNameContainsOrSingerNameContains(String name, String singer, Pageable pageable) { return songRepository.findAllByNameContainsOrSingerNameContains(name, singer, pageable); } @Override public Page<Song> findAllByNameContains(String name, Pageable pageable) { return songRepository.findAllByNameContains(name, pageable); } @Override public Optional<Song> findByNameContains(String name) { return songRepository.findByNameContains(name); } }
3,668
0.732552
0.732007
117
30.350428
31.969355
139
false
false
0
0
0
0
0
0
0.57265
false
false
4
b72712611a42974060c10859bb937bcaf3e5f250
33,268,816,711,324
8751cb22764de6c353813aa6ec0bb21f59e0ea4c
/JavaProject/src/qsp1/CollectionjapaProgram.java
d98b8154b467da9f5353c0de069d4a83e2888aaf
[]
no_license
rky1991/JavaProject
https://github.com/rky1991/JavaProject
a68aac94021baedbcdb11e3088edb809d99871d8
30f440880d0517bb7a8f4dde1477df9750a087fe
refs/heads/master
2020-04-14T17:56:02.497000
2019-01-10T08:53:49
2019-01-10T08:53:49
163,999,775
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package qsp1; import java.util.LinkedHashMap; public class CollectionjapaProgram { public static void main(String[] args) { // TODO Auto-generated method stub LinkedHashMap<String,Integer>map=new LinkedHashMap<String,Integer>(); map.put("Projecter",1); map.put("chair",10); map.put("Table",11); System.out.println(map); } }
UTF-8
Java
366
java
CollectionjapaProgram.java
Java
[]
null
[]
package qsp1; import java.util.LinkedHashMap; public class CollectionjapaProgram { public static void main(String[] args) { // TODO Auto-generated method stub LinkedHashMap<String,Integer>map=new LinkedHashMap<String,Integer>(); map.put("Projecter",1); map.put("chair",10); map.put("Table",11); System.out.println(map); } }
366
0.672131
0.655738
18
18.222221
19.357903
71
false
false
0
0
0
0
0
0
1.555556
false
false
4
5d2e8f636f084039eaa7ffb71b3300cb318d3ca7
25,666,724,590,169
8f409af3a64e89ccd32b49b64a5b1e6913e87241
/sdk/src/main/java/com/qcloud/cmq/client/cloudapi/CloudApiQueueClient.java
e650de8ae90ecbf31ef23039a009476670d44bc8
[]
no_license
tencentyun/cmq-java-tcp-sdk
https://github.com/tencentyun/cmq-java-tcp-sdk
122c6dea1e52122279c8ee4a10be5de3aaa5bbc4
07ab03c10e056e0b904eef6b6ca642b82bb640d7
refs/heads/master
2023-08-31T12:37:43.957000
2022-07-15T06:20:29
2022-07-15T06:20:29
171,469,265
22
20
null
false
2022-10-04T23:48:33
2019-02-19T12:24:21
2022-07-15T06:20:08
2022-10-04T23:48:30
390
16
15
7
Java
false
false
package com.qcloud.cmq.client.cloudapi; import com.qcloud.cmq.client.cloudapi.entity.CmqQueue; import java.util.List; /** * @author: feynmanlin * @date: 2020/1/14 7:25 下午 */ public interface CloudApiQueueClient { String createQueue(String queueName, QueueMeta meta); int countQueue(String searchWord, int offset, int limit); List<CmqQueue> describeQueue(String searchWord, int offset, int limit); void deleteQueue(String queueName); QueueMeta getQueueAttributes(String queueName); }
UTF-8
Java
518
java
CloudApiQueueClient.java
Java
[ { "context": "CmqQueue;\n\nimport java.util.List;\n\n/**\n * @author: feynmanlin\n * @date: 2020/1/14 7:25 下午\n */\npublic interface ", "end": 147, "score": 0.9996585845947266, "start": 137, "tag": "USERNAME", "value": "feynmanlin" } ]
null
[]
package com.qcloud.cmq.client.cloudapi; import com.qcloud.cmq.client.cloudapi.entity.CmqQueue; import java.util.List; /** * @author: feynmanlin * @date: 2020/1/14 7:25 下午 */ public interface CloudApiQueueClient { String createQueue(String queueName, QueueMeta meta); int countQueue(String searchWord, int offset, int limit); List<CmqQueue> describeQueue(String searchWord, int offset, int limit); void deleteQueue(String queueName); QueueMeta getQueueAttributes(String queueName); }
518
0.747082
0.727626
22
22.363636
24.597755
75
false
false
0
0
0
0
0
0
0.590909
false
false
4
6fd6035ab9cc6e6d17e32091187cd2117715b008
6,382,321,436,760
7df6a2c81f0682c43b83e33c4f6808fba1a57311
/spring-data-cassandra/src/main/java/org/springframework/data/cassandra/observability/ObservationStatement.java
a68d5aad0eb7b870001d2116356d34595cec1544
[ "Apache-2.0" ]
permissive
spring-projects/spring-data-cassandra
https://github.com/spring-projects/spring-data-cassandra
0f322956672fe0708fbcbeaa96abd632784c376b
746541447cb1d2a308bde2b12d65e937693a2f10
refs/heads/main
2023-08-31T03:26:47.928000
2023-08-29T11:36:24
2023-08-30T12:10:49
2,183,665
331
332
Apache-2.0
false
2023-07-12T07:24:45
2011-08-10T06:16:44
2023-06-25T02:11:37
2023-07-11T13:30:02
15,973
356
306
37
Java
false
false
/* * Copyright 2022-2023 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 org.springframework.data.cassandra.observability; import io.micrometer.observation.Observation; import java.lang.reflect.Method; import javax.annotation.Nonnull; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ProxyFactory; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; import com.datastax.oss.driver.api.core.cql.Statement; /** * Trace implementation of a {@link Statement}. * * @author Mark Paluch * @author Marcin Grzejszczak * @since 4.0 */ final class ObservationStatement implements MethodInterceptor { private final Observation observation; private Statement<?> delegate; private ObservationStatement(Observation observation, Statement<?> delegate) { this.observation = observation; this.delegate = delegate; } /** * Creates a proxy with {@link ObservationStatement} attached to it. * * @param observation current observation * @param target target to proxy * @param <T> type of target * @return proxied object with trace advice */ @SuppressWarnings("unchecked") public static <T> T createProxy(Observation observation, T target) { ProxyFactory factory = new ProxyFactory(ClassUtils.getAllInterfaces(target)); factory.addInterface(CassandraObservationSupplier.class); factory.setTarget(target); factory.addAdvice(new ObservationStatement(observation, (Statement<?>) target)); return (T) factory.getProxy(); } /** * @param statement target statement to inspect * @return whether the given {@code statement} is a traced statement wrapper */ public static boolean isObservationStatement(Statement<?> statement) { return statement instanceof CassandraObservationSupplier; } @Nullable @Override public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); if (method.getName().equals("getTargetClass")) { return this.delegate.getClass(); } if (method.getName().equals("getObservation")) { return this.observation; } Object result = invocation.proceed(); if (result instanceof Statement<?>) { this.delegate = (Statement<?>) result; } return result; } }
UTF-8
Java
2,881
java
ObservationStatement.java
Java
[ { "context": "plementation of a {@link Statement}.\n *\n * @author Mark Paluch\n * @author Marcin Grzejszczak\n * @since 4.0\n */\nf", "end": 1174, "score": 0.999808132648468, "start": 1163, "tag": "NAME", "value": "Mark Paluch" }, { "context": "k Statement}.\n *\n * @author Mark Paluch\n * @author Marcin Grzejszczak\n * @since 4.0\n */\nfinal class ObservationStatemen", "end": 1204, "score": 0.9997979402542114, "start": 1186, "tag": "NAME", "value": "Marcin Grzejszczak" } ]
null
[]
/* * Copyright 2022-2023 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 org.springframework.data.cassandra.observability; import io.micrometer.observation.Observation; import java.lang.reflect.Method; import javax.annotation.Nonnull; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ProxyFactory; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; import com.datastax.oss.driver.api.core.cql.Statement; /** * Trace implementation of a {@link Statement}. * * @author <NAME> * @author <NAME> * @since 4.0 */ final class ObservationStatement implements MethodInterceptor { private final Observation observation; private Statement<?> delegate; private ObservationStatement(Observation observation, Statement<?> delegate) { this.observation = observation; this.delegate = delegate; } /** * Creates a proxy with {@link ObservationStatement} attached to it. * * @param observation current observation * @param target target to proxy * @param <T> type of target * @return proxied object with trace advice */ @SuppressWarnings("unchecked") public static <T> T createProxy(Observation observation, T target) { ProxyFactory factory = new ProxyFactory(ClassUtils.getAllInterfaces(target)); factory.addInterface(CassandraObservationSupplier.class); factory.setTarget(target); factory.addAdvice(new ObservationStatement(observation, (Statement<?>) target)); return (T) factory.getProxy(); } /** * @param statement target statement to inspect * @return whether the given {@code statement} is a traced statement wrapper */ public static boolean isObservationStatement(Statement<?> statement) { return statement instanceof CassandraObservationSupplier; } @Nullable @Override public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); if (method.getName().equals("getTargetClass")) { return this.delegate.getClass(); } if (method.getName().equals("getObservation")) { return this.observation; } Object result = invocation.proceed(); if (result instanceof Statement<?>) { this.delegate = (Statement<?>) result; } return result; } }
2,864
0.754946
0.750087
99
28.101009
26.641842
82
false
false
0
0
0
0
0
0
1.030303
false
false
4
11ed3ebadba3cabd509c550e014468fe2f58f733
18,502,719,164,837
6d35cd53bc1de5a9549b39f235029669c18ca902
/q19.java
e07e9d9ed4dcbbb265c9c5aa87ce90d690891878
[]
no_license
zuber524/Java
https://github.com/zuber524/Java
0c04c7d4e11ec6c09b67bf223b16e2b8d71f9ec3
62d6b0a5b06ff5ac338dd9a7082c4099c8d698d3
refs/heads/master
2020-08-30T04:32:13.561000
2019-11-10T19:12:46
2019-11-10T19:12:46
218,264,479
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//19. Write a program to show the use of nested try statements //that emphasizes the sequence of checking for catch handler statements. import java.util.*; class q19 { public static void main(String []args) { Scanner s=new Scanner (System.in); System.out.print("\nEnter the limit of list :"); int n=s.nextInt(); int a[]=new int[n]; System.out.print("\nEnter the elements of list :"); for(int i=0;i<n;i++) a[i]=s.nextInt(); System.out.print("List :["); for(int i=0;i<n;i++) System.out.print(a[i]+", "); System.out.print("\b\b] "); System.out.print("\nEnter the position of element you want to select :"); int p=s.nextInt(); try { int q=a[p-1]; System.out.print("\nYou have selected :"); System.out.print(q); System.out.print("\nEnter your divisor :"); int r=s.nextInt(); try { int div=q/r; System.out.print("\nQuotient :"+div); } catch(ArithmeticException e) { System.out.print("\nException caught ...\nException is :"+e); } } catch(ArrayIndexOutOfBoundsException e) { System.out.print("\nException caught ...\nException is :"+e); } } }
UTF-8
Java
1,179
java
q19.java
Java
[]
null
[]
//19. Write a program to show the use of nested try statements //that emphasizes the sequence of checking for catch handler statements. import java.util.*; class q19 { public static void main(String []args) { Scanner s=new Scanner (System.in); System.out.print("\nEnter the limit of list :"); int n=s.nextInt(); int a[]=new int[n]; System.out.print("\nEnter the elements of list :"); for(int i=0;i<n;i++) a[i]=s.nextInt(); System.out.print("List :["); for(int i=0;i<n;i++) System.out.print(a[i]+", "); System.out.print("\b\b] "); System.out.print("\nEnter the position of element you want to select :"); int p=s.nextInt(); try { int q=a[p-1]; System.out.print("\nYou have selected :"); System.out.print(q); System.out.print("\nEnter your divisor :"); int r=s.nextInt(); try { int div=q/r; System.out.print("\nQuotient :"+div); } catch(ArithmeticException e) { System.out.print("\nException caught ...\nException is :"+e); } } catch(ArrayIndexOutOfBoundsException e) { System.out.print("\nException caught ...\nException is :"+e); } } }
1,179
0.603053
0.597116
44
24.795454
21.54549
75
false
false
0
0
0
0
0
0
2.772727
false
false
4
a38e5eaadbb7edee5b39257cb77cc75ff3b32881
14,894,946,600,860
d666b37c89bc43ae9dc744b96659adde953e3994
/flight.analist/src/main/java/com/flight/analist/itinerary/model/Itinerary.java
8b69491bbadebaf45a7bcc8dd8f42dd2564213a1
[]
no_license
slavcho87/flight
https://github.com/slavcho87/flight
d40b48409400e49d72ced7d6cd08664d809abc8e
f2f0f689d36c3c8b19ff7681b2d46d8dbe493075
refs/heads/master
2020-03-09T02:53:48.878000
2018-04-10T20:05:01
2018-04-10T20:05:01
128,551,506
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.flight.analist.itinerary.model; import java.util.Date; public class Itinerary { private Integer flightId; private String destination; private Date departure; private Date arrival; public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public Date getDeparture() { return departure; } public void setDeparture(Date departure) { this.departure = departure; } public Date getArrival() { return arrival; } public void setArrival(Date arrival) { this.arrival = arrival; } public Integer getFlightId() { return flightId; } public void setFlightId(Integer flightId) { this.flightId = flightId; } }
UTF-8
Java
742
java
Itinerary.java
Java
[]
null
[]
package com.flight.analist.itinerary.model; import java.util.Date; public class Itinerary { private Integer flightId; private String destination; private Date departure; private Date arrival; public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public Date getDeparture() { return departure; } public void setDeparture(Date departure) { this.departure = departure; } public Date getArrival() { return arrival; } public void setArrival(Date arrival) { this.arrival = arrival; } public Integer getFlightId() { return flightId; } public void setFlightId(Integer flightId) { this.flightId = flightId; } }
742
0.726415
0.726415
47
14.787234
15.449211
49
false
false
0
0
0
0
0
0
1.170213
false
false
4
f54a0fd2d7d68ccae889db27ee644b959b7cf78d
14,894,946,602,323
870604ba5587aba4dedd3789779ebbaee1dd0f13
/Java-Hw06/Hw06/src/test/java/HW06_1310444065_Furkan_Erdol/MyComparatorTest.java
ffa1dbaf0ef7bd062642f32f7c1b84ca5c7e169f
[]
no_license
furkanerdol/Data-Structures
https://github.com/furkanerdol/Data-Structures
fbf0066866eb9ee7a7173874d66a522bfe8d0f25
4dc3d394ad12f4d1c5fa2b45912debfbfcecb24c
refs/heads/master
2021-01-01T05:00:57.058000
2016-06-04T11:21:44
2016-06-04T11:21:44
57,238,234
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package HW06_1310444065_Furkan_Erdol; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Furkan */ public class MyComparatorTest { public MyComparatorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of compare method, of class MyComparator. */ @Test public void testCompare() { System.out.println("compare"); Object o1 = 1; Object o2 = 1; MyComparator instance = new MyComparator(); int expResult = 0; int result = instance.compare(o1, o2); assertEquals(expResult, result); } }
UTF-8
Java
979
java
MyComparatorTest.java
Java
[ { "context": " static org.junit.Assert.*;\r\n\r\n/**\r\n *\r\n * @author Furkan\r\n */\r\npublic class MyComparatorTest {\r\n \r\n pu", "end": 240, "score": 0.9169825911521912, "start": 234, "tag": "NAME", "value": "Furkan" } ]
null
[]
package HW06_1310444065_Furkan_Erdol; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Furkan */ public class MyComparatorTest { public MyComparatorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of compare method, of class MyComparator. */ @Test public void testCompare() { System.out.println("compare"); Object o1 = 1; Object o2 = 1; MyComparator instance = new MyComparator(); int expResult = 0; int result = instance.compare(o1, o2); assertEquals(expResult, result); } }
979
0.563841
0.544433
50
17.58
14.954719
53
false
false
0
0
0
0
0
0
0.34
false
false
4
0fc0bd075e6f392c94e4e506ae35a8287055a57a
17,205,639,000,527
ee0ed1ff768ab1f539defce1b0d8c491c5e87af5
/src/java/main/common/RaftSnaphot.java
c84a2e708374976e39471b23332474a26ef0719a
[]
no_license
mmmuuuuua/QCache
https://github.com/mmmuuuuua/QCache
5c258f836a22ff52cf479cc49f0f690088812c75
131e89a41c165e4294590230dc142decb09f8913
refs/heads/master
2020-06-17T05:36:23.302000
2019-06-24T02:24:29
2019-06-24T02:24:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.HashMap; import java.util.Map; /** * Created by quan on 2019/4/25 * 持久化和恢复 * Single Thread 上运行不用加锁 */ public class RaftSnaphot { private static Logger log = LoggerFactory.getLogger(RaftSnaphot.class); /** * 存放RaftSnaphot 文件的路径 */ private String path; public RaftSnaphot(String path) { this.path = path; } /** * 获取snaphost. * * @return 返回一个以nodeId 为key的 Node 值未val的map. 不存在的时候返回一个空的map,而不是null */ public HashMap<Short, Node> getRaftSnaphot() { HashMap<Short, Node> res = new HashMap<Short, Node>(); FileInputStream fileInputStream = null; ObjectInputStream objectInputStream = null; try { File file = new File(path); if (file.isDirectory() || !file.exists()) { boolean flag = file.createNewFile(); if (!flag) { System.exit(1); } } fileInputStream = new FileInputStream(new File(path)); objectInputStream = new ObjectInputStream(fileInputStream); Object temp = objectInputStream.readObject(); if (file.length() > 0 && temp == null) { file.delete(); } if (temp instanceof HashMap) { res = (HashMap<Short, Node>) temp; } } catch (IOException ex) { log.debug(ex.toString()); } catch (ClassNotFoundException ex) { log.debug(ex.toString()); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (objectInputStream != null) { objectInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return res; } /** * 持久化数据到磁盘中 */ public void raftSnaphotStore(Map<Short, Node> map) { File file = new File(path); if (!file.exists() || file.isDirectory()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } ObjectOutputStream objectOutputStream = null; try { objectOutputStream = new ObjectOutputStream( new FileOutputStream(file)); objectOutputStream.writeObject(map); } catch (IOException e) { e.printStackTrace(); } finally { if (objectOutputStream != null) { try { objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
UTF-8
Java
3,001
java
RaftSnaphot.java
Java
[ { "context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by quan on 2019/4/25\n * 持久化和恢复\n * Single Thread 上运行不用加锁\n ", "end": 164, "score": 0.999462366104126, "start": 160, "tag": "USERNAME", "value": "quan" } ]
null
[]
package common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.HashMap; import java.util.Map; /** * Created by quan on 2019/4/25 * 持久化和恢复 * Single Thread 上运行不用加锁 */ public class RaftSnaphot { private static Logger log = LoggerFactory.getLogger(RaftSnaphot.class); /** * 存放RaftSnaphot 文件的路径 */ private String path; public RaftSnaphot(String path) { this.path = path; } /** * 获取snaphost. * * @return 返回一个以nodeId 为key的 Node 值未val的map. 不存在的时候返回一个空的map,而不是null */ public HashMap<Short, Node> getRaftSnaphot() { HashMap<Short, Node> res = new HashMap<Short, Node>(); FileInputStream fileInputStream = null; ObjectInputStream objectInputStream = null; try { File file = new File(path); if (file.isDirectory() || !file.exists()) { boolean flag = file.createNewFile(); if (!flag) { System.exit(1); } } fileInputStream = new FileInputStream(new File(path)); objectInputStream = new ObjectInputStream(fileInputStream); Object temp = objectInputStream.readObject(); if (file.length() > 0 && temp == null) { file.delete(); } if (temp instanceof HashMap) { res = (HashMap<Short, Node>) temp; } } catch (IOException ex) { log.debug(ex.toString()); } catch (ClassNotFoundException ex) { log.debug(ex.toString()); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (objectInputStream != null) { objectInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return res; } /** * 持久化数据到磁盘中 */ public void raftSnaphotStore(Map<Short, Node> map) { File file = new File(path); if (!file.exists() || file.isDirectory()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } ObjectOutputStream objectOutputStream = null; try { objectOutputStream = new ObjectOutputStream( new FileOutputStream(file)); objectOutputStream.writeObject(map); } catch (IOException e) { e.printStackTrace(); } finally { if (objectOutputStream != null) { try { objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
3,001
0.505365
0.501558
100
27.889999
19.156668
75
false
false
0
0
0
0
0
0
0.45
false
false
4
c09de64b5769acfbe52a0d48796ff53ff7f68a37
17,205,639,003,754
a12dee7565e528c7e47d9d025720d67874d31281
/src/main/java/sales/goods/service/GoodsServiceImpl.java
8b32b9a69cbcec2fb59eb47c7ab99cb0f76f5831
[ "MIT" ]
permissive
KraytsMan/sales-if-ua
https://github.com/KraytsMan/sales-if-ua
dc1eb4f9bb68509054ec78a460801ca0363199a3
7480d942f1408f8e51a48b712aaa9a946e360ea3
refs/heads/master
2021-01-18T06:06:52.127000
2015-08-10T11:49:59
2015-08-10T11:49:59
39,687,788
0
0
null
true
2015-07-25T14:04:19
2015-07-25T14:04:19
2015-07-20T21:04:32
2015-07-25T14:02:50
156
0
0
0
null
null
null
package sales.goods.service; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import sales.goods.domain.Good; import sales.goods.repository.GoodsRepository; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @Service @Transactional public class GoodsServiceImpl implements GoodsService { @Autowired private GoodsRepository repository; public Good get(long id) { return repository.findById(id); } public List<Good> getAll() { return repository.findAll(); } public Good save(Good good) { repository.save(good); return good; } public void delete(long id) { repository.removeById(id); } public List<Good> page(int page, int amount, Map<String, String> sort) { PageRequest pageRequest; if (sort == null || sort.isEmpty()) { pageRequest = new PageRequest(page, amount); } else { List<Sort.Order> orders = new ArrayList(); Set<String> sortParams = sort.keySet(); for (String sortParam : sortParams) { orders.add(new Sort.Order(Sort.Direction.fromString(sort.get(sortParam)), sortParam)); } pageRequest = new PageRequest( page, amount, new Sort(orders)); } return Lists.newArrayList(repository.findAll(pageRequest).getContent()); } public List<Good> searchByName(String name) { return repository.findByNameContainingIgnoreCase(name); } }
UTF-8
Java
1,839
java
GoodsServiceImpl.java
Java
[]
null
[]
package sales.goods.service; import com.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import sales.goods.domain.Good; import sales.goods.repository.GoodsRepository; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @Service @Transactional public class GoodsServiceImpl implements GoodsService { @Autowired private GoodsRepository repository; public Good get(long id) { return repository.findById(id); } public List<Good> getAll() { return repository.findAll(); } public Good save(Good good) { repository.save(good); return good; } public void delete(long id) { repository.removeById(id); } public List<Good> page(int page, int amount, Map<String, String> sort) { PageRequest pageRequest; if (sort == null || sort.isEmpty()) { pageRequest = new PageRequest(page, amount); } else { List<Sort.Order> orders = new ArrayList(); Set<String> sortParams = sort.keySet(); for (String sortParam : sortParams) { orders.add(new Sort.Order(Sort.Direction.fromString(sort.get(sortParam)), sortParam)); } pageRequest = new PageRequest( page, amount, new Sort(orders)); } return Lists.newArrayList(repository.findAll(pageRequest).getContent()); } public List<Good> searchByName(String name) { return repository.findByNameContainingIgnoreCase(name); } }
1,839
0.660685
0.660685
62
28.661291
23.344505
102
false
false
0
0
0
0
0
0
0.580645
false
false
4
376d703035af9165808c5a6521470f99dc2a29a3
893,353,200,181
7462083f34655405414ed6ab082889f97d8eea77
/src/java/controlador/servletLogin.java
cd22b98f651a5d31187d680a41aee4c107323a97
[]
no_license
carlosalejandro98/technoFoodGit
https://github.com/carlosalejandro98/technoFoodGit
8f257787dce8f1f7e6908deda1f502b13db34451
29737b49bc4c3109a0da31c339c9fba04ca326a5
refs/heads/master
2020-08-15T12:22:31.592000
2019-11-10T19:12:44
2019-11-10T19:12:44
215,341,524
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 controlador; import dao.UsuarioDAO; import dto.Usuario; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author Carlitos */ public class servletLogin extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String accion = request.getParameter("btnAccion"); if (accion.equals("Ingresar")) { String usu = request.getParameter("txtUsuario"); String pass = request.getParameter("txtContrasena"); UsuarioDAO dao = new UsuarioDAO(); Usuario u = new Usuario(); int r; u.setUsuario(usu); u.setContrasena(pass); r = dao.validar(u); if (r == 1) { request.getSession().setAttribute("usuario", u.getId()); request.getSession().setAttribute("sesion", u); request.getSession().setAttribute("nombre", u.getNombre()); request.getSession().setAttribute("apellido", u.getApellido()); request.getSession().setAttribute("usu", u.getTipo_usuario()); request.getRequestDispatcher("navegador.jsp").forward(request, response); } else { request.setAttribute("msjOK", "Usuario o Contraseña incorrecta"); request.getRequestDispatcher("login.jsp").forward(request, response); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
UTF-8
Java
3,595
java
servletLogin.java
Java
[ { "context": "x.servlet.http.HttpSession;\r\n\r\n/**\r\n *\r\n * @author Carlitos\r\n */\r\npublic class servletLogin extends HttpServl", "end": 562, "score": 0.8540045619010925, "start": 554, "tag": "USERNAME", "value": "Carlitos" } ]
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 controlador; import dao.UsuarioDAO; import dto.Usuario; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author Carlitos */ public class servletLogin extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String accion = request.getParameter("btnAccion"); if (accion.equals("Ingresar")) { String usu = request.getParameter("txtUsuario"); String pass = request.getParameter("txtContrasena"); UsuarioDAO dao = new UsuarioDAO(); Usuario u = new Usuario(); int r; u.setUsuario(usu); u.setContrasena(pass); r = dao.validar(u); if (r == 1) { request.getSession().setAttribute("usuario", u.getId()); request.getSession().setAttribute("sesion", u); request.getSession().setAttribute("nombre", u.getNombre()); request.getSession().setAttribute("apellido", u.getApellido()); request.getSession().setAttribute("usu", u.getTipo_usuario()); request.getRequestDispatcher("navegador.jsp").forward(request, response); } else { request.setAttribute("msjOK", "Usuario o Contraseña incorrecta"); request.getRequestDispatcher("login.jsp").forward(request, response); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
3,595
0.63133
0.631052
102
33.235294
27.885683
123
false
false
0
0
0
0
0
0
0.480392
false
false
4
e1ca39d45313b88c06aed821d592df5ed0a88aa7
16,956,530,884,984
853f03f9e8bd9377332f2b100b45ed1ef996d4ab
/pubmed-glutton/src/main/java/com/scienceminer/glutton/export/PubMedExporter.java
92c6560df2cc25ecd773c8b842fb38cebfbd3f31
[ "Apache-2.0" ]
permissive
nguyendoanquyet/biblio-glutton
https://github.com/nguyendoanquyet/biblio-glutton
711e47cb590fd8926f968cb39dd0dc94358aa8cc
26e080bc8e6b1d6118a62aaef0620d67dd034c9b
refs/heads/master
2023-03-20T14:51:36.244000
2020-10-14T03:02:45
2020-10-14T03:02:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.scienceminer.glutton.export; import java.io.*; import java.util.*; import com.opencsv.*; import com.scienceminer.glutton.utilities.GluttonConfig; import com.scienceminer.glutton.data.db.KBEnvironment; import com.scienceminer.glutton.data.db.KBStagingEnvironment; import com.scienceminer.glutton.data.db.KBIterator; import com.scienceminer.glutton.data.Biblio; import com.scienceminer.glutton.data.ClassificationClass; import com.scienceminer.glutton.data.MeSHClass; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.io.*; import org.fusesource.lmdbjni.*; import static org.fusesource.lmdbjni.Constants.*; import org.elasticsearch.client.*; import org.elasticsearch.action.index.*; import org.elasticsearch.action.search.*; import org.elasticsearch.search.Scroll; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import static org.elasticsearch.index.query.QueryBuilders.*; import org.elasticsearch.action.bulk.*; import static org.elasticsearch.common.xcontent.XContentFactory.*; import org.elasticsearch.common.xcontent.*; import org.elasticsearch.common.unit.TimeValue; import org.apache.http.HttpHost; public class PubMedExporter { private GluttonConfig conf = null; private KBStagingEnvironment env = null; private ObjectMapper mapper = new ObjectMapper(); public enum Format { CSV, JSON, XML } public static String extension(Format format) { switch(format) { case CSV: return ".csv"; case JSON: return ".json"; case XML: return ".xml"; default: return ""; } } public PubMedExporter(KBStagingEnvironment env, GluttonConfig conf) { this.env = env; this.conf = conf; } /** * Simple export based on MeSH descriptors (MeSH class ID or MeSH term) using ES. * Boolean majorTopic indicates if the MeSH descriptor must be a major topic or * not for the candidate documents. * * MeSH descriptors per class are given by the input file as csv table. One class is defined * by one or several MeSH descriptors. * Output path gives the repository were to write the export files, one file per class. * * If onlyPMC parameter is true, we only export entries having a PMC identifier. */ public void export(String inputPathDescriptors, String outputPath, Format outputFormat, boolean onlyPMC) { List<String> allLevel2 = new ArrayList<String>(); List<String> allLevel1 = new ArrayList<String>(); try (BufferedReader reader = new BufferedReader(new FileReader(inputPathDescriptors))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); String[] pieces = line.split(","); if (pieces.length != 4) continue; String level1 = pieces[0]; String level2 = pieces[1]; String level3 = pieces[2]; String descriptor = pieces[3]; CSVWriter writerLevel2 = null; CSVWriter writerLevel1 = null; // check if the export file exist for level 2 File fileLevel2 = new File(outputPath + File.separator + level2 + extension(outputFormat)); if (fileLevel2.exists() && allLevel2.contains(level2)) { // append Writer writerFileLevel2 = new FileWriter(fileLevel2, true); writerLevel2 = new CSVWriter(writerFileLevel2); } else { Writer writerFileLevel2 = new FileWriter(fileLevel2); writerLevel2 = new CSVWriter(writerFileLevel2); } allLevel2.add(level2); // check if the export file exist for level 1 File fileLevel1 = new File(outputPath + File.separator + level1 + extension(outputFormat)); if (fileLevel1.exists() && allLevel1.contains(level1)) { // append Writer writerFileLevel1 = new FileWriter(fileLevel1, true); writerLevel1 = new CSVWriter(writerFileLevel1); } else { Writer writerFileLevel1 = new FileWriter(fileLevel1); writerLevel1 = new CSVWriter(writerFileLevel1); writerLevel1.writeNext(PubMedSerializer.CSV_HEADERS); } allLevel1.add(level1); export(descriptor, null, true, writerLevel2, outputFormat, onlyPMC); export(descriptor, null, true, writerLevel1, outputFormat, onlyPMC); writerLevel2.close(); writerLevel1.close(); } } catch (IOException e) { e.printStackTrace(); } } /** * Export records based on one MeSH descriptor (MeSH class ID or MeSH term) using ES. * Boolean majorTopic indicates if the MeSH descriptor must be a major topic or * not for the candidate documents. */ public void export(String meshId, String term, boolean majorTopic, CSVWriter writer, Format outputFormat, boolean onlyPMC) throws IOException { /** Example ES search query to retrieve document identifiers from a MeSH id descriptor pubmed/_search { "query": { "query_string": { "default_field": "mesh.descriptor.meshId", "query": "D003250" } } } **/ // init elasticsearch client RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost(conf.getEsHost(), conf.getEsPort(), "http"), new HttpHost(conf.getEsHost(), conf.getEsPort(), "http"))); final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(120L)); SearchRequest searchRequest = new SearchRequest("pubmed"); searchRequest.scroll(scroll); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(matchQuery("mesh.descriptor.meshId", meshId)); searchSourceBuilder.size(100); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); String scrollId = searchResponse.getScrollId(); SearchHit[] searchHits = searchResponse.getHits().getHits(); while (searchHits != null && searchHits.length > 0) { SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId); scrollRequest.scroll(scroll); searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT); scrollId = searchResponse.getScrollId(); searchHits = searchResponse.getHits().getHits(); System.out.println(searchHits.length); // access the result for (SearchHit hit : searchHits) { //System.out.println(hit.getSourceAsString()); String doi = null; String pmc = null; String pmid = null; try { JsonNode resJsonStruct = mapper.readTree(hit.getSourceAsString()); if (majorTopic && !isMajorTopic(resJsonStruct, meshId)) { //System.out.println(hit.getSourceAsString()); continue; } JsonNode doiNode = resJsonStruct.path("doi"); if (!doiNode.isMissingNode()) { doi = doiNode.textValue(); } JsonNode pmidNode = resJsonStruct.path("PMID"); if (!pmidNode.isMissingNode()) { pmid = pmidNode.asText(); } JsonNode pmcNode = resJsonStruct.path("pmc"); if (!pmcNode.isMissingNode()) { pmc = pmcNode.textValue(); } if (pmc == null && onlyPMC) continue; } catch(Exception e){ e.printStackTrace(); } if (pmid == null) continue; // retrieve the full PubMed biblio object Biblio biblio = env.getDbPMID2Biblio().retrieve(new Integer(pmid)); if (biblio.getDoi() == null) { biblio.setDoi(doi); } if (biblio.getPmc() == null) { biblio.setPmc(pmc); } // serialize the biblio object in the desired format if (outputFormat == Format.CSV) { try { PubMedSerializer.serializeCsv(writer, biblio); } catch(Exception e) { e.printStackTrace(); } } } } ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(scrollId); ClearScrollResponse clearScrollResponse = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT); boolean succeeded = clearScrollResponse.isSucceeded(); if (succeeded) System.out.println("scroll request cleaned"); else System.out.println("scroll request cleaning failed"); } /** * Return true if the mesh id is present in the mesh descriptors as major topic */ public boolean isMajorTopic(JsonNode resJsonStruct, String meshId) { JsonNode meshNode = resJsonStruct.path("mesh"); if (!meshNode.isMissingNode()) { if (meshNode.isArray()) { for (JsonNode arrayItem : meshNode) { JsonNode descriptorNode = arrayItem.path("descriptor"); if (!descriptorNode.isMissingNode()) { JsonNode meshIdNode = descriptorNode.path("meshId"); String localMeshId = meshIdNode.textValue(); if (!localMeshId.equals(meshId)) continue; JsonNode majorTopicNode = descriptorNode.path("majorTopic"); String majorTopic = majorTopicNode.textValue(); if (majorTopic.equals("true")) return true; // if an associated qualifier has a majorTopic at true, we consider that // the descriptor can inherite it (at least it's how PubMed search engine is working) JsonNode qualifiersNode = arrayItem.path("qualifiers"); if (!qualifiersNode.isMissingNode()) { if (qualifiersNode.isArray()) { for (JsonNode qualifierArrayItem : qualifiersNode) { JsonNode qualifierNode = qualifierArrayItem.path("qualifier"); if (!qualifierNode.isMissingNode()) { JsonNode qualifierMajorTopicNode = qualifierNode.path("majorTopic"); String qualifierMajorTopic = qualifierMajorTopicNode.textValue(); if (qualifierMajorTopic.equals("true")) return true; } } } } } } } } return false; } }
UTF-8
Java
12,344
java
PubMedExporter.java
Java
[]
null
[]
package com.scienceminer.glutton.export; import java.io.*; import java.util.*; import com.opencsv.*; import com.scienceminer.glutton.utilities.GluttonConfig; import com.scienceminer.glutton.data.db.KBEnvironment; import com.scienceminer.glutton.data.db.KBStagingEnvironment; import com.scienceminer.glutton.data.db.KBIterator; import com.scienceminer.glutton.data.Biblio; import com.scienceminer.glutton.data.ClassificationClass; import com.scienceminer.glutton.data.MeSHClass; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.io.*; import org.fusesource.lmdbjni.*; import static org.fusesource.lmdbjni.Constants.*; import org.elasticsearch.client.*; import org.elasticsearch.action.index.*; import org.elasticsearch.action.search.*; import org.elasticsearch.search.Scroll; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import static org.elasticsearch.index.query.QueryBuilders.*; import org.elasticsearch.action.bulk.*; import static org.elasticsearch.common.xcontent.XContentFactory.*; import org.elasticsearch.common.xcontent.*; import org.elasticsearch.common.unit.TimeValue; import org.apache.http.HttpHost; public class PubMedExporter { private GluttonConfig conf = null; private KBStagingEnvironment env = null; private ObjectMapper mapper = new ObjectMapper(); public enum Format { CSV, JSON, XML } public static String extension(Format format) { switch(format) { case CSV: return ".csv"; case JSON: return ".json"; case XML: return ".xml"; default: return ""; } } public PubMedExporter(KBStagingEnvironment env, GluttonConfig conf) { this.env = env; this.conf = conf; } /** * Simple export based on MeSH descriptors (MeSH class ID or MeSH term) using ES. * Boolean majorTopic indicates if the MeSH descriptor must be a major topic or * not for the candidate documents. * * MeSH descriptors per class are given by the input file as csv table. One class is defined * by one or several MeSH descriptors. * Output path gives the repository were to write the export files, one file per class. * * If onlyPMC parameter is true, we only export entries having a PMC identifier. */ public void export(String inputPathDescriptors, String outputPath, Format outputFormat, boolean onlyPMC) { List<String> allLevel2 = new ArrayList<String>(); List<String> allLevel1 = new ArrayList<String>(); try (BufferedReader reader = new BufferedReader(new FileReader(inputPathDescriptors))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); String[] pieces = line.split(","); if (pieces.length != 4) continue; String level1 = pieces[0]; String level2 = pieces[1]; String level3 = pieces[2]; String descriptor = pieces[3]; CSVWriter writerLevel2 = null; CSVWriter writerLevel1 = null; // check if the export file exist for level 2 File fileLevel2 = new File(outputPath + File.separator + level2 + extension(outputFormat)); if (fileLevel2.exists() && allLevel2.contains(level2)) { // append Writer writerFileLevel2 = new FileWriter(fileLevel2, true); writerLevel2 = new CSVWriter(writerFileLevel2); } else { Writer writerFileLevel2 = new FileWriter(fileLevel2); writerLevel2 = new CSVWriter(writerFileLevel2); } allLevel2.add(level2); // check if the export file exist for level 1 File fileLevel1 = new File(outputPath + File.separator + level1 + extension(outputFormat)); if (fileLevel1.exists() && allLevel1.contains(level1)) { // append Writer writerFileLevel1 = new FileWriter(fileLevel1, true); writerLevel1 = new CSVWriter(writerFileLevel1); } else { Writer writerFileLevel1 = new FileWriter(fileLevel1); writerLevel1 = new CSVWriter(writerFileLevel1); writerLevel1.writeNext(PubMedSerializer.CSV_HEADERS); } allLevel1.add(level1); export(descriptor, null, true, writerLevel2, outputFormat, onlyPMC); export(descriptor, null, true, writerLevel1, outputFormat, onlyPMC); writerLevel2.close(); writerLevel1.close(); } } catch (IOException e) { e.printStackTrace(); } } /** * Export records based on one MeSH descriptor (MeSH class ID or MeSH term) using ES. * Boolean majorTopic indicates if the MeSH descriptor must be a major topic or * not for the candidate documents. */ public void export(String meshId, String term, boolean majorTopic, CSVWriter writer, Format outputFormat, boolean onlyPMC) throws IOException { /** Example ES search query to retrieve document identifiers from a MeSH id descriptor pubmed/_search { "query": { "query_string": { "default_field": "mesh.descriptor.meshId", "query": "D003250" } } } **/ // init elasticsearch client RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost(conf.getEsHost(), conf.getEsPort(), "http"), new HttpHost(conf.getEsHost(), conf.getEsPort(), "http"))); final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(120L)); SearchRequest searchRequest = new SearchRequest("pubmed"); searchRequest.scroll(scroll); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(matchQuery("mesh.descriptor.meshId", meshId)); searchSourceBuilder.size(100); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); String scrollId = searchResponse.getScrollId(); SearchHit[] searchHits = searchResponse.getHits().getHits(); while (searchHits != null && searchHits.length > 0) { SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId); scrollRequest.scroll(scroll); searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT); scrollId = searchResponse.getScrollId(); searchHits = searchResponse.getHits().getHits(); System.out.println(searchHits.length); // access the result for (SearchHit hit : searchHits) { //System.out.println(hit.getSourceAsString()); String doi = null; String pmc = null; String pmid = null; try { JsonNode resJsonStruct = mapper.readTree(hit.getSourceAsString()); if (majorTopic && !isMajorTopic(resJsonStruct, meshId)) { //System.out.println(hit.getSourceAsString()); continue; } JsonNode doiNode = resJsonStruct.path("doi"); if (!doiNode.isMissingNode()) { doi = doiNode.textValue(); } JsonNode pmidNode = resJsonStruct.path("PMID"); if (!pmidNode.isMissingNode()) { pmid = pmidNode.asText(); } JsonNode pmcNode = resJsonStruct.path("pmc"); if (!pmcNode.isMissingNode()) { pmc = pmcNode.textValue(); } if (pmc == null && onlyPMC) continue; } catch(Exception e){ e.printStackTrace(); } if (pmid == null) continue; // retrieve the full PubMed biblio object Biblio biblio = env.getDbPMID2Biblio().retrieve(new Integer(pmid)); if (biblio.getDoi() == null) { biblio.setDoi(doi); } if (biblio.getPmc() == null) { biblio.setPmc(pmc); } // serialize the biblio object in the desired format if (outputFormat == Format.CSV) { try { PubMedSerializer.serializeCsv(writer, biblio); } catch(Exception e) { e.printStackTrace(); } } } } ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(scrollId); ClearScrollResponse clearScrollResponse = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT); boolean succeeded = clearScrollResponse.isSucceeded(); if (succeeded) System.out.println("scroll request cleaned"); else System.out.println("scroll request cleaning failed"); } /** * Return true if the mesh id is present in the mesh descriptors as major topic */ public boolean isMajorTopic(JsonNode resJsonStruct, String meshId) { JsonNode meshNode = resJsonStruct.path("mesh"); if (!meshNode.isMissingNode()) { if (meshNode.isArray()) { for (JsonNode arrayItem : meshNode) { JsonNode descriptorNode = arrayItem.path("descriptor"); if (!descriptorNode.isMissingNode()) { JsonNode meshIdNode = descriptorNode.path("meshId"); String localMeshId = meshIdNode.textValue(); if (!localMeshId.equals(meshId)) continue; JsonNode majorTopicNode = descriptorNode.path("majorTopic"); String majorTopic = majorTopicNode.textValue(); if (majorTopic.equals("true")) return true; // if an associated qualifier has a majorTopic at true, we consider that // the descriptor can inherite it (at least it's how PubMed search engine is working) JsonNode qualifiersNode = arrayItem.path("qualifiers"); if (!qualifiersNode.isMissingNode()) { if (qualifiersNode.isArray()) { for (JsonNode qualifierArrayItem : qualifiersNode) { JsonNode qualifierNode = qualifierArrayItem.path("qualifier"); if (!qualifierNode.isMissingNode()) { JsonNode qualifierMajorTopicNode = qualifierNode.path("majorTopic"); String qualifierMajorTopic = qualifierMajorTopicNode.textValue(); if (qualifierMajorTopic.equals("true")) return true; } } } } } } } } return false; } }
12,344
0.557599
0.552495
308
39.081169
29.088366
145
false
false
0
0
0
0
0
0
0.548701
false
false
4
cb6077b6d1d665754c9766c2fe25d7fbde2a55b8
25,744,034,024,375
c40e53f511b05d281644f1e8dd1782dad080dc4a
/ball1.java
619b995f45fb69f1faaefbfabeab8463889102de
[ "Apache-2.0" ]
permissive
uon-projects/BallGame
https://github.com/uon-projects/BallGame
01825c64f011feb4a6265f78c2cd97c2b5e31596
1978133d7a07aea24bdb2ec8669565f88c15f720
refs/heads/master
2023-04-08T15:46:54.189000
2020-09-03T16:58:20
2020-09-03T16:58:20
227,173,921
0
0
Apache-2.0
false
2021-04-20T18:20:43
2019-12-10T17:07:03
2021-04-20T17:40:50
2021-04-20T17:37:58
46
2
0
0
Java
false
false
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class ball1 here. * * @authors (Teodor Grigor & Scott Turner) * @version (v1.0) */ public class ball1 extends Actor { //method that is called when the run or act button is pressed //method that draw the actor public void act() { //getting the class of the holder world - MyWorld World world = getWorld(); MyWorld myWorld = (MyWorld)world; //getting the speed of the ball from the myWorld int ballSpeed = myWorld.getBallSpeed(); //move the ball by ballSpeed value move(ballSpeed); //getting the counter from the myWorld so we can interact with the public methods Counter counter = myWorld.getCounter(); //getting the babies that are in the Team A //getting the baby1 class and store it into a variable Actor baby_1 = getOneIntersectingObject(baby1.class); //getting the baby3 class and store it into a variable Actor baby_3 = getOneIntersectingObject(baby3.class); //getting the babies that are in the Team B //getting the baby2 class and store it into a variable Actor baby_2 = getOneIntersectingObject(baby2.class); //getting the baby4 class and store it into a variable Actor baby_4 = getOneIntersectingObject(baby4.class); //check for collision for the babies from the Team A //cehck for baby 1 if (baby_1!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby1.class); } //cehck for baby 3 if (baby_3!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby3.class); } //check for collision for the babies from the Team B //cehck for baby 2 if (baby_2!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby2.class); } //check for baby 4 if (baby_4!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby4.class); } //check if the ball hits the bottom or the top boundary if(checkHitsBoundaries()) { //in case it hits the boundaries then we bounce the ball of the wall bounceBallOffWall(); } //check if the ball go beyound the babies from each team if(checkLost()) { //in case it does: // -we add a point to team team that scored // -we show the notification for GOAL for the relevant team if(getX() <= 100) { counter.addScoreToB(); myWorld.goalScored(2); } else if(getX() >=500) { counter.addScoreToA(); myWorld.goalScored(1); } // -we initialise the team members and the ball to the default positions setLocation(300, 200); Actor baby1 = (Actor)getWorld().getObjects(baby1.class).get(0); baby1.setLocation(150, 100); Actor baby2 = (Actor)getWorld().getObjects(baby2.class).get(0); baby2.setLocation(450, 100); Actor baby3 = (Actor)getWorld().getObjects(baby3.class).get(0); baby3.setLocation(150, 300); Actor baby4 = (Actor)getWorld().getObjects(baby4.class).get(0); baby4.setLocation(450, 300); } } //method that retrives a number //this number represents the turn degree //the number returned is in a range from 30 to 150 private int generateTurnDegree() { return Greenfoot.getRandomNumber(120) + 30; } //method that moves the ball until it doesn't collide with the baby private void moveOnCollision(Class baby) { do { //move by 10 move(10); } while(getOneIntersectingObject(baby) != null); } //method that check if the ball hits the boundaries private boolean checkHitsBoundaries() { if(getY() > 10 && getY() < 390) { //it doesn't return false; } //it does return true; } //method that makes the ball to rotate in a realistic way private void bounceBallOffWall() { if (getY() == 0 || getY() == getWorld().getHeight() - 1) { setRotation(360-getRotation()); } } //method that checks if the ball passed beyond the babies public boolean checkLost() { if(getX() > 100 && getX() < 500) { //it didn't return false; } //it did return true; } }
UTF-8
Java
5,459
java
ball1.java
Java
[ { "context": "description of class ball1 here.\n * \n * @authors (Teodor Grigor & Scott Turner) \n * @version (v1.0)\n */\npublic cl", "end": 159, "score": 0.9998986124992371, "start": 146, "tag": "NAME", "value": "Teodor Grigor" }, { "context": "class ball1 here.\n * \n * @authors (Teodor Grigor & Scott Turner) \n * @version (v1.0)\n */\npublic class ball1 exten", "end": 174, "score": 0.9998868703842163, "start": 162, "tag": "NAME", "value": "Scott Turner" } ]
null
[]
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class ball1 here. * * @authors (<NAME> & <NAME>) * @version (v1.0) */ public class ball1 extends Actor { //method that is called when the run or act button is pressed //method that draw the actor public void act() { //getting the class of the holder world - MyWorld World world = getWorld(); MyWorld myWorld = (MyWorld)world; //getting the speed of the ball from the myWorld int ballSpeed = myWorld.getBallSpeed(); //move the ball by ballSpeed value move(ballSpeed); //getting the counter from the myWorld so we can interact with the public methods Counter counter = myWorld.getCounter(); //getting the babies that are in the Team A //getting the baby1 class and store it into a variable Actor baby_1 = getOneIntersectingObject(baby1.class); //getting the baby3 class and store it into a variable Actor baby_3 = getOneIntersectingObject(baby3.class); //getting the babies that are in the Team B //getting the baby2 class and store it into a variable Actor baby_2 = getOneIntersectingObject(baby2.class); //getting the baby4 class and store it into a variable Actor baby_4 = getOneIntersectingObject(baby4.class); //check for collision for the babies from the Team A //cehck for baby 1 if (baby_1!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby1.class); } //cehck for baby 3 if (baby_3!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby3.class); } //check for collision for the babies from the Team B //cehck for baby 2 if (baby_2!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby2.class); } //check for baby 4 if (baby_4!=null) { //on collision: // -turn the ball to a random direction turn(generateTurnDegree() + 90); // -move the baby until the two sprites don't collide anymore moveOnCollision(baby4.class); } //check if the ball hits the bottom or the top boundary if(checkHitsBoundaries()) { //in case it hits the boundaries then we bounce the ball of the wall bounceBallOffWall(); } //check if the ball go beyound the babies from each team if(checkLost()) { //in case it does: // -we add a point to team team that scored // -we show the notification for GOAL for the relevant team if(getX() <= 100) { counter.addScoreToB(); myWorld.goalScored(2); } else if(getX() >=500) { counter.addScoreToA(); myWorld.goalScored(1); } // -we initialise the team members and the ball to the default positions setLocation(300, 200); Actor baby1 = (Actor)getWorld().getObjects(baby1.class).get(0); baby1.setLocation(150, 100); Actor baby2 = (Actor)getWorld().getObjects(baby2.class).get(0); baby2.setLocation(450, 100); Actor baby3 = (Actor)getWorld().getObjects(baby3.class).get(0); baby3.setLocation(150, 300); Actor baby4 = (Actor)getWorld().getObjects(baby4.class).get(0); baby4.setLocation(450, 300); } } //method that retrives a number //this number represents the turn degree //the number returned is in a range from 30 to 150 private int generateTurnDegree() { return Greenfoot.getRandomNumber(120) + 30; } //method that moves the ball until it doesn't collide with the baby private void moveOnCollision(Class baby) { do { //move by 10 move(10); } while(getOneIntersectingObject(baby) != null); } //method that check if the ball hits the boundaries private boolean checkHitsBoundaries() { if(getY() > 10 && getY() < 390) { //it doesn't return false; } //it does return true; } //method that makes the ball to rotate in a realistic way private void bounceBallOffWall() { if (getY() == 0 || getY() == getWorld().getHeight() - 1) { setRotation(360-getRotation()); } } //method that checks if the ball passed beyond the babies public boolean checkLost() { if(getX() > 100 && getX() < 500) { //it didn't return false; } //it did return true; } }
5,446
0.560176
0.538194
159
33.333332
23.130384
89
false
false
0
0
0
0
0
0
0.314465
false
false
4
0dfd531202cbc25f30ef5a028c93a5d70a10dbce
12,146,167,514,600
e22b474b2d896820a921fb20c0b1c6235dcaa821
/app/src/main/java/com/gallosdata/fragment/cock/CockRacesFragment.java
83179a25826c0f144b4ea68b9d804dd3b90a56d4
[]
no_license
sidmobileapps/gcda
https://github.com/sidmobileapps/gcda
9f3600656b74eb1e0fe19c87bced639ea6cbedc6
8ad2eed8c5be486fcd0f0be72a67a1c69949abcf
refs/heads/master
2018-12-25T08:56:53.591000
2018-12-17T20:27:01
2018-12-17T20:27:01
140,046,920
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gallosdata.fragment.cock; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.gallosdata.Application; import com.gallosdata.Constants; import com.gallosdata.R; import com.gallosdata.activity.BaseActivity; import com.gallosdata.activity.HomeActivity; import com.gallosdata.fragment.BaseFragment; import com.gallosdata.model.Cock; import com.gallosdata.model.Race; import com.gallosdata.net.NetworkClient; import com.gallosdata.net.NoInternetException; import com.gallosdata.view.GraphMenuItem; import com.gallosdata.view.RaceItem; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Mr.Dzyga on 07.07.2018. */ public class CockRacesFragment extends BaseFragment implements View.OnClickListener { private static final String TAG = "CockRacesFragment"; private LinearLayout racesHolder, graphsHolder, addRaceHolder; private List<Race> racesList = new ArrayList<>(); private LineChart lineChart; private GraphMenuItem btnAll, btnStart, btnStrength, btnSpeed, btnBalance, btnPosition; private Cock cock; private CockFragment root; private TextView emptyView, addRace, racesQuality; @Override public void onCreate(Bundle bundle){ super.onCreate(bundle); } @Override public void onDestroy() { super.onDestroy(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_cock_races, container, false); racesHolder = (LinearLayout)rootView.findViewById(R.id.cock_races_holder); graphsHolder = (LinearLayout)rootView.findViewById(R.id.races_graphs); addRaceHolder = (LinearLayout)rootView.findViewById(R.id.add_race_button_holder); btnAll = (GraphMenuItem)rootView.findViewById(R.id.races_chart_all); btnStart = (GraphMenuItem)rootView.findViewById(R.id.races_chart_start); btnStrength = (GraphMenuItem)rootView.findViewById(R.id.races_chart_strength); btnSpeed = (GraphMenuItem)rootView.findViewById(R.id.races_chart_speed); btnBalance = (GraphMenuItem)rootView.findViewById(R.id.races_chart_balance); btnPosition = (GraphMenuItem)rootView.findViewById(R.id.races_chart_position); racesQuality = (TextView)rootView.findViewById(R.id.races_average_quality); emptyView = (TextView)rootView.findViewById(R.id.races_empty_view); addRace = (TextView)rootView.findViewById(R.id.add_race_button); addRace.setOnClickListener(this); btnAll.setOnClickListener(this); btnStart.setOnClickListener(this); btnStrength.setOnClickListener(this); btnSpeed.setOnClickListener(this); btnBalance.setOnClickListener(this); btnPosition.setOnClickListener(this); HomeActivity activity = (HomeActivity) getActivity(); if (activity!=null) activity.setToolbarItems(true, root.cock.getID()<0?getString(R.string.add_cock):root.cock.getName(), false, root.cock.getGender()==0?getString(R.string.add_race):null); lineChart = (LineChart)rootView.findViewById(R.id.races_chart); //setAllStuff(); if (root.cock.getGender()!=0){ emptyView.setText(getText(R.string.female_cannot_have_races)); graphsHolder.setVisibility(View.GONE); addRaceHolder.setVisibility(View.GONE); } // fillRaces(); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (root.cock.getGender()==0) getRaces(); } private void getRaces() { BaseActivity.showProgress((HomeActivity)getActivity(), true); Call<List<Race>> call = NetworkClient.getInstance().getRestApi() .getCockRaces(Application.getInstance().getToken(), cock!=null?cock.getID():null); call.enqueue(new Callback<List<Race>>() { @Override public void onResponse(Call<List<Race>> call, Response<List<Race>> response) { BaseActivity.showProgress((HomeActivity)getActivity(), false); if (response.isSuccessful()) { Log.d(TAG, "getCockRaces: done!"); racesList.clear(); racesList.addAll(response.body()); fillRaces(); } else{ Log.d(TAG, "getCockRaces: error = " + response.headers().get(Constants.STATUS_MESSAGE)); BaseActivity.showWarning((HomeActivity)getActivity(), response.headers().get(Constants.STATUS_MESSAGE)); } } @Override public void onFailure(Call<List<Race>> call, Throwable t) { BaseActivity.showProgress((HomeActivity)getActivity(), false); Log.d(TAG, "getCockRaces: error = " + t.toString()); if (t instanceof NoInternetException) { BaseActivity.showWarning((HomeActivity)getActivity(), getString(R.string.error_no_internet)); } else{ BaseActivity.showWarning((HomeActivity)getActivity(), getString(R.string.server_request_error)); } } }); } private void setAllStuff() { double [] starts = new double[racesList.size()+2];//{0, 50, 60, 20, 0}; double [] strengths = new double[racesList.size()+2];//{0, 50, 10, 40, 0}; double [] speeds = new double[racesList.size()+2];//{0, 50, 22, 34, 0}; double [] balances = new double[racesList.size()+2];//{0, 12, 1, 42, 0}; double [] positions = new double[racesList.size()+2];//{0, 45, 32, 24, 0}; for (int i=1; i<=racesList.size(); i++){ Race race = racesList.get(racesList.size()-i); starts[i] = race.start_style; strengths[i] = race.strength; speeds[i] = race.speed; balances[i] = race.balance; positions[i] = race.position; } List<Entry> entries1 = new ArrayList<Entry>(); List<Entry> entries2 = new ArrayList<Entry>(); List<Entry> entries3 = new ArrayList<Entry>(); List<Entry> entries4 = new ArrayList<Entry>(); List<Entry> entries5 = new ArrayList<Entry>(); for (int i=0; i<starts.length; i++) { entries1.add(new Entry(i+1, (float)starts[i])); entries2.add(new Entry(i+1, (float)strengths[i])); entries3.add(new Entry(i+1, (float)speeds[i])); entries4.add(new Entry(i+1, (float)balances[i])); entries5.add(new Entry(i+1, (float)positions[i])); } LineData lineData = new LineData(); if (btnAll.isChecked() || btnStart.isChecked()){ LineDataSet dataSet1 = new LineDataSet(entries1, "Label1"); // add entries to dataset fillDataSet(dataSet1); dataSet1.setLineWidth(0.2f); dataSet1.setColor(getResources().getColor(R.color.start_style)); dataSet1.setFillColor(getResources().getColor(R.color.start_style)); dataSet1.setFillAlpha(204); lineData.addDataSet(dataSet1); } if (btnAll.isChecked() || btnStrength.isChecked()){ LineDataSet dataSet2 = new LineDataSet(entries2, "Label2"); // add entries to dataset fillDataSet(dataSet2); dataSet2.setLineWidth(0.2f); dataSet2.setColor(getResources().getColor(R.color.strength)); dataSet2.setFillColor(getResources().getColor(R.color.strength)); dataSet2.setFillAlpha(204); lineData.addDataSet(dataSet2); } if (btnAll.isChecked() || btnSpeed.isChecked()){ LineDataSet dataSet3 = new LineDataSet(entries3, "Label3"); // add entries to dataset fillDataSet(dataSet3); dataSet3.setLineWidth(0.2f); dataSet3.setColor(getResources().getColor(R.color.speed)); dataSet3.setFillColor(getResources().getColor(R.color.speed)); dataSet3.setFillAlpha(204); lineData.addDataSet(dataSet3); } if (btnAll.isChecked() || btnBalance.isChecked()){ LineDataSet dataSet4 = new LineDataSet(entries4, "Label4"); // add entries to dataset fillDataSet(dataSet4); dataSet4.setLineWidth(0.2f); dataSet4.setColor(getResources().getColor(R.color.balance)); dataSet4.setFillColor(getResources().getColor(R.color.balance)); dataSet4.setFillAlpha(204); lineData.addDataSet(dataSet4); } if (btnAll.isChecked() || btnPosition.isChecked()){ LineDataSet dataSet5 = new LineDataSet(entries5, "Label5"); // add entries to dataset fillDataSet(dataSet5); dataSet5.setLineWidth(0.2f); dataSet5.setColor(getResources().getColor(R.color.position)); dataSet5.setFillColor(getResources().getColor(R.color.position)); dataSet5.setFillAlpha(204); lineData.addDataSet(dataSet5); } fillLineChart(lineData); } void fillDataSet(LineDataSet dataSet){ dataSet.setDrawValues(false); dataSet.setDrawCircles(false); dataSet.setDrawFilled(true); dataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); dataSet.setCubicIntensity(0.6f); dataSet.setFillAlpha(0xff); } void fillLineChart(LineData lineData){ lineChart.getXAxis().setAxisMinimum(1); lineChart.setTouchEnabled(false); lineChart.setDragEnabled(false); lineChart.setScaleEnabled(false); lineChart.setScaleXEnabled(false); lineChart.setScaleYEnabled(false); lineChart.setPinchZoom(false); lineChart.setDoubleTapToZoomEnabled(false); lineChart.setDragDecelerationEnabled(false); lineChart.setHighlightPerDragEnabled(false); lineChart.setHighlightPerTapEnabled(false); lineChart.getAxisLeft().setEnabled(true); lineChart.getAxisLeft().setDrawAxisLine(false); lineChart.getAxisLeft().setLabelCount(5); lineChart.getAxisRight().setEnabled(false); lineChart.getAxisRight().setDrawLabels(false); lineChart.getAxisLeft().setDrawGridLines(false); lineChart.getAxisLeft().setDrawLabels(true); lineChart.getXAxis().setDrawGridLines(false); lineChart.getXAxis().setDrawAxisLine(false); lineChart.setLogEnabled(false); lineChart.getLegend().setEnabled(false); lineChart.getDescription().setEnabled(false); lineChart.getAxisLeft().setSpaceBottom(0); lineChart.getAxisLeft().setAxisMinimum(0); lineChart.getAxisLeft().setXOffset(5); lineChart.getAxisLeft().setYOffset(0); lineChart.getAxisLeft().setStartAtZero(true); lineChart.getAxisLeft().setAxisMinValue(0); lineChart.getXAxis().setDrawGridLines(false); lineChart.getXAxis().setDrawAxisLine(false); lineChart.getXAxis().setEnabled(false); lineChart.getAxisRight().setSpaceBottom(0); lineChart.getAxisRight().setAxisMinimum(0); lineChart.getAxisRight().setXOffset(0); lineChart.getAxisRight().setYOffset(0); lineChart.getAxisRight().setStartAtZero(true); lineChart.getAxisRight().setAxisMinValue(0); lineChart.getXAxis().setXOffset(0); lineChart.getXAxis().setYOffset(0); lineChart.getAxisLeft().setTextColor(getResources().getColor(R.color.black)); lineChart.setDrawBorders(false); lineChart.setData(lineData); lineChart.invalidate(); } private void fillRaces() { if (racesList!=null && !racesList.isEmpty()){ racesHolder.removeAllViews(); int average = 0; for (Race race : racesList) { RaceItem item = new RaceItem(this, race); //item.setOnClickListener(this); racesHolder.addView(item); average += race.getRating(); } if (!racesList.isEmpty()) average /= racesList.size(); racesQuality.setText(""+average); if (racesList.size()>1) graphsHolder.setVisibility(View.VISIBLE); else graphsHolder.setVisibility(View.GONE); addRaceHolder.setVisibility(View.GONE); setAllStuff(); } else { graphsHolder.setVisibility(View.GONE); if (root.cock.getGender()==0) addRaceHolder.setVisibility(View.VISIBLE); } } @Override public void onResume() { super.onResume(); fillRaces(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.races_chart_all: btnAll.setChecked(true); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_start: btnAll.setChecked(false); btnStart.setChecked(true); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_strength: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(true); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_speed: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(true); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_balance: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(true); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_position: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(true); setAllStuff(); break; case R.id.add_race_button: addRace(); break; } } private void addRace() { Fragment fragment = getFragmentManager().findFragmentById(R.id.cock_fragment_holder); AddRaceFragment aR = new AddRaceFragment(); if (fragment!=null && fragment instanceof CockRacesFragment){ aR.setCock(((CockRacesFragment) fragment).getRoot().cock); getFragmentManager().beginTransaction() .addToBackStack("races").replace(R.id.cock_fragment_holder, aR).commit(); } } public void setRoot(CockFragment cockFragment) { this.root = cockFragment; if (root!=null && root.cock!=null) this.cock = root.cock; } public CockFragment getRoot() { return root; } }
UTF-8
Java
16,361
java
CockRacesFragment.java
Java
[ { "context": "ack;\nimport retrofit2.Response;\n\n/**\n * Created by Mr.Dzyga on 07.07.2018.\n */\npublic class CockRacesFragment", "end": 1152, "score": 0.9981501698493958, "start": 1144, "tag": "USERNAME", "value": "Mr.Dzyga" } ]
null
[]
package com.gallosdata.fragment.cock; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.gallosdata.Application; import com.gallosdata.Constants; import com.gallosdata.R; import com.gallosdata.activity.BaseActivity; import com.gallosdata.activity.HomeActivity; import com.gallosdata.fragment.BaseFragment; import com.gallosdata.model.Cock; import com.gallosdata.model.Race; import com.gallosdata.net.NetworkClient; import com.gallosdata.net.NoInternetException; import com.gallosdata.view.GraphMenuItem; import com.gallosdata.view.RaceItem; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Mr.Dzyga on 07.07.2018. */ public class CockRacesFragment extends BaseFragment implements View.OnClickListener { private static final String TAG = "CockRacesFragment"; private LinearLayout racesHolder, graphsHolder, addRaceHolder; private List<Race> racesList = new ArrayList<>(); private LineChart lineChart; private GraphMenuItem btnAll, btnStart, btnStrength, btnSpeed, btnBalance, btnPosition; private Cock cock; private CockFragment root; private TextView emptyView, addRace, racesQuality; @Override public void onCreate(Bundle bundle){ super.onCreate(bundle); } @Override public void onDestroy() { super.onDestroy(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_cock_races, container, false); racesHolder = (LinearLayout)rootView.findViewById(R.id.cock_races_holder); graphsHolder = (LinearLayout)rootView.findViewById(R.id.races_graphs); addRaceHolder = (LinearLayout)rootView.findViewById(R.id.add_race_button_holder); btnAll = (GraphMenuItem)rootView.findViewById(R.id.races_chart_all); btnStart = (GraphMenuItem)rootView.findViewById(R.id.races_chart_start); btnStrength = (GraphMenuItem)rootView.findViewById(R.id.races_chart_strength); btnSpeed = (GraphMenuItem)rootView.findViewById(R.id.races_chart_speed); btnBalance = (GraphMenuItem)rootView.findViewById(R.id.races_chart_balance); btnPosition = (GraphMenuItem)rootView.findViewById(R.id.races_chart_position); racesQuality = (TextView)rootView.findViewById(R.id.races_average_quality); emptyView = (TextView)rootView.findViewById(R.id.races_empty_view); addRace = (TextView)rootView.findViewById(R.id.add_race_button); addRace.setOnClickListener(this); btnAll.setOnClickListener(this); btnStart.setOnClickListener(this); btnStrength.setOnClickListener(this); btnSpeed.setOnClickListener(this); btnBalance.setOnClickListener(this); btnPosition.setOnClickListener(this); HomeActivity activity = (HomeActivity) getActivity(); if (activity!=null) activity.setToolbarItems(true, root.cock.getID()<0?getString(R.string.add_cock):root.cock.getName(), false, root.cock.getGender()==0?getString(R.string.add_race):null); lineChart = (LineChart)rootView.findViewById(R.id.races_chart); //setAllStuff(); if (root.cock.getGender()!=0){ emptyView.setText(getText(R.string.female_cannot_have_races)); graphsHolder.setVisibility(View.GONE); addRaceHolder.setVisibility(View.GONE); } // fillRaces(); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (root.cock.getGender()==0) getRaces(); } private void getRaces() { BaseActivity.showProgress((HomeActivity)getActivity(), true); Call<List<Race>> call = NetworkClient.getInstance().getRestApi() .getCockRaces(Application.getInstance().getToken(), cock!=null?cock.getID():null); call.enqueue(new Callback<List<Race>>() { @Override public void onResponse(Call<List<Race>> call, Response<List<Race>> response) { BaseActivity.showProgress((HomeActivity)getActivity(), false); if (response.isSuccessful()) { Log.d(TAG, "getCockRaces: done!"); racesList.clear(); racesList.addAll(response.body()); fillRaces(); } else{ Log.d(TAG, "getCockRaces: error = " + response.headers().get(Constants.STATUS_MESSAGE)); BaseActivity.showWarning((HomeActivity)getActivity(), response.headers().get(Constants.STATUS_MESSAGE)); } } @Override public void onFailure(Call<List<Race>> call, Throwable t) { BaseActivity.showProgress((HomeActivity)getActivity(), false); Log.d(TAG, "getCockRaces: error = " + t.toString()); if (t instanceof NoInternetException) { BaseActivity.showWarning((HomeActivity)getActivity(), getString(R.string.error_no_internet)); } else{ BaseActivity.showWarning((HomeActivity)getActivity(), getString(R.string.server_request_error)); } } }); } private void setAllStuff() { double [] starts = new double[racesList.size()+2];//{0, 50, 60, 20, 0}; double [] strengths = new double[racesList.size()+2];//{0, 50, 10, 40, 0}; double [] speeds = new double[racesList.size()+2];//{0, 50, 22, 34, 0}; double [] balances = new double[racesList.size()+2];//{0, 12, 1, 42, 0}; double [] positions = new double[racesList.size()+2];//{0, 45, 32, 24, 0}; for (int i=1; i<=racesList.size(); i++){ Race race = racesList.get(racesList.size()-i); starts[i] = race.start_style; strengths[i] = race.strength; speeds[i] = race.speed; balances[i] = race.balance; positions[i] = race.position; } List<Entry> entries1 = new ArrayList<Entry>(); List<Entry> entries2 = new ArrayList<Entry>(); List<Entry> entries3 = new ArrayList<Entry>(); List<Entry> entries4 = new ArrayList<Entry>(); List<Entry> entries5 = new ArrayList<Entry>(); for (int i=0; i<starts.length; i++) { entries1.add(new Entry(i+1, (float)starts[i])); entries2.add(new Entry(i+1, (float)strengths[i])); entries3.add(new Entry(i+1, (float)speeds[i])); entries4.add(new Entry(i+1, (float)balances[i])); entries5.add(new Entry(i+1, (float)positions[i])); } LineData lineData = new LineData(); if (btnAll.isChecked() || btnStart.isChecked()){ LineDataSet dataSet1 = new LineDataSet(entries1, "Label1"); // add entries to dataset fillDataSet(dataSet1); dataSet1.setLineWidth(0.2f); dataSet1.setColor(getResources().getColor(R.color.start_style)); dataSet1.setFillColor(getResources().getColor(R.color.start_style)); dataSet1.setFillAlpha(204); lineData.addDataSet(dataSet1); } if (btnAll.isChecked() || btnStrength.isChecked()){ LineDataSet dataSet2 = new LineDataSet(entries2, "Label2"); // add entries to dataset fillDataSet(dataSet2); dataSet2.setLineWidth(0.2f); dataSet2.setColor(getResources().getColor(R.color.strength)); dataSet2.setFillColor(getResources().getColor(R.color.strength)); dataSet2.setFillAlpha(204); lineData.addDataSet(dataSet2); } if (btnAll.isChecked() || btnSpeed.isChecked()){ LineDataSet dataSet3 = new LineDataSet(entries3, "Label3"); // add entries to dataset fillDataSet(dataSet3); dataSet3.setLineWidth(0.2f); dataSet3.setColor(getResources().getColor(R.color.speed)); dataSet3.setFillColor(getResources().getColor(R.color.speed)); dataSet3.setFillAlpha(204); lineData.addDataSet(dataSet3); } if (btnAll.isChecked() || btnBalance.isChecked()){ LineDataSet dataSet4 = new LineDataSet(entries4, "Label4"); // add entries to dataset fillDataSet(dataSet4); dataSet4.setLineWidth(0.2f); dataSet4.setColor(getResources().getColor(R.color.balance)); dataSet4.setFillColor(getResources().getColor(R.color.balance)); dataSet4.setFillAlpha(204); lineData.addDataSet(dataSet4); } if (btnAll.isChecked() || btnPosition.isChecked()){ LineDataSet dataSet5 = new LineDataSet(entries5, "Label5"); // add entries to dataset fillDataSet(dataSet5); dataSet5.setLineWidth(0.2f); dataSet5.setColor(getResources().getColor(R.color.position)); dataSet5.setFillColor(getResources().getColor(R.color.position)); dataSet5.setFillAlpha(204); lineData.addDataSet(dataSet5); } fillLineChart(lineData); } void fillDataSet(LineDataSet dataSet){ dataSet.setDrawValues(false); dataSet.setDrawCircles(false); dataSet.setDrawFilled(true); dataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER); dataSet.setCubicIntensity(0.6f); dataSet.setFillAlpha(0xff); } void fillLineChart(LineData lineData){ lineChart.getXAxis().setAxisMinimum(1); lineChart.setTouchEnabled(false); lineChart.setDragEnabled(false); lineChart.setScaleEnabled(false); lineChart.setScaleXEnabled(false); lineChart.setScaleYEnabled(false); lineChart.setPinchZoom(false); lineChart.setDoubleTapToZoomEnabled(false); lineChart.setDragDecelerationEnabled(false); lineChart.setHighlightPerDragEnabled(false); lineChart.setHighlightPerTapEnabled(false); lineChart.getAxisLeft().setEnabled(true); lineChart.getAxisLeft().setDrawAxisLine(false); lineChart.getAxisLeft().setLabelCount(5); lineChart.getAxisRight().setEnabled(false); lineChart.getAxisRight().setDrawLabels(false); lineChart.getAxisLeft().setDrawGridLines(false); lineChart.getAxisLeft().setDrawLabels(true); lineChart.getXAxis().setDrawGridLines(false); lineChart.getXAxis().setDrawAxisLine(false); lineChart.setLogEnabled(false); lineChart.getLegend().setEnabled(false); lineChart.getDescription().setEnabled(false); lineChart.getAxisLeft().setSpaceBottom(0); lineChart.getAxisLeft().setAxisMinimum(0); lineChart.getAxisLeft().setXOffset(5); lineChart.getAxisLeft().setYOffset(0); lineChart.getAxisLeft().setStartAtZero(true); lineChart.getAxisLeft().setAxisMinValue(0); lineChart.getXAxis().setDrawGridLines(false); lineChart.getXAxis().setDrawAxisLine(false); lineChart.getXAxis().setEnabled(false); lineChart.getAxisRight().setSpaceBottom(0); lineChart.getAxisRight().setAxisMinimum(0); lineChart.getAxisRight().setXOffset(0); lineChart.getAxisRight().setYOffset(0); lineChart.getAxisRight().setStartAtZero(true); lineChart.getAxisRight().setAxisMinValue(0); lineChart.getXAxis().setXOffset(0); lineChart.getXAxis().setYOffset(0); lineChart.getAxisLeft().setTextColor(getResources().getColor(R.color.black)); lineChart.setDrawBorders(false); lineChart.setData(lineData); lineChart.invalidate(); } private void fillRaces() { if (racesList!=null && !racesList.isEmpty()){ racesHolder.removeAllViews(); int average = 0; for (Race race : racesList) { RaceItem item = new RaceItem(this, race); //item.setOnClickListener(this); racesHolder.addView(item); average += race.getRating(); } if (!racesList.isEmpty()) average /= racesList.size(); racesQuality.setText(""+average); if (racesList.size()>1) graphsHolder.setVisibility(View.VISIBLE); else graphsHolder.setVisibility(View.GONE); addRaceHolder.setVisibility(View.GONE); setAllStuff(); } else { graphsHolder.setVisibility(View.GONE); if (root.cock.getGender()==0) addRaceHolder.setVisibility(View.VISIBLE); } } @Override public void onResume() { super.onResume(); fillRaces(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.races_chart_all: btnAll.setChecked(true); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_start: btnAll.setChecked(false); btnStart.setChecked(true); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_strength: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(true); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_speed: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(true); btnBalance.setChecked(false); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_balance: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(true); btnPosition.setChecked(false); setAllStuff(); break; case R.id.races_chart_position: btnAll.setChecked(false); btnStart.setChecked(false); btnStrength.setChecked(false); btnSpeed.setChecked(false); btnBalance.setChecked(false); btnPosition.setChecked(true); setAllStuff(); break; case R.id.add_race_button: addRace(); break; } } private void addRace() { Fragment fragment = getFragmentManager().findFragmentById(R.id.cock_fragment_holder); AddRaceFragment aR = new AddRaceFragment(); if (fragment!=null && fragment instanceof CockRacesFragment){ aR.setCock(((CockRacesFragment) fragment).getRoot().cock); getFragmentManager().beginTransaction() .addToBackStack("races").replace(R.id.cock_fragment_holder, aR).commit(); } } public void setRoot(CockFragment cockFragment) { this.root = cockFragment; if (root!=null && root.cock!=null) this.cock = root.cock; } public CockFragment getRoot() { return root; } }
16,361
0.623739
0.613593
391
40.84399
25.515629
129
false
false
0
0
0
0
0
0
0.88491
false
false
4
74cb92f97b25ff2d6a1a79f73ff6cc635a81b385
26,456,998,580,807
010beb91555b28e29b08aec6b56bbcfd00b1a0b2
/app/src/main/java/com/smedialink/abakarmagomedov/githubapplication/presentation/UserPostActivity/UserPostActivity.java
9f615cdaeae422ead1f5d5396ef92d1ef3061d90
[]
no_license
jumpstreet13/GithubApplication
https://github.com/jumpstreet13/GithubApplication
3172308718a6b17be71da00effcce810fea704b6
1cbd82fca88f88e048e7c4ef4349b4eb54839fdd
refs/heads/master
2022-10-20T18:37:11.948000
2022-10-10T15:57:22
2022-10-10T15:57:22
91,343,862
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smedialink.abakarmagomedov.githubapplication.presentation.UserPostActivity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import com.smedialink.abakarmagomedov.githubapplication.App; import com.smedialink.abakarmagomedov.githubapplication.BaseActivity; import com.smedialink.abakarmagomedov.githubapplication.Constants; import com.smedialink.abakarmagomedov.githubapplication.R; import com.smedialink.abakarmagomedov.githubapplication.adapters.PostsAdapter; import com.smedialink.abakarmagomedov.githubapplication.data.entity.Repository; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; public class UserPostActivity extends BaseActivity implements UserPostView, PostsAdapter.RepoClickListener { @Inject UserPostPresenter presenter; @BindView(R.id.bottomSheet) View bottomSheet; @BindView(R.id.repos_recyclerview) RecyclerView reposRecycler; @BindView(R.id.forks) TextView forks; @BindView(R.id.stars) TextView stars; @BindView(R.id.watchers) TextView watchers; @BindView(R.id.info) TextView info; private PostsAdapter adapter; private BottomSheetBehavior mBottomSheetBehavior; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_post); ButterKnife.bind(this); App.getApp(this).getComponentsHolder().getUserPostComponent().inject(this); presenter.attachView(this); presenter.getRepos(getIntent().getStringExtra(Constants.LOGIN)); mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); } @Override public void fetchData(List<Repository> reposList) { adapter = new PostsAdapter(reposList, this); reposRecycler.setLayoutManager(new LinearLayoutManager(this)); reposRecycler.setAdapter(adapter); } @Override public void showDialog() { showProgress(); } @Override public void hideDialog() { hideProgress(); } @Override public void error() { getErrorDialog().show(); } @Override public void userClicked(Integer watchers, Integer forks, Integer stars, String info) { this.watchers.setText(String.valueOf(watchers)); this.forks.setText(forks + ""); this.stars.setText(stars + ""); this.info.setText(info); mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } @Override protected void onDestroy() { super.onDestroy(); hideProgress(); if (isFinishing()) { App.getApp(this).getComponentsHolder().releaseUserPostComponent(); presenter.detachView(); } } }
UTF-8
Java
3,237
java
UserPostActivity.java
Java
[]
null
[]
package com.smedialink.abakarmagomedov.githubapplication.presentation.UserPostActivity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import com.smedialink.abakarmagomedov.githubapplication.App; import com.smedialink.abakarmagomedov.githubapplication.BaseActivity; import com.smedialink.abakarmagomedov.githubapplication.Constants; import com.smedialink.abakarmagomedov.githubapplication.R; import com.smedialink.abakarmagomedov.githubapplication.adapters.PostsAdapter; import com.smedialink.abakarmagomedov.githubapplication.data.entity.Repository; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; public class UserPostActivity extends BaseActivity implements UserPostView, PostsAdapter.RepoClickListener { @Inject UserPostPresenter presenter; @BindView(R.id.bottomSheet) View bottomSheet; @BindView(R.id.repos_recyclerview) RecyclerView reposRecycler; @BindView(R.id.forks) TextView forks; @BindView(R.id.stars) TextView stars; @BindView(R.id.watchers) TextView watchers; @BindView(R.id.info) TextView info; private PostsAdapter adapter; private BottomSheetBehavior mBottomSheetBehavior; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_post); ButterKnife.bind(this); App.getApp(this).getComponentsHolder().getUserPostComponent().inject(this); presenter.attachView(this); presenter.getRepos(getIntent().getStringExtra(Constants.LOGIN)); mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); } @Override public void fetchData(List<Repository> reposList) { adapter = new PostsAdapter(reposList, this); reposRecycler.setLayoutManager(new LinearLayoutManager(this)); reposRecycler.setAdapter(adapter); } @Override public void showDialog() { showProgress(); } @Override public void hideDialog() { hideProgress(); } @Override public void error() { getErrorDialog().show(); } @Override public void userClicked(Integer watchers, Integer forks, Integer stars, String info) { this.watchers.setText(String.valueOf(watchers)); this.forks.setText(forks + ""); this.stars.setText(stars + ""); this.info.setText(info); mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); } @Override protected void onDestroy() { super.onDestroy(); hideProgress(); if (isFinishing()) { App.getApp(this).getComponentsHolder().releaseUserPostComponent(); presenter.detachView(); } } }
3,237
0.742972
0.741427
98
32.030613
26.403252
108
false
false
0
0
0
0
0
0
0.602041
false
false
4
04f95726833634cdf94a5dbe55c4a182feb31e62
24,094,766,592,605
7b4ce451b8a7b5017ca7832db8e2bd85cf318bb5
/nuwa/src/main/java/cn/asany/nuwa/app/domain/LayoutSettings.java
aa79633a4b0db98c32bb258832d6045d51cb6269
[]
no_license
limaofeng/shanhai
https://github.com/limaofeng/shanhai
b9b1f3713edd7d3b5daaae22c0ee5c5650ea1f29
9a36b1e9fcc96822cd270171f314bdea0e679d59
refs/heads/master
2023-04-04T18:48:56.375000
2023-01-06T06:22:16
2023-01-06T06:22:16
347,710,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.asany.nuwa.app.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; /** * 布局设置 * * @author limaofeng */ @Data @Embeddable @SuperBuilder @NoArgsConstructor @AllArgsConstructor public class LayoutSettings implements Serializable { /** 不使用默认布局 */ @Builder.Default @Column(name = "PURE", length = 1) private Boolean pure = false; /** 隐藏菜单栏 */ @Builder.Default @Column(name = "HIDE_MENU", length = 1) private Boolean hideMenu = false; }
UTF-8
Java
702
java
LayoutSettings.java
Java
[ { "context": "erimental.SuperBuilder;\n\n/**\n * 布局设置\n *\n * @author limaofeng\n */\n@Data\n@Embeddable\n@SuperBuilder\n@NoArgsConstr", "end": 321, "score": 0.9994357228279114, "start": 312, "tag": "USERNAME", "value": "limaofeng" } ]
null
[]
package cn.asany.nuwa.app.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; /** * 布局设置 * * @author limaofeng */ @Data @Embeddable @SuperBuilder @NoArgsConstructor @AllArgsConstructor public class LayoutSettings implements Serializable { /** 不使用默认布局 */ @Builder.Default @Column(name = "PURE", length = 1) private Boolean pure = false; /** 隐藏菜单栏 */ @Builder.Default @Column(name = "HIDE_MENU", length = 1) private Boolean hideMenu = false; }
702
0.752239
0.749254
31
20.612904
14.05445
53
false
false
0
0
0
0
0
0
0.419355
false
false
4
6e05888289d6a5fac02f40b38f968d262d16919b
4,629,974,745,941
05d0a9553358fbf159e566c403626de2718e17c9
/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/main/java/org/apache/hadoop/yarn/server/router/webapp/NodesBlock.java
720302e5a0d839da3f35fa5abf58f1f34411ad79
[ "CC-BY-2.5", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "EPL-1.0", "Classpath-exception-2.0", "GCC-exception-3.1", "BSD-3-Clause", "CC-PDDC", "GPL-2.0-only", "CDDL-1.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "GPL-1.0-or-later", "LicenseRef-scancode-jdom", "LicenseRef-scancode-proprietary-license", "BSD-2-Clause-Views", "MPL-2.0-no-copyleft-exception", "MPL-2.0", "CC-BY-3.0", "AGPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause", "CDDL-1.1", "LicenseRef-scancode-protobuf", "LGPL-2.1-or-later", "LGPL-2.0-or-later", "LicenseRef-scancode-oracle-bcl-javase-javafx-2012", "LGPL-2.0-only", "LicenseRef-scancode-unknown" ]
permissive
hopshadoop/hops
https://github.com/hopshadoop/hops
d8baaf20bc418af460e582974839a3a9a72f173a
ed0d4de3dadbde5afa12899e703954aa67db7b3b
refs/heads/master
2023-08-31T20:36:31.212000
2023-08-28T15:31:37
2023-08-28T15:31:37
32,975,439
295
85
Apache-2.0
false
2023-09-05T09:19:57
2015-03-27T08:31:42
2023-08-21T05:46:22
2023-09-05T09:19:56
156,037
281
79
53
Java
false
false
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.router.webapp; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWSConsts; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeInfo; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodesInfo; import org.apache.hadoop.yarn.server.router.Router; import org.apache.hadoop.yarn.util.Times; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet.TABLE; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet.TBODY; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet.TR; import org.apache.hadoop.yarn.webapp.util.WebAppUtils; import org.apache.hadoop.yarn.webapp.view.HtmlBlock; import com.google.inject.Inject; /** * Nodes block for the Router Web UI. */ public class NodesBlock extends HtmlBlock { private static final long BYTES_IN_MB = 1024 * 1024; private final Router router; @Inject NodesBlock(Router router, ViewContext ctx) { super(ctx); this.router = router; } @Override protected void render(Block html) { // Get the node info from the federation Configuration conf = this.router.getConfig(); String webAppAddress = WebAppUtils.getRouterWebAppURLWithScheme(conf); NodesInfo nodes = RouterWebServiceUtil.genericForward(webAppAddress, null, NodesInfo.class, HTTPMethods.GET, RMWSConsts.RM_WEB_SERVICE_PATH + RMWSConsts.NODES, null, null); setTitle("Nodes"); TBODY<TABLE<Hamlet>> tbody = html.table("#nodes").thead().tr() .th(".nodelabels", "Node Labels") .th(".rack", "Rack") .th(".state", "Node State") .th(".nodeaddress", "Node Address") .th(".nodehttpaddress", "Node HTTP Address") .th(".lastHealthUpdate", "Last health-update") .th(".healthReport", "Health-report") .th(".containers", "Containers") .th(".mem", "Mem Used") .th(".mem", "Mem Avail") .th(".vcores", "VCores Used") .th(".vcores", "VCores Avail") .th(".nodeManagerVersion", "Version") .__().__().tbody(); // Add nodes to the web UI for (NodeInfo info : nodes.getNodes()) { int usedMemory = (int) info.getUsedMemory(); int availableMemory = (int) info.getAvailableMemory(); TR<TBODY<TABLE<Hamlet>>> row = tbody.tr(); row.td().__(StringUtils.join(",", info.getNodeLabels())).__(); row.td().__(info.getRack()).__(); row.td().__(info.getState()).__(); row.td().__(info.getNodeId()).__(); boolean isInactive = false; if (isInactive) { row.td().__("N/A").__(); } else { String httpAddress = info.getNodeHTTPAddress(); row.td().a("//" + httpAddress, httpAddress).__(); } row.td().br().$title(String.valueOf(info.getLastHealthUpdate())).__() .__(Times.format(info.getLastHealthUpdate())).__() .td(info.getHealthReport()) .td(String.valueOf(info.getNumContainers())).td().br() .$title(String.valueOf(usedMemory)).__() .__(StringUtils.byteDesc(usedMemory * BYTES_IN_MB)).__().td().br() .$title(String.valueOf(availableMemory)).__() .__(StringUtils.byteDesc(availableMemory * BYTES_IN_MB)).__() .td(String.valueOf(info.getUsedVirtualCores())) .td(String.valueOf(info.getAvailableVirtualCores())) .td(info.getVersion()).__(); } tbody.__().__(); } }
UTF-8
Java
4,332
java
NodesBlock.java
Java
[]
null
[]
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.router.webapp; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWSConsts; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeInfo; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodesInfo; import org.apache.hadoop.yarn.server.router.Router; import org.apache.hadoop.yarn.util.Times; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet.TABLE; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet.TBODY; import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet.TR; import org.apache.hadoop.yarn.webapp.util.WebAppUtils; import org.apache.hadoop.yarn.webapp.view.HtmlBlock; import com.google.inject.Inject; /** * Nodes block for the Router Web UI. */ public class NodesBlock extends HtmlBlock { private static final long BYTES_IN_MB = 1024 * 1024; private final Router router; @Inject NodesBlock(Router router, ViewContext ctx) { super(ctx); this.router = router; } @Override protected void render(Block html) { // Get the node info from the federation Configuration conf = this.router.getConfig(); String webAppAddress = WebAppUtils.getRouterWebAppURLWithScheme(conf); NodesInfo nodes = RouterWebServiceUtil.genericForward(webAppAddress, null, NodesInfo.class, HTTPMethods.GET, RMWSConsts.RM_WEB_SERVICE_PATH + RMWSConsts.NODES, null, null); setTitle("Nodes"); TBODY<TABLE<Hamlet>> tbody = html.table("#nodes").thead().tr() .th(".nodelabels", "Node Labels") .th(".rack", "Rack") .th(".state", "Node State") .th(".nodeaddress", "Node Address") .th(".nodehttpaddress", "Node HTTP Address") .th(".lastHealthUpdate", "Last health-update") .th(".healthReport", "Health-report") .th(".containers", "Containers") .th(".mem", "Mem Used") .th(".mem", "Mem Avail") .th(".vcores", "VCores Used") .th(".vcores", "VCores Avail") .th(".nodeManagerVersion", "Version") .__().__().tbody(); // Add nodes to the web UI for (NodeInfo info : nodes.getNodes()) { int usedMemory = (int) info.getUsedMemory(); int availableMemory = (int) info.getAvailableMemory(); TR<TBODY<TABLE<Hamlet>>> row = tbody.tr(); row.td().__(StringUtils.join(",", info.getNodeLabels())).__(); row.td().__(info.getRack()).__(); row.td().__(info.getState()).__(); row.td().__(info.getNodeId()).__(); boolean isInactive = false; if (isInactive) { row.td().__("N/A").__(); } else { String httpAddress = info.getNodeHTTPAddress(); row.td().a("//" + httpAddress, httpAddress).__(); } row.td().br().$title(String.valueOf(info.getLastHealthUpdate())).__() .__(Times.format(info.getLastHealthUpdate())).__() .td(info.getHealthReport()) .td(String.valueOf(info.getNumContainers())).td().br() .$title(String.valueOf(usedMemory)).__() .__(StringUtils.byteDesc(usedMemory * BYTES_IN_MB)).__().td().br() .$title(String.valueOf(availableMemory)).__() .__(StringUtils.byteDesc(availableMemory * BYTES_IN_MB)).__() .td(String.valueOf(info.getUsedVirtualCores())) .td(String.valueOf(info.getAvailableVirtualCores())) .td(info.getVersion()).__(); } tbody.__().__(); } }
4,332
0.662742
0.659049
109
38.743118
23.753862
78
false
false
0
0
0
0
0
0
0.59633
false
false
4
c692ba92ac945665f7300d4cc3aea99ff900f016
4,629,974,747,560
34b7035c92e01c3fe74e6fb5b1174f1e07358212
/Serializer.java
d8be3f6ae5280c131b2e197a1f8a3a039e9a5a55
[]
no_license
ghodulik95/DataMiningProject
https://github.com/ghodulik95/DataMiningProject
d9b6fb63360b4e8ebe36cb3a3ac2da3bfd1f7e54
75a12d2ebec784037ca4b1778803bf4b3c2e398d
refs/heads/master
2016-09-06T13:24:45.174000
2015-04-22T04:17:36
2015-04-22T04:17:36
33,423,452
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Serializer { public void serializeClusters(List<Cluster> clus){ try{ int i = 1; for(Cluster c : clus){ FileOutputStream fout = new FileOutputStream("Clusters"+(i++)+".ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(c); oos.close(); } System.out.println("Done"); }catch(Exception ex){ ex.printStackTrace(); } } @SuppressWarnings("unchecked") public List< Cluster> deserializeClusters(){ List<Cluster> clus = new ArrayList<Cluster>(); try{ int i = 1; while(true){ FileInputStream fin = new FileInputStream("Clusters"+(i++)+".ser"); ObjectInputStream ois = new ObjectInputStream(fin); clus.add( (Cluster) ois.readObject()); ois.close(); } }catch(FileNotFoundException ex){ return clus; }catch(Exception ex){ ex.printStackTrace(); return null; } } }
UTF-8
Java
1,193
java
Serializer.java
Java
[]
null
[]
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Serializer { public void serializeClusters(List<Cluster> clus){ try{ int i = 1; for(Cluster c : clus){ FileOutputStream fout = new FileOutputStream("Clusters"+(i++)+".ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(c); oos.close(); } System.out.println("Done"); }catch(Exception ex){ ex.printStackTrace(); } } @SuppressWarnings("unchecked") public List< Cluster> deserializeClusters(){ List<Cluster> clus = new ArrayList<Cluster>(); try{ int i = 1; while(true){ FileInputStream fin = new FileInputStream("Clusters"+(i++)+".ser"); ObjectInputStream ois = new ObjectInputStream(fin); clus.add( (Cluster) ois.readObject()); ois.close(); } }catch(FileNotFoundException ex){ return clus; }catch(Exception ex){ ex.printStackTrace(); return null; } } }
1,193
0.676446
0.674769
48
23.854166
18.812662
74
false
false
0
0
0
0
0
0
2.333333
false
false
4
da1be92ed464b12822bc416fd4ff2dc3e32eaacd
19,980,187,931,512
ddf671d16a8bea0adbdfd05b2436c83968b4a5aa
/src/main/java/com/flns/autotab/DatabaseGUI.java
d5ecdf6c3b8022b982860c9388c2ea83040578b4
[ "Unlicense" ]
permissive
VarunAnanth2003/AutoTAB
https://github.com/VarunAnanth2003/AutoTAB
e4a9f5906a545829ed1d0aa505d8fd518017dbc6
54b4cc80524fd8c981dd986d462d22cc6ae5a875
refs/heads/main
2023-03-13T15:19:51.906000
2021-03-08T18:14:57
2021-03-08T18:14:57
345,524,794
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.flns.autotab; import java.awt.*; import javax.swing.*; public class DatabaseGUI { public static void displayList(Point oldPos) { String[][] dbData = ConnectionHandler.pullData(); final JFrame mainFrame = new JFrame("MIDItoTAB"); mainFrame.setSize(600,400); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainFrame.setResizable(false); mainFrame.setLayout(new BorderLayout()); mainFrame.setLocation(oldPos); JButton ex = new JButton("Exit"); ex.addActionListener(e -> { RunnerGUI.executeGUI(mainFrame.getLocation()); mainFrame.dispose(); }); ex.setMaximumSize(new Dimension(100, 30)); ex.setAlignmentX(Component.CENTER_ALIGNMENT); JLabel jlb = new JLabel("All TABs:"); jlb.setAlignmentX(Component.CENTER_ALIGNMENT); JPanel mainPanel = new JPanel(); mainPanel.setBounds(50, 50, 500, 300); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); mainPanel.add(Box.createVerticalStrut(10)); mainPanel.add(ex); mainPanel.add(Box.createVerticalStrut(40)); mainPanel.add(jlb); mainPanel.add(Box.createVerticalStrut(10)); for (int i = 0; i < dbData.length; i++) { final JButton b = new JButton(dbData[i][1]); b.putClientProperty("ID", dbData[i][0]); b.putClientProperty("name", dbData[i][1]); b.putClientProperty("tabString", dbData[i][2]); b.setAlignmentX(Component.CENTER_ALIGNMENT); Dimension buttonDim = new Dimension(400, 30); b.setMaximumSize(buttonDim); b.addActionListener(e -> { TABDisplayGUIDB.displayTab(mainFrame.getLocation(), (String) b.getClientProperty("ID"), (String) b.getClientProperty("name"), (String) b.getClientProperty("tabString")); mainFrame.dispose(); }); mainPanel.add(b); mainPanel.add(Box.createVerticalStrut(10)); } JScrollPane jsp = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); mainFrame.add(jsp); mainFrame.setVisible(true); } }
UTF-8
Java
2,279
java
DatabaseGUI.java
Java
[]
null
[]
package com.flns.autotab; import java.awt.*; import javax.swing.*; public class DatabaseGUI { public static void displayList(Point oldPos) { String[][] dbData = ConnectionHandler.pullData(); final JFrame mainFrame = new JFrame("MIDItoTAB"); mainFrame.setSize(600,400); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainFrame.setResizable(false); mainFrame.setLayout(new BorderLayout()); mainFrame.setLocation(oldPos); JButton ex = new JButton("Exit"); ex.addActionListener(e -> { RunnerGUI.executeGUI(mainFrame.getLocation()); mainFrame.dispose(); }); ex.setMaximumSize(new Dimension(100, 30)); ex.setAlignmentX(Component.CENTER_ALIGNMENT); JLabel jlb = new JLabel("All TABs:"); jlb.setAlignmentX(Component.CENTER_ALIGNMENT); JPanel mainPanel = new JPanel(); mainPanel.setBounds(50, 50, 500, 300); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); mainPanel.add(Box.createVerticalStrut(10)); mainPanel.add(ex); mainPanel.add(Box.createVerticalStrut(40)); mainPanel.add(jlb); mainPanel.add(Box.createVerticalStrut(10)); for (int i = 0; i < dbData.length; i++) { final JButton b = new JButton(dbData[i][1]); b.putClientProperty("ID", dbData[i][0]); b.putClientProperty("name", dbData[i][1]); b.putClientProperty("tabString", dbData[i][2]); b.setAlignmentX(Component.CENTER_ALIGNMENT); Dimension buttonDim = new Dimension(400, 30); b.setMaximumSize(buttonDim); b.addActionListener(e -> { TABDisplayGUIDB.displayTab(mainFrame.getLocation(), (String) b.getClientProperty("ID"), (String) b.getClientProperty("name"), (String) b.getClientProperty("tabString")); mainFrame.dispose(); }); mainPanel.add(b); mainPanel.add(Box.createVerticalStrut(10)); } JScrollPane jsp = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); mainFrame.add(jsp); mainFrame.setVisible(true); } }
2,279
0.629223
0.612111
54
41.203705
30.848722
185
false
false
0
0
0
0
0
0
1.074074
false
false
4
0942d28a6f98241b458f5d6050398ea4b294a29a
27,547,920,291,429
d38344ea9dd4ba45909644e7f6d34c7919a43477
/src/main/java/br/com/imaginativo/itcm/repository/ParcelaRepository.java
f15ef831c7c076c27d175443996e06f8c0a14b9a
[ "MIT" ]
permissive
le4ndro/ITCM
https://github.com/le4ndro/ITCM
ebce17878eaefff6e166746caaf3862a2d1b7ea8
3e4b6bd4eb46715f8bfb6967c347f008deea0c6f
refs/heads/master
2021-01-24T11:45:25.182000
2019-02-12T22:42:36
2019-02-12T22:42:36
123,099,871
0
0
null
false
2018-02-27T08:52:17
2018-02-27T08:46:57
2018-02-27T08:51:01
2018-02-27T08:52:17
0
0
0
0
HTML
false
null
package br.com.imaginativo.itcm.repository; import org.springframework.data.repository.CrudRepository; import br.com.imaginativo.itcm.model.Parcela; public interface ParcelaRepository extends CrudRepository<Parcela, Long> { }
UTF-8
Java
230
java
ParcelaRepository.java
Java
[]
null
[]
package br.com.imaginativo.itcm.repository; import org.springframework.data.repository.CrudRepository; import br.com.imaginativo.itcm.model.Parcela; public interface ParcelaRepository extends CrudRepository<Parcela, Long> { }
230
0.830435
0.830435
9
24.555555
28.457029
74
false
false
0
0
0
0
0
0
0.444444
false
false
4
0e1994ba6c2495cf8168c963a4e153553ef2f135
28,793,460,752,618
d24664bc477b98b7682ab3f6443152071b1073c7
/graph-command-service/src/main/java/com/stackroute/graphcommandservice/Model/User.java
ccbefd512e82c80af17caa2eb71776dd8f93e435
[]
no_license
HemaTalluru/wholesome-care
https://github.com/HemaTalluru/wholesome-care
83cab8adc62df53c8956829c1870bc56344a3e4a
a08415d4066254538358817e958c21e2bbc46abb
refs/heads/main
2023-06-21T00:19:40.917000
2021-07-25T15:59:41
2021-07-25T15:59:41
389,377,271
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stackroute.graphcommandservice.Model; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.neo4j.core.schema.Node; @Data @Node public class User { @Id private String email; private String password; private String role; private String name; private String age; private String place; private String gender; private String imageUrl; }
UTF-8
Java
451
java
User.java
Java
[]
null
[]
package com.stackroute.graphcommandservice.Model; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.neo4j.core.schema.Node; @Data @Node public class User { @Id private String email; private String password; private String role; private String name; private String age; private String place; private String gender; private String imageUrl; }
451
0.707317
0.7051
21
19.476191
16.290865
55
false
false
0
0
0
0
0
0
0.571429
false
false
4
5320b88cb99b033ff5801e827c78324e8f0dde22
17,617,955,904,356
9bbf702a0f17829b3f55e363fd9979e9412e8324
/app/src/main/java/com/salgado/jorge/keymanky/procesodeventa/Principal.java
6ece614d02a9f676330162d8e78abd73cf7fcfdd
[]
no_license
victormanuelfrancodev/la_loma
https://github.com/victormanuelfrancodev/la_loma
477a36cd87d0c61346751ac0b4d014f00029b34f
293661d6ba91ebea6e675090da3cc45f03b2b771
refs/heads/master
2020-03-16T16:28:16.365000
2018-05-11T19:06:59
2018-05-11T19:06:59
132,789,173
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.salgado.jorge.keymanky.procesodeventa; import android.Manifest; import android.annotation.SuppressLint; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.webkit.CookieManager; import android.webkit.DownloadListener; import android.webkit.URLUtil; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ArrayAdapter; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.json.JSONException; import org.json.JSONObject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.Retrofit.Builder; import retrofit2.converter.gson.GsonConverterFactory; import static java.security.AccessController.getContext; @SuppressLint({"SetJavaScriptEnabled"}) public class Principal extends AppCompatActivity { private static final String DEVICE_ADDRESS_END = ")"; private static final String DEVICE_ADDRESS_START = " ("; public static final int RC_STORAGE = 55; private static final int REQUEST_CODE_ACTION_PICK = 2; private static final int REQUEST_CODE_BLUETOOTH = 1; JavaScriptInterface Jinterface; private final String TAG_REQUEST = "MY_TAG"; private ArrayAdapter<CharSequence> arrayAdapter; private final ArrayList<CharSequence> bondedDevices = new ArrayList(); public static final String KEY_CONNECTIONS = "KEY_CONNECTIONS"; private int brightness = 50; public WebView browser; private int compress = 0; private BroadcastReceiver deliveredStatusReceiver; private String logicalName; private BroadcastReceiver sentStatusReceiver; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //requestPermissionLocation(); setContentView((int) R.layout.activity_principal); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); if (VERSION.SDK_INT >= 19 && (getApplicationInfo().flags & 2) != 0) { WebView.setWebContentsDebuggingEnabled(true); } this.browser = (WebView) findViewById(R.id.browser); WebSettings webSettings = this.browser.getSettings(); webSettings.setJavaScriptEnabled(true); this.browser.setWebViewClient(new WebViewClient()); this.Jinterface = new JavaScriptInterface(this, this.browser); this.browser.addJavascriptInterface(this.Jinterface, "javascript_obj"); this.browser.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { super.onPageFinished(Principal.this.browser, url); Principal.this.injectFunction(); } public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { view.loadUrl("/sdcard/htdocs/rutas/error.php"); Principal.this.startActivity(Principal.this.getPackageManager().getLaunchIntentForPackage("ru.kslabs.ksweb")); view.loadUrl("http://localhost:8080/rutas/index.php"); Principal.this.browser.loadUrl("http://www.websitehere.php"); view.loadUrl("/sdcard/htdocs/rutas/error.php"); } }); webSettings.setDomStorageEnabled(true); this.browser.setWebChromeClient(new WebChromeClient()); this.browser.loadUrl("http://localhost:8080/rutas/index.php"); webSettings.setBuiltInZoomControls(true); webSettings.setSupportZoom(true); this.browser.setInitialScale(105); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_principal, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.base) { startActivity(getPackageManager().getLaunchIntentForPackage("ru.kslabs.ksweb")); return true; } else if (id == R.id.menu) { this.browser.loadUrl("http://localhost:8080/rutas/menu.php"); return true; } else if (id == R.id.ventas) { this.browser.loadUrl("http://localhost:8080/rutas/3.2.php"); return true; } else if (id == R.id.conecta_gps) { startActivity(getPackageManager().getLaunchIntentForPackage("fr.herverenault.selfhostedgpstracker")); return true; } else if (id == R.id.consulta_gps) { this.browser.loadUrl("http://localhost:8080/gps/index.php"); return true; } else if (id == R.id.imprimir) { startActivity(getPackageManager().getLaunchIntentForPackage("com.bixolon.webprint")); return true; } else if (id == R.id.blue) { startActivityForResult(new Intent("android.settings.BLUETOOTH_SETTINGS"), 1); return true; } else if (id == R.id.conectar) { Intent i = new Intent(this, Imprimir.class); i.putExtra("url", this.browser.getUrl().toString()); startActivity(i); return true; } else if (id == R.id.actualizar) { showToast(""); this.browser.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { final Request request = new Request(Uri.parse("http://187.176.24.218:88/gps.rar")); request.allowScanningByMediaScanner(); request.setMimeType(mimetype); request.addRequestHeader("cookie", CookieManager.getInstance().getCookie("http://187.176.24.218:888/gps.rar")); request.addRequestHeader("User-Agent", userAgent); Principal.this.showToast(""); request.setDescription("Downloading file..."); request.setTitle(URLUtil.guessFileName("http://187.176.24.218:888/gps.rar", contentDisposition, mimetype)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(1); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName("http://187.176.24.218:88/gps.rar", contentDisposition, mimetype)); final DownloadManager dm = (DownloadManager) Principal.this.getSystemService("download"); new Thread("Browser download") { public void run() { dm.enqueue(request); } }.start(); Principal.this.showToast(""); if (!JavaScriptInterface.longitudeGPS.toString().isEmpty() || !JavaScriptInterface.latitudeGPS.toString().isEmpty() || !JavaScriptInterface.usuario3.isEmpty()) { JSONObject json = new JSONObject(); try { json.put("username", "DCP001"); json.put("password", "02b2de20e8981444cb9a57a6621acf0bcd95693daab029549b0b0c2ab8248a2c"); json.put("useragent", "Android tracker v0.8"); } catch (JSONException e) { e.printStackTrace(); } ((ManagerService) new Builder().baseUrl("https://www.apps-sellcom-dev.com/LALOMA_CENTRAL-web/").addConverterFactory(GsonConverterFactory.create()).build().create(ManagerService.class)).setConfirmar(RequestBody.create( MediaType.parse("application/json; charset=utf-8"), json.toString())).enqueue(new Callback<ResponseBody>() { /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void onResponse(retrofit2.Call<okhttp3.ResponseBody> r19, retrofit2.Response<okhttp3.ResponseBody> r20) { throw new UnsupportedOperationException("Method not decompiled: com.salgado.jorge.keymanky.procesodeventa.Principal.2.2.onResponse(retrofit2.Call, retrofit2.Response):void"); } public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } } }); showToast(""); String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null); Type type = new TypeToken< ArrayList < Ruta >>() {}.getType(); ArrayList < Ruta > rutasObject = new Gson().fromJson(connectionsJSONString, type); for (int i=0; i< rutasObject.size(); i++) { Ruta ruta = VariablesGlobales.rutas.get(i); JSONObject json = new JSONObject(); try { json.put("clientID", ruta.clienteId); json.put("route", ruta.route); json.put("onDate", ruta.onDate); json.put("endDate", ruta.endDate); json.put("checkinLocation", ruta.checkinLocation); } catch (JSONException e) { e.printStackTrace(); } Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.apps-sellcom-dev.com/LALOMA_CENTRAL-web/").addConverterFactory(GsonConverterFactory.create()).build(); ManagerService managerService = retrofit.create(ManagerService.class); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString()); managerService.setInsertar("e1c35bf0594ac92177406e4ef28d46f671a00fafb7347b880a7a42450e4bbad0", "3122d44f-3900-45be-9709-0d4d5a05aad2", requestBody).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } return true; } else { /* if (id == R.id.lectorCodigo) { startActivity(new Intent(this, LectorDeBarras.class)); }*/ return super.onOptionsItemSelected(item); } } private void showToast(String msg) { } private void injectFunction() { this.browser.loadUrl("javascript: window.androidObj.notificationA = function(identificador,identificador2) { javascript_obj.ejecutarGPS(identificador,identificador2) }"); } public void onDestroy() { super.onDestroy(); this.browser.removeJavascriptInterface("javascript_obj"); } }
UTF-8
Java
12,088
java
Principal.java
Java
[ { "context": "l Request request = new Request(Uri.parse(\"http://187.176.24.218:88/gps.rar\"));\r\n request.allow", "end": 6506, "score": 0.9996382594108582, "start": 6492, "tag": "IP_ADDRESS", "value": "187.176.24.218" }, { "context": "e\", CookieManager.getInstance().getCookie(\"http://187.176.24.218:888/gps.rar\"));\r\n request.addR", "end": 6750, "score": 0.9996259808540344, "start": 6736, "tag": "IP_ADDRESS", "value": "187.176.24.218" }, { "context": " request.setTitle(URLUtil.guessFileName(\"http://187.176.24.218:888/gps.rar\", contentDisposition, mimetype));\r\n ", "end": 7040, "score": 0.9996277093887329, "start": 7026, "tag": "IP_ADDRESS", "value": "187.176.24.218" }, { "context": "IRECTORY_DOWNLOADS, URLUtil.guessFileName(\"http://187.176.24.218:88/gps.rar\", contentDisposition, mimetype));\r\n ", "end": 7346, "score": 0.999629020690918, "start": 7332, "tag": "IP_ADDRESS", "value": "187.176.24.218" }, { "context": " json.put(\"username\", \"DCP001\");\r\n json.put(\"passwor", "end": 8094, "score": 0.9995249509811401, "start": 8088, "tag": "USERNAME", "value": "DCP001" }, { "context": " json.put(\"password\", \"02b2de20e8981444cb9a57a6621acf0bcd95693daab029549b0b0c2ab8248a2c\");\r\n json.put(\"userage", "end": 8213, "score": 0.9882164597511292, "start": 8149, "tag": "PASSWORD", "value": "02b2de20e8981444cb9a57a6621acf0bcd95693daab029549b0b0c2ab8248a2c" } ]
null
[]
package com.salgado.jorge.keymanky.procesodeventa; import android.Manifest; import android.annotation.SuppressLint; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.webkit.CookieManager; import android.webkit.DownloadListener; import android.webkit.URLUtil; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ArrayAdapter; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.json.JSONException; import org.json.JSONObject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.Retrofit.Builder; import retrofit2.converter.gson.GsonConverterFactory; import static java.security.AccessController.getContext; @SuppressLint({"SetJavaScriptEnabled"}) public class Principal extends AppCompatActivity { private static final String DEVICE_ADDRESS_END = ")"; private static final String DEVICE_ADDRESS_START = " ("; public static final int RC_STORAGE = 55; private static final int REQUEST_CODE_ACTION_PICK = 2; private static final int REQUEST_CODE_BLUETOOTH = 1; JavaScriptInterface Jinterface; private final String TAG_REQUEST = "MY_TAG"; private ArrayAdapter<CharSequence> arrayAdapter; private final ArrayList<CharSequence> bondedDevices = new ArrayList(); public static final String KEY_CONNECTIONS = "KEY_CONNECTIONS"; private int brightness = 50; public WebView browser; private int compress = 0; private BroadcastReceiver deliveredStatusReceiver; private String logicalName; private BroadcastReceiver sentStatusReceiver; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //requestPermissionLocation(); setContentView((int) R.layout.activity_principal); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); if (VERSION.SDK_INT >= 19 && (getApplicationInfo().flags & 2) != 0) { WebView.setWebContentsDebuggingEnabled(true); } this.browser = (WebView) findViewById(R.id.browser); WebSettings webSettings = this.browser.getSettings(); webSettings.setJavaScriptEnabled(true); this.browser.setWebViewClient(new WebViewClient()); this.Jinterface = new JavaScriptInterface(this, this.browser); this.browser.addJavascriptInterface(this.Jinterface, "javascript_obj"); this.browser.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { super.onPageFinished(Principal.this.browser, url); Principal.this.injectFunction(); } public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { view.loadUrl("/sdcard/htdocs/rutas/error.php"); Principal.this.startActivity(Principal.this.getPackageManager().getLaunchIntentForPackage("ru.kslabs.ksweb")); view.loadUrl("http://localhost:8080/rutas/index.php"); Principal.this.browser.loadUrl("http://www.websitehere.php"); view.loadUrl("/sdcard/htdocs/rutas/error.php"); } }); webSettings.setDomStorageEnabled(true); this.browser.setWebChromeClient(new WebChromeClient()); this.browser.loadUrl("http://localhost:8080/rutas/index.php"); webSettings.setBuiltInZoomControls(true); webSettings.setSupportZoom(true); this.browser.setInitialScale(105); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_principal, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.base) { startActivity(getPackageManager().getLaunchIntentForPackage("ru.kslabs.ksweb")); return true; } else if (id == R.id.menu) { this.browser.loadUrl("http://localhost:8080/rutas/menu.php"); return true; } else if (id == R.id.ventas) { this.browser.loadUrl("http://localhost:8080/rutas/3.2.php"); return true; } else if (id == R.id.conecta_gps) { startActivity(getPackageManager().getLaunchIntentForPackage("fr.herverenault.selfhostedgpstracker")); return true; } else if (id == R.id.consulta_gps) { this.browser.loadUrl("http://localhost:8080/gps/index.php"); return true; } else if (id == R.id.imprimir) { startActivity(getPackageManager().getLaunchIntentForPackage("com.bixolon.webprint")); return true; } else if (id == R.id.blue) { startActivityForResult(new Intent("android.settings.BLUETOOTH_SETTINGS"), 1); return true; } else if (id == R.id.conectar) { Intent i = new Intent(this, Imprimir.class); i.putExtra("url", this.browser.getUrl().toString()); startActivity(i); return true; } else if (id == R.id.actualizar) { showToast(""); this.browser.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { final Request request = new Request(Uri.parse("http://192.168.3.11:88/gps.rar")); request.allowScanningByMediaScanner(); request.setMimeType(mimetype); request.addRequestHeader("cookie", CookieManager.getInstance().getCookie("http://192.168.3.11:888/gps.rar")); request.addRequestHeader("User-Agent", userAgent); Principal.this.showToast(""); request.setDescription("Downloading file..."); request.setTitle(URLUtil.guessFileName("http://192.168.3.11:888/gps.rar", contentDisposition, mimetype)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(1); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName("http://192.168.3.11:88/gps.rar", contentDisposition, mimetype)); final DownloadManager dm = (DownloadManager) Principal.this.getSystemService("download"); new Thread("Browser download") { public void run() { dm.enqueue(request); } }.start(); Principal.this.showToast(""); if (!JavaScriptInterface.longitudeGPS.toString().isEmpty() || !JavaScriptInterface.latitudeGPS.toString().isEmpty() || !JavaScriptInterface.usuario3.isEmpty()) { JSONObject json = new JSONObject(); try { json.put("username", "DCP001"); json.put("password", "<PASSWORD>"); json.put("useragent", "Android tracker v0.8"); } catch (JSONException e) { e.printStackTrace(); } ((ManagerService) new Builder().baseUrl("https://www.apps-sellcom-dev.com/LALOMA_CENTRAL-web/").addConverterFactory(GsonConverterFactory.create()).build().create(ManagerService.class)).setConfirmar(RequestBody.create( MediaType.parse("application/json; charset=utf-8"), json.toString())).enqueue(new Callback<ResponseBody>() { /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public void onResponse(retrofit2.Call<okhttp3.ResponseBody> r19, retrofit2.Response<okhttp3.ResponseBody> r20) { throw new UnsupportedOperationException("Method not decompiled: com.salgado.jorge.keymanky.procesodeventa.Principal.2.2.onResponse(retrofit2.Call, retrofit2.Response):void"); } public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } } }); showToast(""); String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null); Type type = new TypeToken< ArrayList < Ruta >>() {}.getType(); ArrayList < Ruta > rutasObject = new Gson().fromJson(connectionsJSONString, type); for (int i=0; i< rutasObject.size(); i++) { Ruta ruta = VariablesGlobales.rutas.get(i); JSONObject json = new JSONObject(); try { json.put("clientID", ruta.clienteId); json.put("route", ruta.route); json.put("onDate", ruta.onDate); json.put("endDate", ruta.endDate); json.put("checkinLocation", ruta.checkinLocation); } catch (JSONException e) { e.printStackTrace(); } Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.apps-sellcom-dev.com/LALOMA_CENTRAL-web/").addConverterFactory(GsonConverterFactory.create()).build(); ManagerService managerService = retrofit.create(ManagerService.class); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString()); managerService.setInsertar("e1c35bf0594ac92177406e4ef28d46f671a00fafb7347b880a7a42450e4bbad0", "3122d44f-3900-45be-9709-0d4d5a05aad2", requestBody).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } return true; } else { /* if (id == R.id.lectorCodigo) { startActivity(new Intent(this, LectorDeBarras.class)); }*/ return super.onOptionsItemSelected(item); } } private void showToast(String msg) { } private void injectFunction() { this.browser.loadUrl("javascript: window.androidObj.notificationA = function(identificador,identificador2) { javascript_obj.ejecutarGPS(identificador,identificador2) }"); } public void onDestroy() { super.onDestroy(); this.browser.removeJavascriptInterface("javascript_obj"); } }
12,026
0.619209
0.600265
244
47.549179
39.306614
241
false
false
0
0
0
0
64
0.010589
0.848361
false
false
4
d2a87f478ad90383daabb3b85ab1f00b8fd90e83
14,078,902,846,859
e6780ad4381901d1ae35d9b39d4a067b56e891e2
/app/src/main/java/com/stingluc/booksearch/data/source/local/DBBookSearch.java
07cd536c40fd813ba6c57d0b50b6ac4064046ba0
[]
no_license
slucana08/BookSearchUpdate
https://github.com/slucana08/BookSearchUpdate
485d91f84882af8fa1777ff231873287c8aa2196
10b44cfafe1804c7130603b08e237145d18fb922
refs/heads/master
2020-08-01T22:18:50.525000
2019-09-26T16:38:27
2019-09-26T16:38:27
211,123,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stingluc.booksearch.data.source.local; import android.content.Context; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; import com.stingluc.booksearch.data.entities.Book; import com.stingluc.booksearch.data.source.local.dao.DaoBook; @Database(entities = {Book.class},version = 1,exportSchema = false) public abstract class DBBookSearch extends RoomDatabase { public abstract DaoBook daoBook(); private static volatile DBBookSearch INSTANCE; public static DBBookSearch getDatabase(Context context){ if (INSTANCE == null){ synchronized (DBBookSearch.class){ if (INSTANCE == null){ INSTANCE = Room.databaseBuilder(context,DBBookSearch.class,"DBBookSearch") .addCallback(sCallBack) .build(); } } } return INSTANCE; } private static RoomDatabase.Callback sCallBack = new RoomDatabase.Callback(){ @Override public void onOpen(@NonNull SupportSQLiteDatabase db) { super.onOpen(db); } }; }
UTF-8
Java
1,248
java
DBBookSearch.java
Java
[]
null
[]
package com.stingluc.booksearch.data.source.local; import android.content.Context; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; import com.stingluc.booksearch.data.entities.Book; import com.stingluc.booksearch.data.source.local.dao.DaoBook; @Database(entities = {Book.class},version = 1,exportSchema = false) public abstract class DBBookSearch extends RoomDatabase { public abstract DaoBook daoBook(); private static volatile DBBookSearch INSTANCE; public static DBBookSearch getDatabase(Context context){ if (INSTANCE == null){ synchronized (DBBookSearch.class){ if (INSTANCE == null){ INSTANCE = Room.databaseBuilder(context,DBBookSearch.class,"DBBookSearch") .addCallback(sCallBack) .build(); } } } return INSTANCE; } private static RoomDatabase.Callback sCallBack = new RoomDatabase.Callback(){ @Override public void onOpen(@NonNull SupportSQLiteDatabase db) { super.onOpen(db); } }; }
1,248
0.661859
0.661058
41
29.439024
25.122189
94
false
false
0
0
0
0
0
0
0.463415
false
false
4
de9e4cd3b50b936b1a980cba8fd586c463d10fc6
23,287,312,698,653
1945327218e118acac69fbff83b2f7ceccee8854
/control/eventbuilders/NewMostCrowdedJunctionEventBuilder.java
d496f870332f18511ed48d7b8bc5e43ba02021cb
[]
no_license
AlvaroFuentesSolas/Traffic-Simulator
https://github.com/AlvaroFuentesSolas/Traffic-Simulator
1fe845fbf0766645b0bb0a9ff657333c7c426c27
67a733c6adfcb37def2366ac515170b1123ad63c
refs/heads/main
2023-07-19T12:55:08.790000
2021-09-05T18:18:47
2021-09-05T18:18:47
403,272,115
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.ucm.fdi.control.eventbuilders; import es.ucm.fdi.ini.IniSection; import es.ucm.fdi.model.Event; import es.ucm.fdi.model.NewMostCrowededJunctionEvent; public class NewMostCrowdedJunctionEventBuilder extends EventBuilder { public NewMostCrowdedJunctionEventBuilder() { // TODO NewMostCrowdedJunctionEventBuilder NewMostCrowdedJunctionEventBuilder implementar constructor } @Override public Event parse(IniSection is) { // TODO NewMostCrowdedJunctionEventBuilder comprobar la validez de los valores if(!is.getTag().equals(this.tag)) return null; String id = is.getValue("id"); Integer time = Integer.parseInt(is.getValue("time")); return new NewMostCrowededJunctionEvent(time, id); } @Override public String toString() { // TODO NewMostCrowdedJunctionEventBuilder toString necesita especificion return super.toString(); } }
UTF-8
Java
961
java
NewMostCrowdedJunctionEventBuilder.java
Java
[]
null
[]
package es.ucm.fdi.control.eventbuilders; import es.ucm.fdi.ini.IniSection; import es.ucm.fdi.model.Event; import es.ucm.fdi.model.NewMostCrowededJunctionEvent; public class NewMostCrowdedJunctionEventBuilder extends EventBuilder { public NewMostCrowdedJunctionEventBuilder() { // TODO NewMostCrowdedJunctionEventBuilder NewMostCrowdedJunctionEventBuilder implementar constructor } @Override public Event parse(IniSection is) { // TODO NewMostCrowdedJunctionEventBuilder comprobar la validez de los valores if(!is.getTag().equals(this.tag)) return null; String id = is.getValue("id"); Integer time = Integer.parseInt(is.getValue("time")); return new NewMostCrowededJunctionEvent(time, id); } @Override public String toString() { // TODO NewMostCrowdedJunctionEventBuilder toString necesita especificion return super.toString(); } }
961
0.711759
0.711759
32
29.03125
29.230211
109
false
false
0
0
0
0
0
0
0.3125
false
false
4
17dcd0849e654425736ef02832d6a04d4efa1d5d
20,787,641,760,212
46be43fab4095c6945ffcba1b3bcfe49e90d23e6
/src/simpledb/IntGroupAggregator.java
ba299800882e69dfbd1e347ef405adb2cdeffacf
[]
no_license
krylenkom/SimpleDB
https://github.com/krylenkom/SimpleDB
e060d1e458938836e2a87416bb21820e001dcdfc
a29084437156b9cef9afd29722d376d166286aec
refs/heads/master
2021-01-23T15:03:04.414000
2014-04-09T12:47:44
2014-04-09T12:47:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package simpledb; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Knows how to compute some aggregate over a set of IntFields and group by field. */ public class IntGroupAggregator implements Aggregator { private final int gbfield; private final TupleDesc tupleDesc; private final int afield; private final Op what; private final Map<Field, Integer> aggvalues; private final Map<Field, Integer> avgcounts; public IntGroupAggregator(int gbfield, Type gbfieldtype, int afield, Op what) { this.gbfield = gbfield; this.tupleDesc = new TupleDesc( new Type[]{ gbfieldtype, Type.INT_TYPE }, new String[] { "" + gbfield, Aggregate.aggName(what) + "_" + gbfield }); this.afield = afield; this.what = what; this.aggvalues = new HashMap<Field, Integer>(); this.avgcounts = new HashMap<Field, Integer>(); } @Override public void merge(Tuple tup) { Field field = tup.getField(gbfield); Integer old = aggvalues.get(field); int v = ((IntField) tup.getField(afield)).getValue(); if (null == old) { switch (this.what) { case AVG: this.avgcounts.put(field, 1); this.aggvalues.put(field, v); break; case COUNT: this.aggvalues.put(field, 1); break; default: this.aggvalues.put(field, v); break; } } else { switch (this.what) { case MIN: this.aggvalues.put(field, Math.min(old, v)); break; case MAX: this.aggvalues.put(field, Math.max(old, v)); break; case SUM: this.aggvalues.put(field, old + v); break; case COUNT: this.aggvalues.put(field, old + 1); break; case AVG: this.aggvalues.put(field, old + v); this.avgcounts.put(field, this.avgcounts.get(field) + 1); break; } } } @Override public DbIterator iterator() { return new AbstractDbIterator() { private Iterator<Field> inner; @Override protected Tuple readNext() throws DbException, TransactionAbortedException { Tuple t = new Tuple(tupleDesc); if (inner.hasNext()) { Field field = inner.next(); t.setField(0, field); t.setField(1, new IntField(getAggvalue(field))); return t; } else { return null; } } @Override public void open() throws DbException, TransactionAbortedException { this.inner = aggvalues.keySet().iterator(); } @Override public void rewind() throws DbException, TransactionAbortedException { open(); } @Override public TupleDesc getTupleDesc() { return tupleDesc; } }; } @Override public TupleDesc getTupleDesc() { return this.tupleDesc; } private int getAggvalue(Field field) { if (Op.AVG == this.what) { int count = this.avgcounts.get(field); return ((0 == count) ? (int) Double.POSITIVE_INFINITY : this.aggvalues.get(field) / count); } else { return this.aggvalues.get(field); } } }
UTF-8
Java
3,778
java
IntGroupAggregator.java
Java
[]
null
[]
package simpledb; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Knows how to compute some aggregate over a set of IntFields and group by field. */ public class IntGroupAggregator implements Aggregator { private final int gbfield; private final TupleDesc tupleDesc; private final int afield; private final Op what; private final Map<Field, Integer> aggvalues; private final Map<Field, Integer> avgcounts; public IntGroupAggregator(int gbfield, Type gbfieldtype, int afield, Op what) { this.gbfield = gbfield; this.tupleDesc = new TupleDesc( new Type[]{ gbfieldtype, Type.INT_TYPE }, new String[] { "" + gbfield, Aggregate.aggName(what) + "_" + gbfield }); this.afield = afield; this.what = what; this.aggvalues = new HashMap<Field, Integer>(); this.avgcounts = new HashMap<Field, Integer>(); } @Override public void merge(Tuple tup) { Field field = tup.getField(gbfield); Integer old = aggvalues.get(field); int v = ((IntField) tup.getField(afield)).getValue(); if (null == old) { switch (this.what) { case AVG: this.avgcounts.put(field, 1); this.aggvalues.put(field, v); break; case COUNT: this.aggvalues.put(field, 1); break; default: this.aggvalues.put(field, v); break; } } else { switch (this.what) { case MIN: this.aggvalues.put(field, Math.min(old, v)); break; case MAX: this.aggvalues.put(field, Math.max(old, v)); break; case SUM: this.aggvalues.put(field, old + v); break; case COUNT: this.aggvalues.put(field, old + 1); break; case AVG: this.aggvalues.put(field, old + v); this.avgcounts.put(field, this.avgcounts.get(field) + 1); break; } } } @Override public DbIterator iterator() { return new AbstractDbIterator() { private Iterator<Field> inner; @Override protected Tuple readNext() throws DbException, TransactionAbortedException { Tuple t = new Tuple(tupleDesc); if (inner.hasNext()) { Field field = inner.next(); t.setField(0, field); t.setField(1, new IntField(getAggvalue(field))); return t; } else { return null; } } @Override public void open() throws DbException, TransactionAbortedException { this.inner = aggvalues.keySet().iterator(); } @Override public void rewind() throws DbException, TransactionAbortedException { open(); } @Override public TupleDesc getTupleDesc() { return tupleDesc; } }; } @Override public TupleDesc getTupleDesc() { return this.tupleDesc; } private int getAggvalue(Field field) { if (Op.AVG == this.what) { int count = this.avgcounts.get(field); return ((0 == count) ? (int) Double.POSITIVE_INFINITY : this.aggvalues.get(field) / count); } else { return this.aggvalues.get(field); } } }
3,778
0.500794
0.498941
118
31.016949
22.806475
103
false
false
0
0
0
0
0
0
0.669492
false
false
4
3bbd8b99ff7a24f83510808616454305b805b32d
3,393,024,226,340
0e93b2d837c9ee0025638d2cddebfdf98dd136b7
/src/com/cjx913/sorter/Sorter.java
4f6544db2d4b4147f85ca3f0f5a0e9b23c9a880f
[]
no_license
cjx913/Custom
https://github.com/cjx913/Custom
6e26e6918524e8b38ad036a8067cf6269120956f
c642f11f5851201a79096ce3701bbb4b1a8e11dc
refs/heads/master
2020-04-07T11:20:29.929000
2018-11-20T02:51:18
2018-11-20T02:51:18
158,321,487
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cjx913.sorter; import java.util.Comparator; public interface Sorter { public <T extends Comparable<T>> void sort(T[] arr); public <T> void sort(T[] list, Comparator<T> arr); }
UTF-8
Java
193
java
Sorter.java
Java
[]
null
[]
package com.cjx913.sorter; import java.util.Comparator; public interface Sorter { public <T extends Comparable<T>> void sort(T[] arr); public <T> void sort(T[] list, Comparator<T> arr); }
193
0.715026
0.699482
9
20.444445
20.369427
53
false
false
0
0
0
0
0
0
0.777778
false
false
4
3d42c62ec40b24ba872106d2149bbed324ad33ad
33,406,255,633,998
5b1890905dcb6f2a9ce411be904721853c268d69
/Soporte/src/java/soporte/hibernate/dao/imp/EtiquetasDaoImp.java
64f0b49a4e6089224a058e800b0ade9d7538362a
[]
no_license
manerMoniar/Jsp
https://github.com/manerMoniar/Jsp
d14a6ede9b3cc8274332f6e5b06aa63fa5762f49
3b28bd646857cdba5fbf9711b40bb0135e694789
refs/heads/master
2016-09-06T10:56:00.363000
2013-08-27T21:45:09
2013-08-27T21:45:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package soporte.hibernate.dao.imp; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import soporte.hibernate.HibernateUtil; import soporte.hibernate.dao.EtiquetasDao; import soporte.hibernate.model.Etiquetas; import org.hibernate.criterion.Example; /** * * @author Wolf */ public class EtiquetasDaoImp implements EtiquetasDao { Query query; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction transaction; @Override public boolean createEtiquetas(Etiquetas object) { try{ transaction = session.beginTransaction(); session.save(object); transaction.commit(); return true; }catch (Exception e) { System.out.println("createEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return false; } } @Override public List<Etiquetas> retrieveEtiquetas() { try{ transaction = session.beginTransaction(); query = session.createQuery("FROM Etiquetas"); return query.list(); }catch (Exception e) { System.out.println("retrieveEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return null; } } @Override public boolean updateEtiquetas(Etiquetas object) { try{ transaction = session.beginTransaction(); session.update(object); transaction.commit(); return true; }catch (Exception e) { System.out.println("updateEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return false; } } @Override public boolean deleteEtiquetas(Etiquetas object) { try{ transaction = session.beginTransaction(); session.delete(object); transaction.commit(); return true; }catch (Exception e) { System.out.println("deleteEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return false; } } @Override public Etiquetas findById(int id) { try{ transaction = session.beginTransaction(); Etiquetas object = (Etiquetas) session.get("soporte.hibernate.model.Etiquetas", id); transaction.commit(); return object; }catch (Exception e) { System.out.println("findById Etiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return null; } } @Override public List<Etiquetas> findByCriteria(Etiquetas criteria) { try{ transaction = session.beginTransaction(); List<Etiquetas> objects = (List<Etiquetas>) session .createCriteria("soporte.hibernate.model.Etiquetas") .add(Example.create(criteria)) .list(); transaction.commit(); return objects; }catch (Exception e) { System.out.println("findByCriteria Etiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return null; } } }
UTF-8
Java
3,571
java
EtiquetasDaoImp.java
Java
[ { "context": "rg.hibernate.criterion.Example;\n\n/**\n *\n * @author Wolf\n */\npublic class EtiquetasDaoImp implements Etiqu", "end": 439, "score": 0.9935885667800903, "start": 435, "tag": "NAME", "value": "Wolf" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package soporte.hibernate.dao.imp; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import soporte.hibernate.HibernateUtil; import soporte.hibernate.dao.EtiquetasDao; import soporte.hibernate.model.Etiquetas; import org.hibernate.criterion.Example; /** * * @author Wolf */ public class EtiquetasDaoImp implements EtiquetasDao { Query query; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction transaction; @Override public boolean createEtiquetas(Etiquetas object) { try{ transaction = session.beginTransaction(); session.save(object); transaction.commit(); return true; }catch (Exception e) { System.out.println("createEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return false; } } @Override public List<Etiquetas> retrieveEtiquetas() { try{ transaction = session.beginTransaction(); query = session.createQuery("FROM Etiquetas"); return query.list(); }catch (Exception e) { System.out.println("retrieveEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return null; } } @Override public boolean updateEtiquetas(Etiquetas object) { try{ transaction = session.beginTransaction(); session.update(object); transaction.commit(); return true; }catch (Exception e) { System.out.println("updateEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return false; } } @Override public boolean deleteEtiquetas(Etiquetas object) { try{ transaction = session.beginTransaction(); session.delete(object); transaction.commit(); return true; }catch (Exception e) { System.out.println("deleteEtiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return false; } } @Override public Etiquetas findById(int id) { try{ transaction = session.beginTransaction(); Etiquetas object = (Etiquetas) session.get("soporte.hibernate.model.Etiquetas", id); transaction.commit(); return object; }catch (Exception e) { System.out.println("findById Etiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return null; } } @Override public List<Etiquetas> findByCriteria(Etiquetas criteria) { try{ transaction = session.beginTransaction(); List<Etiquetas> objects = (List<Etiquetas>) session .createCriteria("soporte.hibernate.model.Etiquetas") .add(Example.create(criteria)) .list(); transaction.commit(); return objects; }catch (Exception e) { System.out.println("findByCriteria Etiquetas exception"); System.out.println(e.getMessage()); transaction.rollback(); return null; } } }
3,571
0.589191
0.589191
118
29.262712
20.794567
96
false
false
0
0
0
0
0
0
0.525424
false
false
4
aaaf7f28284a4b9c299a502af3b2ada2b26c23e3
33,406,255,636,014
db62fc6f3ecdd357974a589193a24a1279ab3315
/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java
533a2f28b44d91ddc3c98303e56f0636dee2bafe
[ "Apache-2.0" ]
permissive
apache/mina-sshd
https://github.com/apache/mina-sshd
03672180b9aec9b211599a9522fcc501a437c21c
3739a8e23784c173f237b2da2a3f358233268d2b
refs/heads/master
2023-09-03T04:14:34.273000
2023-09-02T17:22:11
2023-09-02T17:22:11
688,360
742
353
Apache-2.0
false
2023-09-14T03:17:49
2010-05-26T23:38:08
2023-09-13T09:56:48
2023-09-12T19:22:59
19,212
744
326
28
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.server.config.keys; import java.io.IOException; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.security.GeneralSecurityException; import java.security.PublicKey; import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.sshd.common.config.keys.AuthorizedKeyEntry; import org.apache.sshd.common.config.keys.AuthorizedKeysTestSupport; import org.apache.sshd.common.config.keys.PublicKeyEntry; import org.apache.sshd.common.config.keys.PublicKeyEntryResolver; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.mockito.Mockito; /** * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AuthorizedKeysAuthenticatorTest extends AuthorizedKeysTestSupport { public AuthorizedKeysAuthenticatorTest() { super(); } @Test public void testAutomaticReload() throws Exception { Path file = getTempTargetRelativeFile(getCurrentTestName()); if (Files.exists(file)) { Files.delete(file); } AtomicInteger reloadCount = new AtomicInteger(0); PublickeyAuthenticator auth = new AuthorizedKeysAuthenticator(file) { @Override protected Collection<AuthorizedKeyEntry> reloadAuthorizedKeys( Path path, String username, ServerSession session) throws IOException, GeneralSecurityException { assertSame("Mismatched reload path", file, path); reloadCount.incrementAndGet(); return super.reloadAuthorizedKeys(path, username, session); } }; assertFalse("Unexpected authentication success for missing file " + file, auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null)); List<String> keyLines = loadDefaultSupportedKeys(); assertHierarchyTargetFolderExists(file.getParent()); while (keyLines.size() > 0) { try (Writer w = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { w.append(PublicKeyEntry.COMMENT_CHAR) .append(' ').append(getCurrentTestName()) .append(' ').append(String.valueOf(keyLines.size())).append(" remaining keys") .append(IoUtils.EOL); for (String l : keyLines) { w.append(l).append(IoUtils.EOL); } } Files.setLastModifiedTime(file, FileTime.from(Instant.now().minusSeconds(4))); List<AuthorizedKeyEntry> entries = AuthorizedKeyEntry.readAuthorizedKeys(file); assertEquals("Mismatched number of loaded entries", keyLines.size(), entries.size()); List<PublicKey> keySet = PublicKeyEntry.resolvePublicKeyEntries(null, entries, PublicKeyEntryResolver.FAILING); assertEquals("Mismatched number of loaded keys", entries.size(), keySet.size()); reloadCount.set(0); for (int index = 0; index < keySet.size(); index++) { PublicKey k = keySet.get(index); String keyData = keyLines.get(index); // we know they are 1-1 matching assertTrue("Failed to authenticate with key #" + (index + 1) + " " + k.getAlgorithm() + "[" + keyData + "] on file=" + file, auth.authenticate(getCurrentTestName(), k, null)); // we expect EXACTLY ONE re-load call since we did not modify the file during the authentication assertEquals("Unexpected keys re-loading of " + keyLines.size() + " remaining at key #" + (index + 1) + " on file=" + file, 1, reloadCount.get()); } keyLines.remove(0); } assertTrue("File no longer exists: " + file, Files.exists(file)); assertFalse("Unexpected authentication success for empty file " + file, auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null)); } }
UTF-8
Java
5,317
java
AuthorizedKeysAuthenticatorTest.java
Java
[ { "context": ".mockito.Mockito;\n\n/**\n * @author <a href=\"mailto:dev@mina.apache.org\">Apache MINA SSHD Project</a>\n */\n@FixMethodOrder", "end": 1841, "score": 0.9999330043792725, "start": 1822, "tag": "EMAIL", "value": "dev@mina.apache.org" } ]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.server.config.keys; import java.io.IOException; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.security.GeneralSecurityException; import java.security.PublicKey; import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.sshd.common.config.keys.AuthorizedKeyEntry; import org.apache.sshd.common.config.keys.AuthorizedKeysTestSupport; import org.apache.sshd.common.config.keys.PublicKeyEntry; import org.apache.sshd.common.config.keys.PublicKeyEntryResolver; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.mockito.Mockito; /** * @author <a href="mailto:<EMAIL>">Apache MINA SSHD Project</a> */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AuthorizedKeysAuthenticatorTest extends AuthorizedKeysTestSupport { public AuthorizedKeysAuthenticatorTest() { super(); } @Test public void testAutomaticReload() throws Exception { Path file = getTempTargetRelativeFile(getCurrentTestName()); if (Files.exists(file)) { Files.delete(file); } AtomicInteger reloadCount = new AtomicInteger(0); PublickeyAuthenticator auth = new AuthorizedKeysAuthenticator(file) { @Override protected Collection<AuthorizedKeyEntry> reloadAuthorizedKeys( Path path, String username, ServerSession session) throws IOException, GeneralSecurityException { assertSame("Mismatched reload path", file, path); reloadCount.incrementAndGet(); return super.reloadAuthorizedKeys(path, username, session); } }; assertFalse("Unexpected authentication success for missing file " + file, auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null)); List<String> keyLines = loadDefaultSupportedKeys(); assertHierarchyTargetFolderExists(file.getParent()); while (keyLines.size() > 0) { try (Writer w = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { w.append(PublicKeyEntry.COMMENT_CHAR) .append(' ').append(getCurrentTestName()) .append(' ').append(String.valueOf(keyLines.size())).append(" remaining keys") .append(IoUtils.EOL); for (String l : keyLines) { w.append(l).append(IoUtils.EOL); } } Files.setLastModifiedTime(file, FileTime.from(Instant.now().minusSeconds(4))); List<AuthorizedKeyEntry> entries = AuthorizedKeyEntry.readAuthorizedKeys(file); assertEquals("Mismatched number of loaded entries", keyLines.size(), entries.size()); List<PublicKey> keySet = PublicKeyEntry.resolvePublicKeyEntries(null, entries, PublicKeyEntryResolver.FAILING); assertEquals("Mismatched number of loaded keys", entries.size(), keySet.size()); reloadCount.set(0); for (int index = 0; index < keySet.size(); index++) { PublicKey k = keySet.get(index); String keyData = keyLines.get(index); // we know they are 1-1 matching assertTrue("Failed to authenticate with key #" + (index + 1) + " " + k.getAlgorithm() + "[" + keyData + "] on file=" + file, auth.authenticate(getCurrentTestName(), k, null)); // we expect EXACTLY ONE re-load call since we did not modify the file during the authentication assertEquals("Unexpected keys re-loading of " + keyLines.size() + " remaining at key #" + (index + 1) + " on file=" + file, 1, reloadCount.get()); } keyLines.remove(0); } assertTrue("File no longer exists: " + file, Files.exists(file)); assertFalse("Unexpected authentication success for empty file " + file, auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null)); } }
5,305
0.666541
0.663532
120
43.308334
31.625095
123
false
false
0
0
0
0
0
0
0.7
false
false
4
74f17446ca728ca1ca74bb93ecd3810f550f163c
16,398,185,204,652
8270cc7930afbf1e6354049999419d0b0a9974b0
/app/src/main/java/com/example/deeppatel/car_rerntal/Returning_Process/Car.java
ad7cf73886bae5633992cfde83b43ac84166b476
[ "MIT" ]
permissive
Sarthak1911/Karz-Admin-App
https://github.com/Sarthak1911/Karz-Admin-App
d5ef61c7a477443be34a2594772799da303f70b6
946d69acc0474c6416223eec6a9a91c8a9c03ca4
refs/heads/master
2020-05-16T12:51:01.516000
2019-04-17T18:09:23
2019-04-17T18:09:23
183,057,041
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.deeppatel.car_rerntal.Returning_Process; import android.graphics.Color; import java.io.Serializable; import java.util.Random; public class Car implements Serializable { private String car_name; private String car_model; private String booked_by; private String booked_on; private String available_on; private int color; public Car(String car_name, String car_model, String booked_by, String booked_on, String available_on) { this.car_name = car_name; this.car_model = car_model; this.booked_by = booked_by; this.booked_on = booked_on; this.available_on = available_on; this.color = getRandColor(); } public static int getRandColor(){ Random rnd = new Random(); return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); } public Car() { } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String getCar_name() { return car_name; } public void setCar_name(String car_name) { this.car_name = car_name; } public String getCar_model() { return car_model; } public String getBooked_by() { return booked_by; } public void setBooked_by(String booked_by) { this.booked_by = booked_by; } public String getBooked_on() { return booked_on; } public void setBooked_on(String booked_on) { this.booked_on = booked_on; } public String getAvailable_on() { return available_on; } public void setAvailable_on(String available_on) { this.available_on = available_on; } public void setCar_model(String car_model) { this.car_model = car_model; } }
UTF-8
Java
1,843
java
Car.java
Java
[]
null
[]
package com.example.deeppatel.car_rerntal.Returning_Process; import android.graphics.Color; import java.io.Serializable; import java.util.Random; public class Car implements Serializable { private String car_name; private String car_model; private String booked_by; private String booked_on; private String available_on; private int color; public Car(String car_name, String car_model, String booked_by, String booked_on, String available_on) { this.car_name = car_name; this.car_model = car_model; this.booked_by = booked_by; this.booked_on = booked_on; this.available_on = available_on; this.color = getRandColor(); } public static int getRandColor(){ Random rnd = new Random(); return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); } public Car() { } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String getCar_name() { return car_name; } public void setCar_name(String car_name) { this.car_name = car_name; } public String getCar_model() { return car_model; } public String getBooked_by() { return booked_by; } public void setBooked_by(String booked_by) { this.booked_by = booked_by; } public String getBooked_on() { return booked_on; } public void setBooked_on(String booked_on) { this.booked_on = booked_on; } public String getAvailable_on() { return available_on; } public void setAvailable_on(String available_on) { this.available_on = available_on; } public void setCar_model(String car_model) { this.car_model = car_model; } }
1,843
0.616929
0.610418
84
20.952381
20.769657
108
false
false
0
0
0
0
0
0
0.440476
false
false
4
6a9bcd4eafbe0eef82803a4b3bc7e26aa9372928
1,520,418,487,423
9d2823f141fb8b1a435362525fa4abcdb6ba3d65
/SampleChat/src/sample/Controller.java
3532cbf66005033896e66c0e4eaa093f18ece9fe
[]
no_license
HpcoderEg/Rept
https://github.com/HpcoderEg/Rept
2d40a7d8e5416d9ecba02ab24c6b8686198d4154
ac87483c385818ef8fb99de348d0937f7754c1ff
refs/heads/master
2020-04-25T04:41:40.600000
2019-04-27T17:45:42
2019-04-27T17:45:42
172,519,311
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; import javafx.fxml.FXML; import javafx.scene.*; import javafx.scene.control.Label; import javafx.scene.control.TextField; import java.io.*; import java.net.Socket; import java.util.Scanner; public class Controller extends Thread { Socket socket; @FXML public Label labelP; @FXML public void initialize() { try { socket = new Socket("localhost",9090); } catch (IOException e) { e.printStackTrace(); } new Controller().start(); } @FXML public void click() { Thread reader = new Thread(new ReaderC(socket,txt.getText())); reader.start(); Thread wreader = new Thread(new WriterC(socket)); wreader.start(); } @FXML public void mve() { System.out.println(texta); labelP.setText(labelP.getText() + "\n" + texta); } public static String texta; public TextField txt; @Override public void run() { // while (true) // { // labelP.setText(labelP.getText() + "\n" + texta); // } } } class ReaderC extends Thread {Socket _socket; String text; ReaderC(Socket socket,String _text) { _socket = socket; text = _text; } @Override public void run() { DataOutputStream dataOutputStream = null; try { dataOutputStream = new DataOutputStream(_socket.getOutputStream()); dataOutputStream.writeUTF(text); } catch (IOException e) { e.printStackTrace(); } } } class WriterC extends Thread {Socket _socket; WriterC(Socket socket) { _socket = socket; } @Override public void run() { while(true) { try { DataInputStream inputStream = new DataInputStream(_socket.getInputStream()); Controller.texta = inputStream.readUTF(); } catch (IOException e) { e.printStackTrace(); } } } }
UTF-8
Java
2,032
java
Controller.java
Java
[]
null
[]
package sample; import javafx.fxml.FXML; import javafx.scene.*; import javafx.scene.control.Label; import javafx.scene.control.TextField; import java.io.*; import java.net.Socket; import java.util.Scanner; public class Controller extends Thread { Socket socket; @FXML public Label labelP; @FXML public void initialize() { try { socket = new Socket("localhost",9090); } catch (IOException e) { e.printStackTrace(); } new Controller().start(); } @FXML public void click() { Thread reader = new Thread(new ReaderC(socket,txt.getText())); reader.start(); Thread wreader = new Thread(new WriterC(socket)); wreader.start(); } @FXML public void mve() { System.out.println(texta); labelP.setText(labelP.getText() + "\n" + texta); } public static String texta; public TextField txt; @Override public void run() { // while (true) // { // labelP.setText(labelP.getText() + "\n" + texta); // } } } class ReaderC extends Thread {Socket _socket; String text; ReaderC(Socket socket,String _text) { _socket = socket; text = _text; } @Override public void run() { DataOutputStream dataOutputStream = null; try { dataOutputStream = new DataOutputStream(_socket.getOutputStream()); dataOutputStream.writeUTF(text); } catch (IOException e) { e.printStackTrace(); } } } class WriterC extends Thread {Socket _socket; WriterC(Socket socket) { _socket = socket; } @Override public void run() { while(true) { try { DataInputStream inputStream = new DataInputStream(_socket.getInputStream()); Controller.texta = inputStream.readUTF(); } catch (IOException e) { e.printStackTrace(); } } } }
2,032
0.561516
0.559547
93
20.849463
18.662794
92
false
false
0
0
0
0
0
0
0.408602
false
false
4
258774e5ff8550b73ee695c2fa858a94873d69fc
8,658,654,125,283
5334c6f9d047dc6e8f2e4027e45bf9a86e7cc3e7
/src/connection/ClientAssistant.java
c05187a85237ed882aa23014f38d0502be84246c
[]
no_license
NetCrackerO2/ScheduleProject
https://github.com/NetCrackerO2/ScheduleProject
2f1e8a7a470b49988979b6ce1a08311995a18809
be6fd9f383cb921b6a16088928a064b953fb850e
refs/heads/master
2021-01-24T19:10:04.108000
2017-01-20T16:09:18
2017-01-20T16:09:18
72,648,864
2
1
null
false
2016-11-26T13:55:05
2016-11-02T14:39:51
2016-11-22T17:10:42
2016-11-26T13:55:05
232
1
1
10
Java
null
null
package connection; import java.io.IOException; import java.net.Socket; /** * Обеспечивает функционал клиентского соединения: * Соединение с единственным сервером; * Приём сообщений от сервера; * Отправка сообщений серверу. */ public class ClientAssistant implements ConnectionAssistant { private ConnectionManager connectionManager; private String serverAddres; private int serverPort; //============= public ClientAssistant() { //TODO: реализовать нормлаьную настройку соединения. serverAddres = "localhost"; serverPort = 4444; connectionManager = new ConnectionManager(); } @Override public void initialize() throws IOException { connectionManager.addNewConnection(new Socket(serverAddres, serverPort)); log("CLIENT_SERVER_CONNECTED"); } @Override public void stop() { connectionManager.closeAllConnections(); } //TODO: может проверять, что connectionIndex в сообщении == 0? //т.к. соединение только с сервером (его индекс = 0) @Override public void sendMessage(Message message) { connectionManager.sendMessage(message); } @Override public Message getNextMessage() { return connectionManager.getNextMessage(); } }
UTF-8
Java
1,509
java
ClientAssistant.java
Java
[]
null
[]
package connection; import java.io.IOException; import java.net.Socket; /** * Обеспечивает функционал клиентского соединения: * Соединение с единственным сервером; * Приём сообщений от сервера; * Отправка сообщений серверу. */ public class ClientAssistant implements ConnectionAssistant { private ConnectionManager connectionManager; private String serverAddres; private int serverPort; //============= public ClientAssistant() { //TODO: реализовать нормлаьную настройку соединения. serverAddres = "localhost"; serverPort = 4444; connectionManager = new ConnectionManager(); } @Override public void initialize() throws IOException { connectionManager.addNewConnection(new Socket(serverAddres, serverPort)); log("CLIENT_SERVER_CONNECTED"); } @Override public void stop() { connectionManager.closeAllConnections(); } //TODO: может проверять, что connectionIndex в сообщении == 0? //т.к. соединение только с сервером (его индекс = 0) @Override public void sendMessage(Message message) { connectionManager.sendMessage(message); } @Override public Message getNextMessage() { return connectionManager.getNextMessage(); } }
1,509
0.68716
0.68249
51
24.196079
21.970587
81
false
false
0
0
0
0
0
0
0.352941
false
false
4
348f8f218bc3e6fdbec5df4c80fdb07369d2bac1
7,052,336,316,491
08dc9d2df1f4ef94676da87d21ca919d48b1d2ac
/app/src/main/java/com/surfspotcheck/surfspotcheck/Activities/LoginEmail.java
cdf16d7c63e4f30341b008f2534d56ebad617a5a
[]
no_license
lerodrigs/SurfSpotCheck
https://github.com/lerodrigs/SurfSpotCheck
91462f7b3f9c0bde01a2a91c3b2b09151b00e430
e4286265f13e6077a4383e80e7992786ca212a2d
refs/heads/master
2020-12-02T11:33:12.606000
2018-01-09T01:14:39
2018-01-09T01:14:39
96,649,893
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.surfspotcheck.surfspotcheck.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.surfspotcheck.surfspotcheck.R; public class LoginEmail extends AppCompatActivity { TextView txt_email; TextView txt_pass; TextView forgot_pass; Button btnLogin; AppCompatActivity context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_email); context = this; txt_email = (TextView) findViewById(R.id.txt_email); txt_pass = (TextView) findViewById(R.id.txt_pass); forgot_pass = (TextView) findViewById(R.id.txt_forgot_pass); btnLogin = (Button) findViewById(R.id.btnLogin); forgot_pass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent forgot = new Intent(context, ForgotPassword.class); startActivity(forgot); } }); } }
UTF-8
Java
1,194
java
LoginEmail.java
Java
[]
null
[]
package com.surfspotcheck.surfspotcheck.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.surfspotcheck.surfspotcheck.R; public class LoginEmail extends AppCompatActivity { TextView txt_email; TextView txt_pass; TextView forgot_pass; Button btnLogin; AppCompatActivity context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_email); context = this; txt_email = (TextView) findViewById(R.id.txt_email); txt_pass = (TextView) findViewById(R.id.txt_pass); forgot_pass = (TextView) findViewById(R.id.txt_forgot_pass); btnLogin = (Button) findViewById(R.id.btnLogin); forgot_pass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent forgot = new Intent(context, ForgotPassword.class); startActivity(forgot); } }); } }
1,194
0.68258
0.681742
41
28.121952
22.53582
74
false
false
0
0
0
0
0
0
0.585366
false
false
4
eb2ecc8fd52e03ec02de6a3ff1cbfe82a60fb033
7,052,336,319,875
5101ca66d7f1cbbc69b551161b5f66b32175f757
/spring-integration-social-twitter/src/main/java/org/springframework/integration/twitter/config/TwitterSearchOutboundGatewayParser.java
b852c89ab45f0c9b637c3b38c63e3b352851b3de
[ "Apache-2.0" ]
permissive
artembilan/spring-integration-extensions
https://github.com/artembilan/spring-integration-extensions
ddb7e655ca8cf67cb5df71b2980e9c7cd0e3e034
a4aeef74d38e06adee705e453882e976b8fdc7b3
refs/heads/main
2023-02-19T16:54:06.498000
2023-02-16T18:02:49
2023-02-16T18:02:49
6,584,471
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 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 org.springframework.integration.twitter.config; import org.w3c.dom.Element; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.config.ExpressionFactoryBean; import org.springframework.integration.config.xml.AbstractConsumerEndpointParser; import org.springframework.integration.config.xml.IntegrationNamespaceUtils; import org.springframework.integration.twitter.outbound.TwitterSearchOutboundGateway; import org.springframework.util.StringUtils; /** * Parser for {@code <int-twitter:search-outbound-gateway/>}. * * @author Gary Russell */ public class TwitterSearchOutboundGatewayParser extends AbstractConsumerEndpointParser { @Override protected String getInputChannelAttributeName() { return "request-channel"; } @Override protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(TwitterSearchOutboundGateway.class); builder.addConstructorArgReference(element.getAttribute("twitter-template")); String searchArgsExpression = element.getAttribute("search-args-expression"); if (StringUtils.hasText(searchArgsExpression)) { BeanDefinition expressionDef = new RootBeanDefinition(ExpressionFactoryBean.class); expressionDef.getConstructorArgumentValues().addGenericArgumentValue(searchArgsExpression); builder.addPropertyValue("searchArgsExpression", expressionDef); } IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel", "outputChannel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout", "sendTimeout"); return builder; } }
UTF-8
Java
2,538
java
TwitterSearchOutboundGatewayParser.java
Java
[ { "context": "-twitter:search-outbound-gateway/>}.\n *\n * @author Gary Russell\n */\npublic class TwitterSearchOutboundGatewayPars", "end": 1421, "score": 0.9997904896736145, "start": 1409, "tag": "NAME", "value": "Gary Russell" } ]
null
[]
/* * Copyright 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 org.springframework.integration.twitter.config; import org.w3c.dom.Element; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.config.ExpressionFactoryBean; import org.springframework.integration.config.xml.AbstractConsumerEndpointParser; import org.springframework.integration.config.xml.IntegrationNamespaceUtils; import org.springframework.integration.twitter.outbound.TwitterSearchOutboundGateway; import org.springframework.util.StringUtils; /** * Parser for {@code <int-twitter:search-outbound-gateway/>}. * * @author <NAME> */ public class TwitterSearchOutboundGatewayParser extends AbstractConsumerEndpointParser { @Override protected String getInputChannelAttributeName() { return "request-channel"; } @Override protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(TwitterSearchOutboundGateway.class); builder.addConstructorArgReference(element.getAttribute("twitter-template")); String searchArgsExpression = element.getAttribute("search-args-expression"); if (StringUtils.hasText(searchArgsExpression)) { BeanDefinition expressionDef = new RootBeanDefinition(ExpressionFactoryBean.class); expressionDef.getConstructorArgumentValues().addGenericArgumentValue(searchArgsExpression); builder.addPropertyValue("searchArgsExpression", expressionDef); } IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel", "outputChannel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout", "sendTimeout"); return builder; } }
2,532
0.815603
0.812057
59
42.016949
35.902641
114
false
false
0
0
0
0
0
0
1.135593
false
false
4
b0b3969cc85140b1d88eca6883de85c487e36ac9
27,298,812,203,490
9d235c722507b5eaa942dba7b33ecf42a451d58a
/plugin-app-market/src/main/java/com/snszyk/iiot/marketization/market/domain/transmarket/valobj/ContainedMarketElements.java
615892f5082199f98bec17c8e618e8b805da056a
[ "MIT" ]
permissive
bellmit/lmocp
https://github.com/bellmit/lmocp
777e33d20dd6b3932b49d41e3122ce5e6d2e0b6a
e7039836bd5459930cc5087812ed07e254e73390
refs/heads/main
2023-07-04T06:08:56.417000
2021-08-11T03:00:44
2021-08-11T03:00:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.snszyk.iiot.marketization.market.domain.transmarket.valobj; import lombok.*; import java.util.List; /** * 所含要素 * * @author tengwang * @version 1.0.0 * @date 2021/8/2 3:48 下午 */ @Getter @Builder @AllArgsConstructor(access = AccessLevel.PROTECTED) @ToString @EqualsAndHashCode public class ContainedMarketElements { private List<MarketElementIdentify> marketElementsIdentifies; }
UTF-8
Java
415
java
ContainedMarketElements.java
Java
[ { "context": "\nimport java.util.List;\n\n/**\n * 所含要素\n *\n * @author tengwang\n * @version 1.0.0\n * @date 2021/8/2 3:48 下午\n */\n@", "end": 149, "score": 0.9982113838195801, "start": 141, "tag": "USERNAME", "value": "tengwang" } ]
null
[]
package com.snszyk.iiot.marketization.market.domain.transmarket.valobj; import lombok.*; import java.util.List; /** * 所含要素 * * @author tengwang * @version 1.0.0 * @date 2021/8/2 3:48 下午 */ @Getter @Builder @AllArgsConstructor(access = AccessLevel.PROTECTED) @ToString @EqualsAndHashCode public class ContainedMarketElements { private List<MarketElementIdentify> marketElementsIdentifies; }
415
0.761787
0.73201
21
18.190475
20.664253
71
false
false
0
0
0
0
0
0
0.190476
false
false
4
bbf64e6916c3c58da7354cf9dd4338bfb37a7d8c
9,019,431,322,677
f22960366f65d631e60744513d4876f4cbb2d33c
/src/main/java/frc/robot/subsystems/DriveSubsystem.java
4c892e2e82cfa87853e804298c68da41447690f4
[]
no_license
nwhsrobotics/FRC_InfiniteRecharge
https://github.com/nwhsrobotics/FRC_InfiniteRecharge
7d92788479d5049e964c6a53ad8801cc919bd649
fccab5876e9fe94d7d3de4c6b7a2087e2f4c6056
refs/heads/master
2021-12-10T11:10:33.855000
2021-10-17T18:39:39
2021-10-17T18:39:39
237,535,916
0
4
null
null
null
null
null
null
null
null
null
null
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMax.IdleMode; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.wpilibj.SpeedControllerGroup; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.util.VelDiffDrive; public class DriveSubsystem extends SubsystemBase { private static final double POWER_FACTOR = 0.8; private static final double TURN_FACTOR = 0.65; // To do: Declare motor controllers (CANSparkMax) private CANSparkMax m_left1 = null; private CANSparkMax m_left2 = null; private CANSparkMax m_right1 = null; private CANSparkMax m_right2 = null; private DifferentialDrive m_drive; public boolean driveExist; //todo: add PID control objects //todo: add trajectory objects //private CANPIDController m_pidController; //private double kP, kI, kD, kIz, kFF, kMaxOutput, kMinOutput; private boolean reverseDrive = false; private double m_turn = 0.0; private double m_power = 0.0; // private VelDiffDrive m_vDrive; private SpeedControllerGroup m_left; private SpeedControllerGroup m_right; private double m_fwdVel; private double m_turnVel; /** * Creates a new DriveSubsystem. */ public DriveSubsystem() { //Add motors to groups //Create ArcadeDrive m_left1 = new CANSparkMax(Constants.Drive.CANID_LEFT1, MotorType.kBrushless); m_left2 = new CANSparkMax(Constants.Drive.CANID_LEFT2, MotorType.kBrushless); m_right1 = new CANSparkMax(Constants.Drive.CANID_RIGHT1, MotorType.kBrushless); m_right2 = new CANSparkMax(Constants.Drive.CANID_RIGHT2, MotorType.kBrushless); // todo: get PID controllers // todo: add PID parameters if (Constants.Drive.CANID_LEFT1 == 0 || Constants.Drive.CANID_LEFT2 == 0 || Constants.Drive.CANID_RIGHT1 == 0 || Constants.Drive.CANID_RIGHT2 == 0) { m_left1 = null; driveExist = false; } if (m_left1 != null || m_left2 != null || m_right1 != null || m_right2 != null){ //Set Idle mode for breaking m_left1.setIdleMode(IdleMode.kBrake); m_left2.setIdleMode(IdleMode.kBrake); m_right1.setIdleMode(IdleMode.kBrake); m_right2.setIdleMode(IdleMode.kBrake); //Declare motor groups m_left = new SpeedControllerGroup(m_left1, m_left2); m_right = new SpeedControllerGroup(m_right1, m_right2); //Declare ArcadeDrive // TODO: restore. m_drive = new DifferentialDrive(m_left, m_right); m_drive.setDeadband(0.15); m_drive.setSafetyEnabled(false); // m_vDrive = new VelDiffDrive(m_left1, m_left2, m_right1, m_right2); // m_vDrive.setDeadband(0.15); // m_vDrive.setSafetyEnabled(false); } } @Override public void periodic() { // (Moved to teleopPeriodic() ) } public void disabledInit() { if(m_drive != null){ m_drive.setSafetyEnabled(false); } // if(m_vDrive != null){ // m_vDrive.setSafetyEnabled(false); // m_vDrive.disable(); // } if (driveExist) { m_left1.set(0.0); m_left2.set(0.0); m_right1.set(0.0); m_right2.set(0.0); } } public void disabledPeriodic() { } public void autonomousInit(){ // m_vDrive.setSafetyEnabled(true); // todo: // m_vDrive.enable(); } public void autonomousPeriodic(){ // m_vDrive.setVel(m_fwdVel, m_turnVel); m_drive.arcadeDrive(m_power * POWER_FACTOR, m_turn * TURN_FACTOR, true); } public void teleopInit(){ // if (m_vDrive != null) { // m_vDrive.disable(); // } m_drive.setSafetyEnabled(true); //System.out.print("driveSubsystem.telopInit"); } public void teleopPeriodic() { m_drive.arcadeDrive(m_power * POWER_FACTOR, m_turn * TURN_FACTOR, true); //m_drive.curvatureDrive(m_power * POWER_FACTOR, m_turn * TURN_FACTOR, false); // TODO: Restore teleop behavior after testing m_vDrive. //m_vDrive.arcadeDrive(m_power, m_turn); //System.out.print("driveSubsystem.telopPeriodic\n"); } public void setDrivePower(double power, double turn){ //To do: Control motors if (m_left1 != null || m_left2 != null || m_right1 != null || m_right2 != null){ //If reversedrive is true, put drive train in reverse if(reverseDrive){ m_power = -power; m_turn = turn; } else{ m_power = power; m_turn = turn; } } } public boolean Reverse(){ //When function is called, switches boolean from true to false and vice versa. reverseDrive = !reverseDrive; return reverseDrive; } public void setVel(double fwd, double turn) { m_fwdVel = fwd; m_turnVel = turn; } }
UTF-8
Java
5,369
java
DriveSubsystem.java
Java
[]
null
[]
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMax.IdleMode; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.wpilibj.SpeedControllerGroup; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.util.VelDiffDrive; public class DriveSubsystem extends SubsystemBase { private static final double POWER_FACTOR = 0.8; private static final double TURN_FACTOR = 0.65; // To do: Declare motor controllers (CANSparkMax) private CANSparkMax m_left1 = null; private CANSparkMax m_left2 = null; private CANSparkMax m_right1 = null; private CANSparkMax m_right2 = null; private DifferentialDrive m_drive; public boolean driveExist; //todo: add PID control objects //todo: add trajectory objects //private CANPIDController m_pidController; //private double kP, kI, kD, kIz, kFF, kMaxOutput, kMinOutput; private boolean reverseDrive = false; private double m_turn = 0.0; private double m_power = 0.0; // private VelDiffDrive m_vDrive; private SpeedControllerGroup m_left; private SpeedControllerGroup m_right; private double m_fwdVel; private double m_turnVel; /** * Creates a new DriveSubsystem. */ public DriveSubsystem() { //Add motors to groups //Create ArcadeDrive m_left1 = new CANSparkMax(Constants.Drive.CANID_LEFT1, MotorType.kBrushless); m_left2 = new CANSparkMax(Constants.Drive.CANID_LEFT2, MotorType.kBrushless); m_right1 = new CANSparkMax(Constants.Drive.CANID_RIGHT1, MotorType.kBrushless); m_right2 = new CANSparkMax(Constants.Drive.CANID_RIGHT2, MotorType.kBrushless); // todo: get PID controllers // todo: add PID parameters if (Constants.Drive.CANID_LEFT1 == 0 || Constants.Drive.CANID_LEFT2 == 0 || Constants.Drive.CANID_RIGHT1 == 0 || Constants.Drive.CANID_RIGHT2 == 0) { m_left1 = null; driveExist = false; } if (m_left1 != null || m_left2 != null || m_right1 != null || m_right2 != null){ //Set Idle mode for breaking m_left1.setIdleMode(IdleMode.kBrake); m_left2.setIdleMode(IdleMode.kBrake); m_right1.setIdleMode(IdleMode.kBrake); m_right2.setIdleMode(IdleMode.kBrake); //Declare motor groups m_left = new SpeedControllerGroup(m_left1, m_left2); m_right = new SpeedControllerGroup(m_right1, m_right2); //Declare ArcadeDrive // TODO: restore. m_drive = new DifferentialDrive(m_left, m_right); m_drive.setDeadband(0.15); m_drive.setSafetyEnabled(false); // m_vDrive = new VelDiffDrive(m_left1, m_left2, m_right1, m_right2); // m_vDrive.setDeadband(0.15); // m_vDrive.setSafetyEnabled(false); } } @Override public void periodic() { // (Moved to teleopPeriodic() ) } public void disabledInit() { if(m_drive != null){ m_drive.setSafetyEnabled(false); } // if(m_vDrive != null){ // m_vDrive.setSafetyEnabled(false); // m_vDrive.disable(); // } if (driveExist) { m_left1.set(0.0); m_left2.set(0.0); m_right1.set(0.0); m_right2.set(0.0); } } public void disabledPeriodic() { } public void autonomousInit(){ // m_vDrive.setSafetyEnabled(true); // todo: // m_vDrive.enable(); } public void autonomousPeriodic(){ // m_vDrive.setVel(m_fwdVel, m_turnVel); m_drive.arcadeDrive(m_power * POWER_FACTOR, m_turn * TURN_FACTOR, true); } public void teleopInit(){ // if (m_vDrive != null) { // m_vDrive.disable(); // } m_drive.setSafetyEnabled(true); //System.out.print("driveSubsystem.telopInit"); } public void teleopPeriodic() { m_drive.arcadeDrive(m_power * POWER_FACTOR, m_turn * TURN_FACTOR, true); //m_drive.curvatureDrive(m_power * POWER_FACTOR, m_turn * TURN_FACTOR, false); // TODO: Restore teleop behavior after testing m_vDrive. //m_vDrive.arcadeDrive(m_power, m_turn); //System.out.print("driveSubsystem.telopPeriodic\n"); } public void setDrivePower(double power, double turn){ //To do: Control motors if (m_left1 != null || m_left2 != null || m_right1 != null || m_right2 != null){ //If reversedrive is true, put drive train in reverse if(reverseDrive){ m_power = -power; m_turn = turn; } else{ m_power = power; m_turn = turn; } } } public boolean Reverse(){ //When function is called, switches boolean from true to false and vice versa. reverseDrive = !reverseDrive; return reverseDrive; } public void setVel(double fwd, double turn) { m_fwdVel = fwd; m_turnVel = turn; } }
5,369
0.629912
0.616316
177
29.327684
26.272045
153
false
false
0
0
0
0
0
0
0.666667
false
false
4
10e177933cf9041b4d4873758efdac2df690e2dc
6,622,839,572,747
6d09099dac386cfc1f79a4b3fc4c2d13fbdf2f9c
/app/src/main/java/com/twist/gametwist/store/app/ConnectionService.java
af91960903f58a4aab81017251ca49d6f5d27c31
[]
no_license
JaMachine/gametwist
https://github.com/JaMachine/gametwist
f96fa9297b76924e01adb62885cd9fa5041849bd
4ba074d75f4b77cb46dc5fb8778b8ea8d5e82689
refs/heads/master
2023-05-21T07:06:01.915000
2021-06-16T09:02:10
2021-06-16T09:02:10
373,887,212
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.twist.gametwist.store.app; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.os.IBinder; import android.os.SystemClock; import androidx.annotation.Nullable; import static com.twist.gametwist.store.app.V.BroadcastStringForAction; public class ConnectionService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { handler.post(networkStateUpdate); return START_STICKY; } public boolean isOnline(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnectedOrConnecting()) return true; else return false; } Handler handler = new Handler(); private Runnable networkStateUpdate = new Runnable() { @Override public void run() { handler.postDelayed(networkStateUpdate, 1 * 1000 - SystemClock.elapsedRealtime() % 1000); Intent intent = new Intent(); intent.setAction(BroadcastStringForAction); intent.putExtra("online_status", "" + isOnline(ConnectionService.this)); sendBroadcast(intent); } }; }
UTF-8
Java
1,523
java
ConnectionService.java
Java
[]
null
[]
package com.twist.gametwist.store.app; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.os.IBinder; import android.os.SystemClock; import androidx.annotation.Nullable; import static com.twist.gametwist.store.app.V.BroadcastStringForAction; public class ConnectionService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { handler.post(networkStateUpdate); return START_STICKY; } public boolean isOnline(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnectedOrConnecting()) return true; else return false; } Handler handler = new Handler(); private Runnable networkStateUpdate = new Runnable() { @Override public void run() { handler.postDelayed(networkStateUpdate, 1 * 1000 - SystemClock.elapsedRealtime() % 1000); Intent intent = new Intent(); intent.setAction(BroadcastStringForAction); intent.putExtra("online_status", "" + isOnline(ConnectionService.this)); sendBroadcast(intent); } }; }
1,523
0.700591
0.694682
48
30.729166
27.299068
115
false
false
0
0
0
0
0
0
0.604167
false
false
4
818cec7ba4759cfc36d4631a4cb3dd2a3dc15f59
3,676,492,017,146
d89f630374e0a95c3a900b54c18e874e9f0a7e3d
/XML/firma/src/main/java/com/firma/services/FirmaService.java
873de500c3db6612b233c770f28a3d3c61d1ab4c
[]
no_license
EducationConsultant/XML
https://github.com/EducationConsultant/XML
93f58d56702de03b160c5b39fa67fbfaaacbb28e
be88bd23005e6bfd8525b62610c6ffdc79aeac41
refs/heads/master
2020-03-07T01:03:32.734000
2017-06-28T09:43:36
2017-06-28T09:43:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.firma.services; import java.util.List; import com.firma.models.domain.FakturaDTO; import com.firma.models.domain.Firma; import com.firma.models.nalogzaprenos.NalogZaPrenos; public interface FirmaService { public Firma findOne(Long id); public Firma save(Firma firma); public Firma findByNaziv(String naziv); public List<Firma> find(); public Firma saveFaktura(Long id, FakturaDTO faktura); public void posaljiNalog(NalogZaPrenos n); public Firma podesiBanku(String nazivBanke, Firma firma); }
UTF-8
Java
522
java
FirmaService.java
Java
[]
null
[]
package com.firma.services; import java.util.List; import com.firma.models.domain.FakturaDTO; import com.firma.models.domain.Firma; import com.firma.models.nalogzaprenos.NalogZaPrenos; public interface FirmaService { public Firma findOne(Long id); public Firma save(Firma firma); public Firma findByNaziv(String naziv); public List<Firma> find(); public Firma saveFaktura(Long id, FakturaDTO faktura); public void posaljiNalog(NalogZaPrenos n); public Firma podesiBanku(String nazivBanke, Firma firma); }
522
0.787356
0.787356
24
20.75
20.646328
58
false
false
0
0
0
0
0
0
0.875
false
false
4
3ee37db0d9856e1e4207facc8a2d59918b5b00d5
9,053,791,061,142
82c5ad39214eb3f6e95634cc9b9aacd059b30776
/java/src/leetcode/SubstringwithConcatenationofAllWords_fake.java
9a75b77a98ef562f1b96f0deba58df678fa19da4
[]
no_license
VinceNKB/leetcode
https://github.com/VinceNKB/leetcode
01181ad3bd506896930165395f22db24da68124e
beae6d426e17bdea0502c0611b5fbb3d5f3d1a86
refs/heads/master
2021-06-25T19:43:44.536000
2017-09-11T04:14:33
2017-09-11T04:14:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /* You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. For example, given: s: "barfoothefoobarman" words: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). */ /* * ["word","good","best","good"] */ //I misunderstood the problem and ignore the "without any intervening characters" public class SubstringwithConcatenationofAllWords_fake { public static void main(String[] args) { new SubstringwithConcatenationofAllWords_fake().findSubstring( "wordgoodgoodgoodbestword", new String[] { "word", "good", "best", "good" }); // new SubstringwithConcatenationofAllWords_fake().findSubstring( // "barfoothefoobarman", new String[] { "foo", "bar" }); } HashMap<String, Integer> wordIndex = new HashMap<String, Integer>(); int[] wordCount = null; int wordLength = 0; int[] indexMap = null; int totalDep = 0; public List<Integer> findSubstring(String s, String[] words) { List<Integer> list = new ArrayList<Integer>(); if (words == null || words.length == 0) return null; if (s == null || s.length() < words[0].length()) return null; wordLength = words[0].length(); indexMap = new int[s.length() - wordLength + 1]; totalDep = words.length; int index = 0; for (int i = 0; i < words.length; i++) { if (!wordIndex.containsKey(words[i])) { wordIndex.put(words[i], index++); } } wordCount = new int[wordIndex.size()]; for (int i = 0; i < words.length; i++) { wordCount[wordIndex.get(words[i])]++; } for (int i = 0; i < indexMap.length; i++) { indexMap[i] = -1; } fillIndexMap(words, s); // for(int i = 0; i < indexMap.length; i++){ // System.out.println(indexMap[i]); // } for (int i = 0; i < indexMap.length; i++) { if (indexMap[i] != -1) { int[] wordAppear = new int[wordCount.length]; wordAppear[indexMap[i]] = 1; if (handle(i, wordAppear, 1)) { // System.out.println(i); list.add(i); } } } return list; } public void fillIndexMap(String[] words, String s) { Iterator iter = wordIndex.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String findWord = (String) entry.getKey(); int i = (int) entry.getValue(); int startIndex = 0; while (startIndex <= indexMap.length) { int findIndex = s.indexOf(findWord, startIndex); if (findIndex != -1) { indexMap[findIndex] = i; startIndex = findIndex + 1; } else { break; } } } } public boolean handle(int start, int[] wordAppear, int dep) { if (dep == totalDep) return true; start += wordLength; if (start >= indexMap.length) return false; int next = -1; for (int i = start; i < indexMap.length; i++) { if (indexMap[i] != -1) { next = i; break; } } if (next == -1) return false; start = next; if (wordAppear[indexMap[start]] >= wordCount[indexMap[start]]) { int count = 0; for (int i = start + 1; i < Math.min(start + wordLength, indexMap.length); i++) { if (indexMap[i] != -1 && wordAppear[indexMap[i]] < wordCount[indexMap[start]]) { count++; } } if (count == 0) return false; } else { int[] newWordAppear = wordAppear.clone(); newWordAppear[indexMap[start]]++; if (handle(start, newWordAppear, dep + 1)) return true; } for (int i = start + 1; i < Math.min(start + wordLength, indexMap.length); i++) { if (indexMap[i] != -1 && wordAppear[indexMap[i]] < wordCount[indexMap[start]]) { int[] newWordAppear = wordAppear.clone(); newWordAppear[indexMap[i]]++; if (handle(i, newWordAppear, dep + 1)) return true; } } return false; } }
UTF-8
Java
4,011
java
SubstringwithConcatenationofAllWords_fake.java
Java
[ { "context": "rvening characters.\n\n For example, given:\n s: \"barfoothefoobarman\"\n words: [\"foo\", \"bar\"]\n\n You should r", "end": 418, "score": 0.5244070887565613, "start": 414, "tag": "USERNAME", "value": "foot" }, { "context": "g characters.\n\n For example, given:\n s: \"barfoothefoobarman\"\n words: [\"foo\", \"bar\"]\n\n You should return the i", "end": 429, "score": 0.6434856057167053, "start": 420, "tag": "USERNAME", "value": "foobarman" } ]
null
[]
package leetcode; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /* You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. For example, given: s: "barfoothefoobarman" words: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). */ /* * ["word","good","best","good"] */ //I misunderstood the problem and ignore the "without any intervening characters" public class SubstringwithConcatenationofAllWords_fake { public static void main(String[] args) { new SubstringwithConcatenationofAllWords_fake().findSubstring( "wordgoodgoodgoodbestword", new String[] { "word", "good", "best", "good" }); // new SubstringwithConcatenationofAllWords_fake().findSubstring( // "barfoothefoobarman", new String[] { "foo", "bar" }); } HashMap<String, Integer> wordIndex = new HashMap<String, Integer>(); int[] wordCount = null; int wordLength = 0; int[] indexMap = null; int totalDep = 0; public List<Integer> findSubstring(String s, String[] words) { List<Integer> list = new ArrayList<Integer>(); if (words == null || words.length == 0) return null; if (s == null || s.length() < words[0].length()) return null; wordLength = words[0].length(); indexMap = new int[s.length() - wordLength + 1]; totalDep = words.length; int index = 0; for (int i = 0; i < words.length; i++) { if (!wordIndex.containsKey(words[i])) { wordIndex.put(words[i], index++); } } wordCount = new int[wordIndex.size()]; for (int i = 0; i < words.length; i++) { wordCount[wordIndex.get(words[i])]++; } for (int i = 0; i < indexMap.length; i++) { indexMap[i] = -1; } fillIndexMap(words, s); // for(int i = 0; i < indexMap.length; i++){ // System.out.println(indexMap[i]); // } for (int i = 0; i < indexMap.length; i++) { if (indexMap[i] != -1) { int[] wordAppear = new int[wordCount.length]; wordAppear[indexMap[i]] = 1; if (handle(i, wordAppear, 1)) { // System.out.println(i); list.add(i); } } } return list; } public void fillIndexMap(String[] words, String s) { Iterator iter = wordIndex.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String findWord = (String) entry.getKey(); int i = (int) entry.getValue(); int startIndex = 0; while (startIndex <= indexMap.length) { int findIndex = s.indexOf(findWord, startIndex); if (findIndex != -1) { indexMap[findIndex] = i; startIndex = findIndex + 1; } else { break; } } } } public boolean handle(int start, int[] wordAppear, int dep) { if (dep == totalDep) return true; start += wordLength; if (start >= indexMap.length) return false; int next = -1; for (int i = start; i < indexMap.length; i++) { if (indexMap[i] != -1) { next = i; break; } } if (next == -1) return false; start = next; if (wordAppear[indexMap[start]] >= wordCount[indexMap[start]]) { int count = 0; for (int i = start + 1; i < Math.min(start + wordLength, indexMap.length); i++) { if (indexMap[i] != -1 && wordAppear[indexMap[i]] < wordCount[indexMap[start]]) { count++; } } if (count == 0) return false; } else { int[] newWordAppear = wordAppear.clone(); newWordAppear[indexMap[start]]++; if (handle(start, newWordAppear, dep + 1)) return true; } for (int i = start + 1; i < Math.min(start + wordLength, indexMap.length); i++) { if (indexMap[i] != -1 && wordAppear[indexMap[i]] < wordCount[indexMap[start]]) { int[] newWordAppear = wordAppear.clone(); newWordAppear[indexMap[i]]++; if (handle(i, newWordAppear, dep + 1)) return true; } } return false; } }
4,011
0.619796
0.611817
167
23.017963
25.981216
234
false
false
0
0
0
0
0
0
2.568862
false
false
4
72ae5134fb6b1ac58ee4bb48a80492ff2452c0d9
19,370,302,572,173
6ee64b3892109445cc90e93fdab2f9aa32a7b912
/runescape-client/src/main/java/IndexData.java
d3df3416cf0fea15c71fcfd75c28e99a1ba8bf89
[ "BSD-2-Clause" ]
permissive
dey0/runelite
https://github.com/dey0/runelite
c033044ac54ced5e1ee68f2b322d1c8c1d785316
43a6e7a267d584146c8cb1db2d34c04b1daa4890
refs/heads/master
2021-08-26T06:39:58.859000
2017-11-20T01:13:55
2017-11-20T01:13:55
98,679,870
0
0
null
true
2017-07-28T19:07:29
2017-07-28T19:07:29
2017-07-28T18:03:35
2017-07-27T00:09:52
20,846
0
0
0
null
null
null
import java.util.zip.CRC32; import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("iu") @Implements("IndexData") public class IndexData extends IndexDataBase { @ObfuscatedName("w") @Export("crc32") static CRC32 crc32; @ObfuscatedName("p") @ObfuscatedSignature( signature = "Lfw;" ) IndexFile field3300; @ObfuscatedName("i") @ObfuscatedSignature( signature = "Lfw;" ) IndexFile field3303; @ObfuscatedName("l") @ObfuscatedGetter( intValue = -157034705 ) @Export("index") int index; @ObfuscatedName("z") volatile boolean field3297; @ObfuscatedName("e") boolean field3294; @ObfuscatedName("v") volatile boolean[] field3295; @ObfuscatedName("av") @ObfuscatedGetter( intValue = -1892340741 ) @Export("crcValue") int crcValue; @ObfuscatedName("au") @ObfuscatedGetter( intValue = 873238095 ) int field3302; @ObfuscatedName("ae") @ObfuscatedGetter( intValue = -2140233085 ) int field3299; static { crc32 = new CRC32(); } @ObfuscatedSignature( signature = "(Lfw;Lfw;IZZZ)V" ) public IndexData(IndexFile var1, IndexFile var2, int var3, boolean var4, boolean var5, boolean var6) { super(var4, var5); this.field3297 = false; this.field3294 = false; this.field3299 = -1; this.field3300 = var1; this.field3303 = var2; this.index = var3; this.field3294 = var6; int var8 = this.index; if(class36.field473 != null) { class36.field473.offset = var8 * 8 + 5; int var9 = class36.field473.readInt(); int var10 = class36.field473.readInt(); this.setInformation(var9, var10); } else { class87.method1678((IndexData)null, 255, 255, 0, (byte)0, true); class245.field3321[var8] = this; } } @ObfuscatedName("s") @ObfuscatedSignature( signature = "(II)V", garbageValue = "1224741281" ) void vmethod4211(int var1) { class20.method148(this.index, var1); } @ObfuscatedName("t") @ObfuscatedSignature( signature = "(IB)I", garbageValue = "1" ) int vmethod4223(int var1) { return super.field3279[var1] != null?100:(this.field3295[var1]?100:MessageNode.method1053(this.index, var1)); } @ObfuscatedName("o") @ObfuscatedSignature( signature = "(IB)V", garbageValue = "71" ) void vmethod4216(int var1) { if(this.field3300 != null && this.field3295 != null && this.field3295[var1]) { class37.method483(var1, this.field3300, this); } else { class87.method1678(this, this.index, var1, super.archiveCrcs[var1], (byte)2, true); } } @ObfuscatedName("cs") @ObfuscatedSignature( signature = "(I)I", garbageValue = "2138172350" ) @Export("percentage") public int percentage() { if(this.field3297) { return 100; } else if(super.field3279 != null) { return 99; } else { int var1 = MessageNode.method1053(255, this.index); if(var1 >= 100) { var1 = 99; } return var1; } } @ObfuscatedName("co") @ObfuscatedSignature( signature = "(III)V", garbageValue = "-1265504799" ) @Export("setInformation") void setInformation(int var1, int var2) { this.crcValue = var1; this.field3302 = var2; if(this.field3303 != null) { class37.method483(this.index, this.field3303, this); } else { class87.method1678(this, 255, this.index, this.crcValue, (byte)0, true); } } @ObfuscatedName("ci") @ObfuscatedSignature( signature = "(I[BZZB)V", garbageValue = "-73" ) void method4212(int var1, byte[] var2, boolean var3, boolean var4) { if(var3) { if(this.field3297) { throw new RuntimeException(); } if(this.field3303 != null) { WidgetNode.method1030(this.index, var2, this.field3303); } this.method4106(var2); this.method4214(); } else { var2[var2.length - 2] = (byte)(super.archiveRevisions[var1] >> 8); var2[var2.length - 1] = (byte)super.archiveRevisions[var1]; if(this.field3300 != null) { WidgetNode.method1030(var1, var2, this.field3300); this.field3295[var1] = true; } if(var4) { super.field3279[var1] = class177.method3156(var2, false); } } } @ObfuscatedName("cr") @ObfuscatedSignature( signature = "(Lfw;I[BZI)V", garbageValue = "-1708519652" ) public void method4213(IndexFile var1, int var2, byte[] var3, boolean var4) { int var5; if(var1 == this.field3303) { if(this.field3297) { throw new RuntimeException(); } else if(var3 == null) { class87.method1678(this, 255, this.index, this.crcValue, (byte)0, true); } else { crc32.reset(); crc32.update(var3, 0, var3.length); var5 = (int)crc32.getValue(); Buffer var9 = new Buffer(CacheFile.decodeContainer(var3)); int var7 = var9.readUnsignedByte(); if(var7 != 5 && var7 != 6) { throw new RuntimeException(var7 + "," + this.index + "," + var2); } else { int var8 = 0; if(var7 >= 6) { var8 = var9.readInt(); } if(var5 != this.crcValue || var8 != this.field3302) { class87.method1678(this, 255, this.index, this.crcValue, (byte)0, true); } else { this.method4106(var3); this.method4214(); } } } } else { if(!var4 && var2 == this.field3299) { this.field3297 = true; } if(var3 != null && var3.length > 2) { crc32.reset(); crc32.update(var3, 0, var3.length - 2); var5 = (int)crc32.getValue(); int var6 = ((var3[var3.length - 2] & 255) << 8) + (var3[var3.length - 1] & 255); if(var5 == super.archiveCrcs[var2] && var6 == super.archiveRevisions[var2]) { this.field3295[var2] = true; if(var4) { super.field3279[var2] = class177.method3156(var3, false); } } else { this.field3295[var2] = false; if(this.field3294 || var4) { class87.method1678(this, this.index, var2, super.archiveCrcs[var2], (byte)2, var4); } } } else { this.field3295[var2] = false; if(this.field3294 || var4) { class87.method1678(this, this.index, var2, super.archiveCrcs[var2], (byte)2, var4); } } } } @ObfuscatedName("cu") @ObfuscatedSignature( signature = "(I)V", garbageValue = "1693650538" ) void method4214() { this.field3295 = new boolean[super.field3279.length]; int var1; for(var1 = 0; var1 < this.field3295.length; ++var1) { this.field3295[var1] = false; } if(this.field3300 == null) { this.field3297 = true; } else { this.field3299 = -1; for(var1 = 0; var1 < this.field3295.length; ++var1) { if(super.archiveNumberOfFiles[var1] > 0) { class34.method469(var1, this.field3300, this); this.field3299 = var1; } } if(this.field3299 == -1) { this.field3297 = true; } } } @ObfuscatedName("cl") @ObfuscatedSignature( signature = "(I)I", garbageValue = "-534251950" ) public int method4217() { int var1 = 0; int var2 = 0; int var3; for(var3 = 0; var3 < super.field3279.length; ++var3) { if(super.archiveNumberOfFiles[var3] > 0) { var1 += 100; var2 += this.vmethod4223(var3); } } if(var1 == 0) { return 100; } else { var3 = var2 * 100 / var1; return var3; } } @ObfuscatedName("f") @ObfuscatedSignature( signature = "(I)V", garbageValue = "1454203423" ) public static void method4233() { try { class156.field2148.method2355(); for(int var0 = 0; var0 < class164.field2212; ++var0) { class221.field2700[var0].method2355(); } class156.field2153.method2355(); class156.field2151.method2355(); } catch (Exception var2) { ; } } }
UTF-8
Java
8,869
java
IndexData.java
Java
[ { "context": " return var1;\n }\n }\n\n @ObfuscatedName(\"co\")\n @ObfuscatedSignature(\n signature = \"(II", "end": 3376, "score": 0.52015221118927, "start": 3374, "tag": "USERNAME", "value": "co" } ]
null
[]
import java.util.zip.CRC32; import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("iu") @Implements("IndexData") public class IndexData extends IndexDataBase { @ObfuscatedName("w") @Export("crc32") static CRC32 crc32; @ObfuscatedName("p") @ObfuscatedSignature( signature = "Lfw;" ) IndexFile field3300; @ObfuscatedName("i") @ObfuscatedSignature( signature = "Lfw;" ) IndexFile field3303; @ObfuscatedName("l") @ObfuscatedGetter( intValue = -157034705 ) @Export("index") int index; @ObfuscatedName("z") volatile boolean field3297; @ObfuscatedName("e") boolean field3294; @ObfuscatedName("v") volatile boolean[] field3295; @ObfuscatedName("av") @ObfuscatedGetter( intValue = -1892340741 ) @Export("crcValue") int crcValue; @ObfuscatedName("au") @ObfuscatedGetter( intValue = 873238095 ) int field3302; @ObfuscatedName("ae") @ObfuscatedGetter( intValue = -2140233085 ) int field3299; static { crc32 = new CRC32(); } @ObfuscatedSignature( signature = "(Lfw;Lfw;IZZZ)V" ) public IndexData(IndexFile var1, IndexFile var2, int var3, boolean var4, boolean var5, boolean var6) { super(var4, var5); this.field3297 = false; this.field3294 = false; this.field3299 = -1; this.field3300 = var1; this.field3303 = var2; this.index = var3; this.field3294 = var6; int var8 = this.index; if(class36.field473 != null) { class36.field473.offset = var8 * 8 + 5; int var9 = class36.field473.readInt(); int var10 = class36.field473.readInt(); this.setInformation(var9, var10); } else { class87.method1678((IndexData)null, 255, 255, 0, (byte)0, true); class245.field3321[var8] = this; } } @ObfuscatedName("s") @ObfuscatedSignature( signature = "(II)V", garbageValue = "1224741281" ) void vmethod4211(int var1) { class20.method148(this.index, var1); } @ObfuscatedName("t") @ObfuscatedSignature( signature = "(IB)I", garbageValue = "1" ) int vmethod4223(int var1) { return super.field3279[var1] != null?100:(this.field3295[var1]?100:MessageNode.method1053(this.index, var1)); } @ObfuscatedName("o") @ObfuscatedSignature( signature = "(IB)V", garbageValue = "71" ) void vmethod4216(int var1) { if(this.field3300 != null && this.field3295 != null && this.field3295[var1]) { class37.method483(var1, this.field3300, this); } else { class87.method1678(this, this.index, var1, super.archiveCrcs[var1], (byte)2, true); } } @ObfuscatedName("cs") @ObfuscatedSignature( signature = "(I)I", garbageValue = "2138172350" ) @Export("percentage") public int percentage() { if(this.field3297) { return 100; } else if(super.field3279 != null) { return 99; } else { int var1 = MessageNode.method1053(255, this.index); if(var1 >= 100) { var1 = 99; } return var1; } } @ObfuscatedName("co") @ObfuscatedSignature( signature = "(III)V", garbageValue = "-1265504799" ) @Export("setInformation") void setInformation(int var1, int var2) { this.crcValue = var1; this.field3302 = var2; if(this.field3303 != null) { class37.method483(this.index, this.field3303, this); } else { class87.method1678(this, 255, this.index, this.crcValue, (byte)0, true); } } @ObfuscatedName("ci") @ObfuscatedSignature( signature = "(I[BZZB)V", garbageValue = "-73" ) void method4212(int var1, byte[] var2, boolean var3, boolean var4) { if(var3) { if(this.field3297) { throw new RuntimeException(); } if(this.field3303 != null) { WidgetNode.method1030(this.index, var2, this.field3303); } this.method4106(var2); this.method4214(); } else { var2[var2.length - 2] = (byte)(super.archiveRevisions[var1] >> 8); var2[var2.length - 1] = (byte)super.archiveRevisions[var1]; if(this.field3300 != null) { WidgetNode.method1030(var1, var2, this.field3300); this.field3295[var1] = true; } if(var4) { super.field3279[var1] = class177.method3156(var2, false); } } } @ObfuscatedName("cr") @ObfuscatedSignature( signature = "(Lfw;I[BZI)V", garbageValue = "-1708519652" ) public void method4213(IndexFile var1, int var2, byte[] var3, boolean var4) { int var5; if(var1 == this.field3303) { if(this.field3297) { throw new RuntimeException(); } else if(var3 == null) { class87.method1678(this, 255, this.index, this.crcValue, (byte)0, true); } else { crc32.reset(); crc32.update(var3, 0, var3.length); var5 = (int)crc32.getValue(); Buffer var9 = new Buffer(CacheFile.decodeContainer(var3)); int var7 = var9.readUnsignedByte(); if(var7 != 5 && var7 != 6) { throw new RuntimeException(var7 + "," + this.index + "," + var2); } else { int var8 = 0; if(var7 >= 6) { var8 = var9.readInt(); } if(var5 != this.crcValue || var8 != this.field3302) { class87.method1678(this, 255, this.index, this.crcValue, (byte)0, true); } else { this.method4106(var3); this.method4214(); } } } } else { if(!var4 && var2 == this.field3299) { this.field3297 = true; } if(var3 != null && var3.length > 2) { crc32.reset(); crc32.update(var3, 0, var3.length - 2); var5 = (int)crc32.getValue(); int var6 = ((var3[var3.length - 2] & 255) << 8) + (var3[var3.length - 1] & 255); if(var5 == super.archiveCrcs[var2] && var6 == super.archiveRevisions[var2]) { this.field3295[var2] = true; if(var4) { super.field3279[var2] = class177.method3156(var3, false); } } else { this.field3295[var2] = false; if(this.field3294 || var4) { class87.method1678(this, this.index, var2, super.archiveCrcs[var2], (byte)2, var4); } } } else { this.field3295[var2] = false; if(this.field3294 || var4) { class87.method1678(this, this.index, var2, super.archiveCrcs[var2], (byte)2, var4); } } } } @ObfuscatedName("cu") @ObfuscatedSignature( signature = "(I)V", garbageValue = "1693650538" ) void method4214() { this.field3295 = new boolean[super.field3279.length]; int var1; for(var1 = 0; var1 < this.field3295.length; ++var1) { this.field3295[var1] = false; } if(this.field3300 == null) { this.field3297 = true; } else { this.field3299 = -1; for(var1 = 0; var1 < this.field3295.length; ++var1) { if(super.archiveNumberOfFiles[var1] > 0) { class34.method469(var1, this.field3300, this); this.field3299 = var1; } } if(this.field3299 == -1) { this.field3297 = true; } } } @ObfuscatedName("cl") @ObfuscatedSignature( signature = "(I)I", garbageValue = "-534251950" ) public int method4217() { int var1 = 0; int var2 = 0; int var3; for(var3 = 0; var3 < super.field3279.length; ++var3) { if(super.archiveNumberOfFiles[var3] > 0) { var1 += 100; var2 += this.vmethod4223(var3); } } if(var1 == 0) { return 100; } else { var3 = var2 * 100 / var1; return var3; } } @ObfuscatedName("f") @ObfuscatedSignature( signature = "(I)V", garbageValue = "1454203423" ) public static void method4233() { try { class156.field2148.method2355(); for(int var0 = 0; var0 < class164.field2212; ++var0) { class221.field2700[var0].method2355(); } class156.field2153.method2355(); class156.field2151.method2355(); } catch (Exception var2) { ; } } }
8,869
0.547525
0.456421
328
26.039635
21.607536
115
false
false
0
0
0
0
0
0
0.606707
false
false
4
92a417fc63c7c52895ec6303f9a00b87f0d6548e
6,141,803,297,730
dccb6a9420170a6df01ba2ddc1f7271bfafe60f9
/middleware-tech-mini/ChatJavaSpaces/src/it/polimi/mini/Chat.java
cf87cc81d8aa3ed090a0dbdf51fe65cf543fab34
[]
no_license
nicolobrognoli/middleware-tech-mini
https://github.com/nicolobrognoli/middleware-tech-mini
83e059327c204dce755b5a92985f73bb0ae0dc50
4f19199811c57d99176a427e3b358899c149ac37
refs/heads/master
2021-01-01T15:50:22.355000
2015-03-15T20:11:10
2015-03-15T20:11:10
32,281,504
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.polimi.mini; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.rmi.RemoteException; import net.jini.core.discovery.LookupLocator; import net.jini.core.entry.UnusableEntryException; import net.jini.core.lease.Lease; import net.jini.core.lookup.ServiceRegistrar; import net.jini.core.lookup.ServiceTemplate; import net.jini.core.transaction.TransactionException; import net.jini.space.JavaSpace; public class Chat { private JavaSpace js; private String username; public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); String choice = "", username = ""; int c = 0; boolean registered, failed; Chat chat = new Chat(); chat.discoverJavaSpace(); //register the user to the system do{ System.out.println("Insert username: "); username = systemInput.readLine(); registered = chat.registerUser(username); }while(!registered); do{ System.out.println("Select the action:"); System.out.println("\t1 - Create chat room"); System.out.println("\t2 - Enter existing chat room"); System.out.println("\t3 - Delete chat room"); System.out.println("\t0 - Exit"); choice = systemInput.readLine(); c = getChoice(choice); switch(c){ case 1: { chat.createChatRoom(); break; } case 2: { failed = chat.enterChatRoom(); if(failed) System.out.println("Chat room doesn't exist."); break; } case 3: { chat.deleteChatRoom(); break; } } }while(c != 0); //delete the user from the system chat.deleteAllChatroom(username); chat.deleteUser(username); System.exit(0); } private void deleteUser(String username) { UserEntry userTemplate = new UserEntry(username); try { this.js.take(userTemplate, null, Lease.FOREVER); } catch (RemoteException e) { e.printStackTrace(); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean registerUser(String username) { try { UserEntry userTemplate = new UserEntry(username); UserEntry user = (UserEntry) js.readIfExists(userTemplate, null, Lease.FOREVER); if(user == null) { js.write(userTemplate, null, Lease.FOREVER); this.username = username; System.out.println("User created."); return true; } else { System.out.println("User already exists."); return false; } } catch (RemoteException e) { e.printStackTrace(); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } public static int getChoice(String str) { if(str.equals("1")) return 1; if(str.equals("2")) return 2; if(str.equals("3")) return 3; if(str.equals("0")) return 0; return -1; } private void discoverJavaSpace() { while (js==null) { try { LookupLocator locator = new LookupLocator("jini://localhost"); ServiceRegistrar registrar = locator.getRegistrar(); js = (JavaSpace) registrar.lookup( new ServiceTemplate(null, new Class[] {JavaSpace.class}, null)); } catch (Exception exc) { exc.printStackTrace(); } } } private void createChatRoom() throws IOException{ InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); System.out.println("Specify the name of the new chat room: "); String input = systemInput.readLine(); ChatRoomEntry chatRoom; try { ChatRoomEntry template = new ChatRoomEntry(input, null, null); chatRoom = (ChatRoomEntry) js.readIfExists(template, null, Lease.FOREVER); if(chatRoom == null){ template = new ChatRoomEntry(input, this.username, 0); js.write(template, null, Lease.FOREVER); System.out.println("Chat Room created."); ChatManagerEntry chatmanager=new ChatManagerEntry(),templateManager=new ChatManagerEntry(null); chatmanager=(ChatManagerEntry)js.takeIfExists(templateManager, null, 1000); if(chatmanager==null) chatmanager=new ChatManagerEntry(); chatmanager.chatrooms.add(template.name); js.write(chatmanager, null, Lease.FOREVER); } else System.out.println("Chat Room already exists."); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean enterChatRoom() throws IOException{ boolean failed = true; try { String chatRoom,message; int i; InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); ChatManagerEntry templateManager=new ChatManagerEntry(null),chatmanager; chatmanager=(ChatManagerEntry)js.take(templateManager, null, Lease.FOREVER); js.write(chatmanager, null, Lease.FOREVER); for(i=0;i<chatmanager.chatrooms.size();i++) System.out.println("Chatroom "+i+" : "+chatmanager.chatrooms.get(i)); System.out.println("Specify the chatroom name: "); chatRoom = systemInput.readLine(); ChatRoomEntry template = new ChatRoomEntry(chatRoom, null, null); ChatRoomEntry chat; chat = (ChatRoomEntry) js.readIfExists(template, null, Lease.FOREVER); if(chat != null){ //correctly accessed the chatroom failed = false; System.out.println("How many messages do you want from this chat room ?"); int n=Integer.parseInt(systemInput.readLine()); ChatRoomEntry chatRoomObject = (ChatRoomEntry) js.take(template, null, Lease.FOREVER); if(n>chatRoomObject.msgNumber) n=chatRoomObject.msgNumber; for(i=0;i<n;i++){ MessageEntry messageTemplate=new MessageEntry(null,chatRoom,null,(Integer)chatRoomObject.msgNumber-n+i); MessageEntry messageObj=(MessageEntry)js.read(messageTemplate, null,Lease.FOREVER); messageObj.printMessage(); } js.write(chatRoomObject, null, Lease.FOREVER); ChatReader chatReader=new ChatReader(js,chatRoom,this.username); Thread t = new Thread(chatReader); t.start(); do{ message=systemInput.readLine(); if(!message.equals("exit")){ template = new ChatRoomEntry(chatRoom, null, null); chatRoomObject = (ChatRoomEntry) js.take(template, null, 2000); //if chatRoomObject is null then the chatroom has been deleted if(chatRoomObject!=null){ MessageEntry messageObject=new MessageEntry(message,chatRoom,this.username, chatRoomObject.msgNumber); chatRoomObject.msgNumber++; js.write(messageObject, null, Lease.FOREVER); js.write(chatRoomObject, null, Lease.FOREVER); } } }while(!message.equals("exit") && chatRoomObject!=null); chatReader.exit(); } } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return failed; } private void deleteChatRoom()throws IOException{ int i; ChatRoomEntry chatRoom; InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); try { ChatManagerEntry templateManager=new ChatManagerEntry(null),chatmanager; chatmanager=(ChatManagerEntry)js.take(templateManager, null, Lease.FOREVER); js.write(chatmanager, null, Lease.FOREVER); for(i=0;i<chatmanager.chatrooms.size();i++) System.out.println("Chatroom "+i+" : "+chatmanager.chatrooms.get(i)); System.out.println("Select a chat room to delete: "); String input = systemInput.readLine(); ChatRoomEntry template = new ChatRoomEntry(input, this.username, null); chatRoom = (ChatRoomEntry) js.take(template, null, 2000); if(chatRoom != null){ MessageEntry messageObject=new MessageEntry("Chatroom deleted, press enter to return to the menu...",chatRoom.name,this.username, chatRoom.msgNumber); js.write(messageObject, null, Lease.FOREVER); templateManager=new ChatManagerEntry(null); chatmanager=(ChatManagerEntry)js.take(templateManager, null, Lease.FOREVER); System.out.println("Rimosso: "+chatmanager.chatrooms.remove(chatRoom.name)); js.write(chatmanager, null, Lease.FOREVER); System.out.println("ChatRoom deleted"); CleanThread clean = new CleanThread(this.js, chatRoom.name); Thread th = new Thread(clean); th.start(); } else System.out.println("Chat Room not exists or you are not the creator of this chat room"); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private void deleteAllChatroom(String username) { ChatRoomEntry chatRoom; boolean finished=false; try { do{ ChatRoomEntry template = new ChatRoomEntry(null, this.username, null); chatRoom = (ChatRoomEntry) js.take(template, null, 2000); if(chatRoom != null){ MessageEntry messageObject=new MessageEntry("Chatroom deleted, press enter to return to the menu...",chatRoom.name,this.username, chatRoom.msgNumber); js.write(messageObject, null, Lease.FOREVER); System.out.println("ChatRoom deleted"); CleanThread clean = new CleanThread(this.js, chatRoom.name); Thread th = new Thread(clean); th.start(); } else finished=true; }while(!finished); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } } }
UTF-8
Java
9,982
java
Chat.java
Java
[ { "context": "emplate, null, Lease.FOREVER);\n\t\t\t\tthis.username = username;\n\t\t\t\tSystem.out.println(\"User created.\");\n\t\t\t\tret", "end": 2500, "score": 0.8608289957046509, "start": 2492, "tag": "USERNAME", "value": "username" } ]
null
[]
package it.polimi.mini; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.rmi.RemoteException; import net.jini.core.discovery.LookupLocator; import net.jini.core.entry.UnusableEntryException; import net.jini.core.lease.Lease; import net.jini.core.lookup.ServiceRegistrar; import net.jini.core.lookup.ServiceTemplate; import net.jini.core.transaction.TransactionException; import net.jini.space.JavaSpace; public class Chat { private JavaSpace js; private String username; public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); String choice = "", username = ""; int c = 0; boolean registered, failed; Chat chat = new Chat(); chat.discoverJavaSpace(); //register the user to the system do{ System.out.println("Insert username: "); username = systemInput.readLine(); registered = chat.registerUser(username); }while(!registered); do{ System.out.println("Select the action:"); System.out.println("\t1 - Create chat room"); System.out.println("\t2 - Enter existing chat room"); System.out.println("\t3 - Delete chat room"); System.out.println("\t0 - Exit"); choice = systemInput.readLine(); c = getChoice(choice); switch(c){ case 1: { chat.createChatRoom(); break; } case 2: { failed = chat.enterChatRoom(); if(failed) System.out.println("Chat room doesn't exist."); break; } case 3: { chat.deleteChatRoom(); break; } } }while(c != 0); //delete the user from the system chat.deleteAllChatroom(username); chat.deleteUser(username); System.exit(0); } private void deleteUser(String username) { UserEntry userTemplate = new UserEntry(username); try { this.js.take(userTemplate, null, Lease.FOREVER); } catch (RemoteException e) { e.printStackTrace(); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean registerUser(String username) { try { UserEntry userTemplate = new UserEntry(username); UserEntry user = (UserEntry) js.readIfExists(userTemplate, null, Lease.FOREVER); if(user == null) { js.write(userTemplate, null, Lease.FOREVER); this.username = username; System.out.println("User created."); return true; } else { System.out.println("User already exists."); return false; } } catch (RemoteException e) { e.printStackTrace(); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } public static int getChoice(String str) { if(str.equals("1")) return 1; if(str.equals("2")) return 2; if(str.equals("3")) return 3; if(str.equals("0")) return 0; return -1; } private void discoverJavaSpace() { while (js==null) { try { LookupLocator locator = new LookupLocator("jini://localhost"); ServiceRegistrar registrar = locator.getRegistrar(); js = (JavaSpace) registrar.lookup( new ServiceTemplate(null, new Class[] {JavaSpace.class}, null)); } catch (Exception exc) { exc.printStackTrace(); } } } private void createChatRoom() throws IOException{ InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); System.out.println("Specify the name of the new chat room: "); String input = systemInput.readLine(); ChatRoomEntry chatRoom; try { ChatRoomEntry template = new ChatRoomEntry(input, null, null); chatRoom = (ChatRoomEntry) js.readIfExists(template, null, Lease.FOREVER); if(chatRoom == null){ template = new ChatRoomEntry(input, this.username, 0); js.write(template, null, Lease.FOREVER); System.out.println("Chat Room created."); ChatManagerEntry chatmanager=new ChatManagerEntry(),templateManager=new ChatManagerEntry(null); chatmanager=(ChatManagerEntry)js.takeIfExists(templateManager, null, 1000); if(chatmanager==null) chatmanager=new ChatManagerEntry(); chatmanager.chatrooms.add(template.name); js.write(chatmanager, null, Lease.FOREVER); } else System.out.println("Chat Room already exists."); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean enterChatRoom() throws IOException{ boolean failed = true; try { String chatRoom,message; int i; InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); ChatManagerEntry templateManager=new ChatManagerEntry(null),chatmanager; chatmanager=(ChatManagerEntry)js.take(templateManager, null, Lease.FOREVER); js.write(chatmanager, null, Lease.FOREVER); for(i=0;i<chatmanager.chatrooms.size();i++) System.out.println("Chatroom "+i+" : "+chatmanager.chatrooms.get(i)); System.out.println("Specify the chatroom name: "); chatRoom = systemInput.readLine(); ChatRoomEntry template = new ChatRoomEntry(chatRoom, null, null); ChatRoomEntry chat; chat = (ChatRoomEntry) js.readIfExists(template, null, Lease.FOREVER); if(chat != null){ //correctly accessed the chatroom failed = false; System.out.println("How many messages do you want from this chat room ?"); int n=Integer.parseInt(systemInput.readLine()); ChatRoomEntry chatRoomObject = (ChatRoomEntry) js.take(template, null, Lease.FOREVER); if(n>chatRoomObject.msgNumber) n=chatRoomObject.msgNumber; for(i=0;i<n;i++){ MessageEntry messageTemplate=new MessageEntry(null,chatRoom,null,(Integer)chatRoomObject.msgNumber-n+i); MessageEntry messageObj=(MessageEntry)js.read(messageTemplate, null,Lease.FOREVER); messageObj.printMessage(); } js.write(chatRoomObject, null, Lease.FOREVER); ChatReader chatReader=new ChatReader(js,chatRoom,this.username); Thread t = new Thread(chatReader); t.start(); do{ message=systemInput.readLine(); if(!message.equals("exit")){ template = new ChatRoomEntry(chatRoom, null, null); chatRoomObject = (ChatRoomEntry) js.take(template, null, 2000); //if chatRoomObject is null then the chatroom has been deleted if(chatRoomObject!=null){ MessageEntry messageObject=new MessageEntry(message,chatRoom,this.username, chatRoomObject.msgNumber); chatRoomObject.msgNumber++; js.write(messageObject, null, Lease.FOREVER); js.write(chatRoomObject, null, Lease.FOREVER); } } }while(!message.equals("exit") && chatRoomObject!=null); chatReader.exit(); } } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return failed; } private void deleteChatRoom()throws IOException{ int i; ChatRoomEntry chatRoom; InputStreamReader reader = new InputStreamReader (System.in); BufferedReader systemInput = new BufferedReader (reader); try { ChatManagerEntry templateManager=new ChatManagerEntry(null),chatmanager; chatmanager=(ChatManagerEntry)js.take(templateManager, null, Lease.FOREVER); js.write(chatmanager, null, Lease.FOREVER); for(i=0;i<chatmanager.chatrooms.size();i++) System.out.println("Chatroom "+i+" : "+chatmanager.chatrooms.get(i)); System.out.println("Select a chat room to delete: "); String input = systemInput.readLine(); ChatRoomEntry template = new ChatRoomEntry(input, this.username, null); chatRoom = (ChatRoomEntry) js.take(template, null, 2000); if(chatRoom != null){ MessageEntry messageObject=new MessageEntry("Chatroom deleted, press enter to return to the menu...",chatRoom.name,this.username, chatRoom.msgNumber); js.write(messageObject, null, Lease.FOREVER); templateManager=new ChatManagerEntry(null); chatmanager=(ChatManagerEntry)js.take(templateManager, null, Lease.FOREVER); System.out.println("Rimosso: "+chatmanager.chatrooms.remove(chatRoom.name)); js.write(chatmanager, null, Lease.FOREVER); System.out.println("ChatRoom deleted"); CleanThread clean = new CleanThread(this.js, chatRoom.name); Thread th = new Thread(clean); th.start(); } else System.out.println("Chat Room not exists or you are not the creator of this chat room"); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private void deleteAllChatroom(String username) { ChatRoomEntry chatRoom; boolean finished=false; try { do{ ChatRoomEntry template = new ChatRoomEntry(null, this.username, null); chatRoom = (ChatRoomEntry) js.take(template, null, 2000); if(chatRoom != null){ MessageEntry messageObject=new MessageEntry("Chatroom deleted, press enter to return to the menu...",chatRoom.name,this.username, chatRoom.msgNumber); js.write(messageObject, null, Lease.FOREVER); System.out.println("ChatRoom deleted"); CleanThread clean = new CleanThread(this.js, chatRoom.name); Thread th = new Thread(clean); th.start(); } else finished=true; }while(!finished); } catch (UnusableEntryException e) { e.printStackTrace(); } catch (TransactionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } } }
9,982
0.697656
0.693749
308
31.40909
25.690367
154
false
false
0
0
0
0
0
0
3.756494
false
false
4
06435a5d37e267b036ebde5c8fbef873d5a6a448
23,029,614,651,416
d5f16e7642e10cdb7c53b96c9b62886b38ff352b
/machines/src/main/java/ru/tenet/service/TriggersManagerService.java
e665ce2cc566f8e3d819974e2b7fbdcf144e95c6
[]
no_license
VitaliyPivovarov/microservices
https://github.com/VitaliyPivovarov/microservices
e1467a68fff9e1dca3525422d56a10b9323413ca
e8d0e20a947b0811c6b46069b5ec8e544c399bb4
refs/heads/master
2019-03-17T06:12:20.205000
2018-02-27T14:06:14
2018-02-27T14:06:14
123,135,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.tenet.service; import ru.tenet.model.exception.AppException; import ru.tenet.rest.message.DeviceTriggering; import ru.tenet.rest.message.RequestForm; import ru.tenet.rest.message.TriggerInfo; import ru.tenet.rest.message.Triggering; import java.sql.SQLException; import java.text.ParseException; import java.util.List; public interface TriggersManagerService { List<TriggerInfo> getTriggers(String token); TriggerInfo createTrigger(String token, TriggerInfo newTrigger); boolean deleteTriggers(String token, Long triggerId); List<Triggering> getTriggering(String token, RequestForm request) throws ParseException, SQLException, AppException; List<DeviceTriggering> getDeviceTriggering(String token, RequestForm request) throws ParseException, SQLException, AppException; List<Triggering> getLastTriggering(Long subscriberID); }
UTF-8
Java
873
java
TriggersManagerService.java
Java
[]
null
[]
package ru.tenet.service; import ru.tenet.model.exception.AppException; import ru.tenet.rest.message.DeviceTriggering; import ru.tenet.rest.message.RequestForm; import ru.tenet.rest.message.TriggerInfo; import ru.tenet.rest.message.Triggering; import java.sql.SQLException; import java.text.ParseException; import java.util.List; public interface TriggersManagerService { List<TriggerInfo> getTriggers(String token); TriggerInfo createTrigger(String token, TriggerInfo newTrigger); boolean deleteTriggers(String token, Long triggerId); List<Triggering> getTriggering(String token, RequestForm request) throws ParseException, SQLException, AppException; List<DeviceTriggering> getDeviceTriggering(String token, RequestForm request) throws ParseException, SQLException, AppException; List<Triggering> getLastTriggering(Long subscriberID); }
873
0.812142
0.812142
26
32.576923
34.957306
132
false
false
0
0
0
0
0
0
0.884615
false
false
4
d1539bdfc64504502d4717bba5ac56f69110d677
23,356,032,197,711
b76b87d8a01c2ee5e06b05df36bc7f7917ffdbf0
/MailNotify/src/main/java/com/kafka/consumer/TheConsumer.java
310ab08853ed80f643d12d5e51f175d2a7d64d3b
[]
no_license
zuolang/java
https://github.com/zuolang/java
008f4797ae4c8d5a22f38282ae899159666c65b5
8f6fe026f77d94e5b90c0eeab7c0869a0bd6ab0a
refs/heads/master
2021-01-20T20:15:53.646000
2018-05-13T05:14:38
2018-05-13T05:14:38
62,728,849
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kafka.consumer; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import com.kafka.vo.KafkaMessage; /** * @author zuolang kafka消息消费者 * */ public class TheConsumer { public List<KafkaMessage> pull(String topic) throws Exception{ Properties pro = new Properties(); InputStream is = TheConsumer.class.getResourceAsStream("/kafka.properties"); pro.load(is); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(pro); List<KafkaMessage> list = new ArrayList<>(); consumer.subscribe(Arrays.asList(topic)); ConsumerRecords<String, String> records = consumer.poll(3000); System.out.println(topic+"数量:"+records.count()); for (ConsumerRecord<String,String> record : records) { KafkaMessage msg= new KafkaMessage(); msg.key=record.key(); msg.value=record.value(); msg.topic=record.topic(); list.add(msg); } consumer.close(); return list; } }
UTF-8
Java
1,224
java
TheConsumer.java
Java
[ { "context": "port com.kafka.vo.KafkaMessage;\r\n\r\n/**\r\n * @author zuolang kafka消息消费者\r\n *\r\n */\r\npublic class TheConsumer {\r\n", "end": 407, "score": 0.9995535612106323, "start": 400, "tag": "USERNAME", "value": "zuolang" } ]
null
[]
package com.kafka.consumer; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import com.kafka.vo.KafkaMessage; /** * @author zuolang kafka消息消费者 * */ public class TheConsumer { public List<KafkaMessage> pull(String topic) throws Exception{ Properties pro = new Properties(); InputStream is = TheConsumer.class.getResourceAsStream("/kafka.properties"); pro.load(is); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(pro); List<KafkaMessage> list = new ArrayList<>(); consumer.subscribe(Arrays.asList(topic)); ConsumerRecords<String, String> records = consumer.poll(3000); System.out.println(topic+"数量:"+records.count()); for (ConsumerRecord<String,String> record : records) { KafkaMessage msg= new KafkaMessage(); msg.key=record.key(); msg.value=record.value(); msg.topic=record.topic(); list.add(msg); } consumer.close(); return list; } }
1,224
0.72351
0.720199
40
28.200001
22.835499
82
false
false
0
0
0
0
0
0
1.75
false
false
4
c6af21e60a04abcbf4cd9e5a845e9fb8122cbd96
25,520,695,686,543
2494cf393a64dc9398ee7d9747270974d195a176
/tools/rspsi-map-editor/client/src/main/java/com/jagex/entity/model/PreviewModel.java
1a694fb15633c0489bffddf0dc0bfdd49894efbf
[]
no_license
chollandcloud/Dodian-OSRS
https://github.com/chollandcloud/Dodian-OSRS
927307430b3e41283b34001683ea2a3ce7316828
bc8b83366753de0d75a024508cd1db8f41a74758
refs/heads/master
2023-07-31T21:02:49.217000
2021-09-04T17:05:10
2021-09-04T17:05:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jagex.entity.model; public class PreviewModel extends Mesh { public PreviewModel(Mesh model) { super(); fitsOnSingleSquare = (model.fitsOnSingleSquare); minimumX = (model.minimumX); maximumX = (model.maximumX); maximumZ = (model.maximumZ); minimumZ = (model.minimumZ); boundingPlaneRadius = (model.boundingPlaneRadius); minimumY = (model.minimumY); boundingSphereRadius = (model.boundingSphereRadius); boundingCylinderRadius = (model.boundingCylinderRadius); anInt1654 = (model.anInt1654); shadedFaceColoursX = copyArray(model.shadedFaceColoursX); shadedFaceColoursY = copyArray(model.shadedFaceColoursY); shadedFaceColoursZ = copyArray(model.shadedFaceColoursZ); faceAlphas = copyArray(model.faceAlphas); faceColours = copyArray(model.faceColours); faceTextures = copyArray(model.faceTextures); texture_coordinates = copyArray(model.texture_coordinates); textureRenderTypes = copyArray(model.textureRenderTypes); faceGroups = copyArray(model.faceGroups); facePriorities = copyArray(model.facePriorities); numFaces = (model.numFaces); faceSkin = copyArray(model.faceSkin); faceIndicesA = copyArray(model.faceIndicesA); faceIndicesB = copyArray(model.faceIndicesB); faceIndicesC = copyArray(model.faceIndicesC); normals = (model.normals); facePriority = (model.facePriority); numTextures = model.numTextures; textureMappingP = copyArray(model.textureMappingP); textureMappingM = copyArray(model.textureMappingM); textureMappingN = copyArray(model.textureMappingN); faceTypes = copyArray(model.faceTypes); vertexGroups = copyArray(model.vertexGroups); vertexBones = copyArray(model.vertexBones); verticesX = copyArray(model.verticesX); verticesY = copyArray(model.verticesY); verticesZ = copyArray(model.verticesZ); numVertices = model.numVertices; } @Override public int getZVertexMax() { return 500; } }
UTF-8
Java
1,909
java
PreviewModel.java
Java
[]
null
[]
package com.jagex.entity.model; public class PreviewModel extends Mesh { public PreviewModel(Mesh model) { super(); fitsOnSingleSquare = (model.fitsOnSingleSquare); minimumX = (model.minimumX); maximumX = (model.maximumX); maximumZ = (model.maximumZ); minimumZ = (model.minimumZ); boundingPlaneRadius = (model.boundingPlaneRadius); minimumY = (model.minimumY); boundingSphereRadius = (model.boundingSphereRadius); boundingCylinderRadius = (model.boundingCylinderRadius); anInt1654 = (model.anInt1654); shadedFaceColoursX = copyArray(model.shadedFaceColoursX); shadedFaceColoursY = copyArray(model.shadedFaceColoursY); shadedFaceColoursZ = copyArray(model.shadedFaceColoursZ); faceAlphas = copyArray(model.faceAlphas); faceColours = copyArray(model.faceColours); faceTextures = copyArray(model.faceTextures); texture_coordinates = copyArray(model.texture_coordinates); textureRenderTypes = copyArray(model.textureRenderTypes); faceGroups = copyArray(model.faceGroups); facePriorities = copyArray(model.facePriorities); numFaces = (model.numFaces); faceSkin = copyArray(model.faceSkin); faceIndicesA = copyArray(model.faceIndicesA); faceIndicesB = copyArray(model.faceIndicesB); faceIndicesC = copyArray(model.faceIndicesC); normals = (model.normals); facePriority = (model.facePriority); numTextures = model.numTextures; textureMappingP = copyArray(model.textureMappingP); textureMappingM = copyArray(model.textureMappingM); textureMappingN = copyArray(model.textureMappingN); faceTypes = copyArray(model.faceTypes); vertexGroups = copyArray(model.vertexGroups); vertexBones = copyArray(model.vertexBones); verticesX = copyArray(model.verticesX); verticesY = copyArray(model.verticesY); verticesZ = copyArray(model.verticesZ); numVertices = model.numVertices; } @Override public int getZVertexMax() { return 500; } }
1,909
0.771084
0.765322
53
35.018867
18.482517
61
false
false
0
0
0
0
0
0
2.433962
false
false
4
3c9f3a52a52106f64fbe2788f87ff00b68e6c4a1
13,786,845,083,119
308020ff16274e92ddd10c3ce5af187397d1c41a
/app/src/main/java/com/example/rendapanda/MainActivity.java
b057cf24b6c0dd25e846d8db5c8d0731eff1344e
[]
no_license
m-o/rentapanda
https://github.com/m-o/rentapanda
f4ff1ef97f34a668aaeacab702febc9ca41097d8
e8c1912e8a4fe8b560dd6fdd7fe9323a440883f6
refs/heads/master
2016-09-12T15:58:03.036000
2016-04-16T07:50:47
2016-04-16T07:50:47
56,355,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.rendapanda; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Rect; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmResults; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; public class MainActivity extends AppCompatActivity implements NetworkCallback{ private String apiURL = "http://private-anon-927eb4af2-rentapanda.apiary-mock.com/jobs"; OkHttpClient client = new OkHttpClient(); // Create a RealmConfiguration which is to locate Realm file in package's "files" directory. RealmConfiguration realmConfig; // Get a Realm instance for this thread @Bind(R.id.recycler_view) RecyclerView recyclerView; private JobsAdapter adapter; private RecyclerView.LayoutManager layoutManager; private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); realmConfig = new RealmConfiguration.Builder(this.getApplicationContext()).build(); realm = Realm.getInstance(realmConfig); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); recyclerView.addItemDecoration(new SpacesItemDecoration(1)); adapter = new JobsAdapter(this); RealmResults<JobModel> jobs = realm.where(JobModel.class).findAll(); List<JobModel> copy = realm.copyFromRealm(jobs); adapter.putData(copy); recyclerView.setAdapter(adapter); } @Override protected void onResume(){ super.onResume(); try { requestJobList(this,this); } catch (IOException e) { e.printStackTrace(); } } private void requestJobList(final Context context, final NetworkCallback callback) throws IOException { Request request = new Request.Builder() .url(apiURL) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { mainHandler.post(new Runnable() { @Override public void run() { NetworkErrorDialogFragment fragment = new NetworkErrorDialogFragment(context,callback); fragment.show(getSupportFragmentManager(),"NetworkErrorFragment"); } }); } @Override public void onResponse(Call call,Response response) throws IOException { final String myResponse = response.body().string(); mainHandler.post(new Runnable() { @Override public void run() { saveResponseToRealm(myResponse); showData(); } }); } Handler mainHandler = new Handler(context.getMainLooper()); }); } private void saveResponseToRealm(String responseBody){ Realm realm = Realm.getInstance(realmConfig); realm.beginTransaction(); realm.clear(JobModel.class); realm.createAllFromJson(JobModel.class,responseBody); realm.commitTransaction(); realm.close(); } private void showData(){ Realm realm = Realm.getInstance(realmConfig); RealmResults<JobModel> jobs = realm.where(JobModel.class).findAll(); jobs.sort("job_date"); List<JobModel> copy = realm.copyFromRealm(jobs); adapter.putData(copy); realm.close(); } @Override protected void onDestroy(){ super.onDestroy(); realm.close(); } @Override public void loadData() { try { requestJobList(this,this); } catch (IOException e) { e.printStackTrace(); } } public class SpacesItemDecoration extends RecyclerView.ItemDecoration { private int space; public SpacesItemDecoration(int space) { this.space = space; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = space; outRect.right = space; outRect.bottom = space; // Add top margin only for the first item to avoid double space between items if(parent.getChildAdapterPosition(view) == 0) outRect.top = space; } } }
UTF-8
Java
5,410
java
MainActivity.java
Java
[]
null
[]
package com.example.rendapanda; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Rect; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmResults; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; public class MainActivity extends AppCompatActivity implements NetworkCallback{ private String apiURL = "http://private-anon-927eb4af2-rentapanda.apiary-mock.com/jobs"; OkHttpClient client = new OkHttpClient(); // Create a RealmConfiguration which is to locate Realm file in package's "files" directory. RealmConfiguration realmConfig; // Get a Realm instance for this thread @Bind(R.id.recycler_view) RecyclerView recyclerView; private JobsAdapter adapter; private RecyclerView.LayoutManager layoutManager; private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); realmConfig = new RealmConfiguration.Builder(this.getApplicationContext()).build(); realm = Realm.getInstance(realmConfig); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); recyclerView.addItemDecoration(new SpacesItemDecoration(1)); adapter = new JobsAdapter(this); RealmResults<JobModel> jobs = realm.where(JobModel.class).findAll(); List<JobModel> copy = realm.copyFromRealm(jobs); adapter.putData(copy); recyclerView.setAdapter(adapter); } @Override protected void onResume(){ super.onResume(); try { requestJobList(this,this); } catch (IOException e) { e.printStackTrace(); } } private void requestJobList(final Context context, final NetworkCallback callback) throws IOException { Request request = new Request.Builder() .url(apiURL) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { mainHandler.post(new Runnable() { @Override public void run() { NetworkErrorDialogFragment fragment = new NetworkErrorDialogFragment(context,callback); fragment.show(getSupportFragmentManager(),"NetworkErrorFragment"); } }); } @Override public void onResponse(Call call,Response response) throws IOException { final String myResponse = response.body().string(); mainHandler.post(new Runnable() { @Override public void run() { saveResponseToRealm(myResponse); showData(); } }); } Handler mainHandler = new Handler(context.getMainLooper()); }); } private void saveResponseToRealm(String responseBody){ Realm realm = Realm.getInstance(realmConfig); realm.beginTransaction(); realm.clear(JobModel.class); realm.createAllFromJson(JobModel.class,responseBody); realm.commitTransaction(); realm.close(); } private void showData(){ Realm realm = Realm.getInstance(realmConfig); RealmResults<JobModel> jobs = realm.where(JobModel.class).findAll(); jobs.sort("job_date"); List<JobModel> copy = realm.copyFromRealm(jobs); adapter.putData(copy); realm.close(); } @Override protected void onDestroy(){ super.onDestroy(); realm.close(); } @Override public void loadData() { try { requestJobList(this,this); } catch (IOException e) { e.printStackTrace(); } } public class SpacesItemDecoration extends RecyclerView.ItemDecoration { private int space; public SpacesItemDecoration(int space) { this.space = space; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = space; outRect.right = space; outRect.bottom = space; // Add top margin only for the first item to avoid double space between items if(parent.getChildAdapterPosition(view) == 0) outRect.top = space; } } }
5,410
0.629575
0.626248
169
31.011835
25.323935
115
false
false
0
0
0
0
0
0
0.568047
false
false
4
94f75adb0464c8f0a035c0b8eb80d8833e8e70af
16,862,041,608,818
f69803960559dcca8e1044f9f7df0ec8ee1e6065
/app/src/main/java/org/ecosia/ecosiatestapp/viewmodel/BaseViewModel.java
e5cf925e9ba2f1735b7b986954e6484bc36a8a6f
[]
no_license
mugheesanwar93/EcosiaTestApp
https://github.com/mugheesanwar93/EcosiaTestApp
4f2325d386a651eaca11b9e5872c4c48a94b1e37
6f1320337658e87495d015fa39ef6250d7d4a5a1
refs/heads/master
2020-04-07T05:18:59.371000
2018-11-18T14:32:57
2018-11-18T14:32:57
158,092,211
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.ecosia.ecosiatestapp.viewmodel; import android.annotation.SuppressLint; import android.app.Activity; import android.databinding.BaseObservable; import java.text.SimpleDateFormat; import java.util.Date; class BaseViewModel extends BaseObservable { @SuppressLint("SimpleDateFormat") String changeTimeFormat(int time) { return new SimpleDateFormat("m:ss").format(new Date(time)); } }
UTF-8
Java
419
java
BaseViewModel.java
Java
[]
null
[]
package org.ecosia.ecosiatestapp.viewmodel; import android.annotation.SuppressLint; import android.app.Activity; import android.databinding.BaseObservable; import java.text.SimpleDateFormat; import java.util.Date; class BaseViewModel extends BaseObservable { @SuppressLint("SimpleDateFormat") String changeTimeFormat(int time) { return new SimpleDateFormat("m:ss").format(new Date(time)); } }
419
0.77327
0.77327
18
22.277779
21.036491
67
false
false
0
0
0
0
0
0
0.388889
false
false
4
8076c36a32178b28c1a1bd1952a7a8947bff6afd
14,671,608,314,392
d83f61c3185d5a6e65cd55429be25c877ba3d712
/server/src/main/java/com/dianwoba/bigdata/redis/canal/server/Connection.java
22b719b2b1acb574aa5b481132b025d58e11b04d
[]
no_license
keyganker/redis-canal
https://github.com/keyganker/redis-canal
a1c01da8dc5403d3927404360a79afc28339b7b6
001ed02f1a396d7836c0da657767e71fc580c8a1
refs/heads/master
2021-06-17T08:51:51.581000
2017-05-25T07:39:27
2017-05-25T07:39:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dianwoba.bigdata.redis.canal.server; import com.dianwoba.bigdata.redis.canal.server.exception.RedisConnectionException; import com.dianwoba.bigdata.redis.canal.server.exception.RedisDataException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; /** * Created by Silas. * Date: 2017/3/21 * Time: 16:47 */ public class Connection implements Closeable { private static final byte[][] EMPTY_ARGS = new byte[0][]; private String host = "localhost"; private int port = 6379; private String pwd = ""; private Socket socket; private RedisOutputStream outputStream; private RedisInputStream inputStream; private int pipelinedCommands = 0; private int connectionTimeout = 10000; private int soTimeout = 0; private boolean broken = false; private boolean ssl; private SSLSocketFactory sslSocketFactory; private SSLParameters sslParameters; private HostnameVerifier hostnameVerifier; private Long offset = -1L; public Connection() { } public Connection(String host) { this.host = host; } public Connection(String host, int port) { this.host = host; this.port = port; } public Connection(String host, int port, String pwd) { this.host = host; this.port = port; this.pwd = pwd; } public Connection(String host, int port, boolean ssl) { this.host = host; this.port = port; this.ssl = ssl; } public Connection(String host, int port, boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, HostnameVerifier hostnameVerifier) { this.host = host; this.port = port; this.ssl = ssl; this.sslSocketFactory = sslSocketFactory; this.sslParameters = sslParameters; this.hostnameVerifier = hostnameVerifier; } public Long getOffset() { return offset; } public void setOffset(Long offset) { this.offset = offset; } public Socket getSocket() { return this.socket; } public int getConnectionTimeout() { return this.connectionTimeout; } public int getSoTimeout() { return this.soTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public void setTimeoutInfinite() { try { if (!this.isConnected()) { this.connect(); } this.socket.setSoTimeout(0); } catch (SocketException var2) { this.broken = true; throw new RedisConnectionException(var2); } } public RedisInputStream getInputStream() { return inputStream; } public void rollbackTimeout() { try { this.socket.setSoTimeout(this.soTimeout); } catch (SocketException var2) { this.broken = true; throw new RedisConnectionException(var2); } } public Connection sendCommand(Protocol.Command cmd, String... args) { byte[][] bargs = new byte[args.length][]; for (int i = 0; i < args.length; ++i) { bargs[i] = SafeEncoder.encode(args[i]); } return this.sendCommand(cmd, bargs); } public Connection sendCommand(Protocol.Command cmd) { return this.sendCommand(cmd, EMPTY_ARGS); } protected Connection sendCommand(Protocol.Command cmd, byte[]... args) { try { this.connect(); Protocol.sendCommand(this.outputStream, cmd, args); ++this.pipelinedCommands; return this; } catch (RedisConnectionException var6) { RedisConnectionException ex = var6; try { String errorMessage = Protocol.readErrorLineIfPossible(this.inputStream); if (errorMessage != null && errorMessage.length() > 0) { ex = new RedisConnectionException(errorMessage, ex.getCause()); } } catch (Exception var5) { ; } this.broken = true; throw ex; } } public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public Connection connect() { if (!this.isConnected()) { try { this.socket = new Socket(); this.socket.setReuseAddress(true); this.socket.setKeepAlive(true); this.socket.setTcpNoDelay(true); this.socket.setSoLinger(true, 0); this.socket.connect(new InetSocketAddress(this.host, this.port), this.connectionTimeout); this.socket.setSoTimeout(this.soTimeout); if (this.ssl) { if (null == this.sslSocketFactory) { this.sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } this.socket = (SSLSocket) this.sslSocketFactory.createSocket(this.socket, this.host, this.port, true); if (null != this.sslParameters) { ((SSLSocket) this.socket).setSSLParameters(this.sslParameters); } if (null != this.hostnameVerifier && !this.hostnameVerifier.verify(this.host, ((SSLSocket) this.socket).getSession())) { String ex = String.format("The connection to \'%s\' failed ssl/tls hostname verification.", new Object[]{this.host}); throw new RedisConnectionException(ex); } } this.outputStream = new RedisOutputStream(this.socket.getOutputStream()); this.inputStream = new RedisInputStream(this.socket.getInputStream()); } catch (IOException var2) { this.broken = true; throw new RedisConnectionException(var2); } } return this; } public void close() { this.disconnect(); } public void disconnect() { if (this.isConnected()) { try { this.outputStream.flush(); this.socket.close(); } catch (IOException var5) { this.broken = true; throw new RedisConnectionException(var5); } finally { IOUtils.closeQuietly(this.socket); } } } public boolean isConnected() { return this.socket != null && this.socket.isBound() && !this.socket.isClosed() && this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown(); } public String getStatusCodeReply() { this.flush(); --this.pipelinedCommands; byte[] resp = (byte[]) ((byte[]) this.readProtocolWithCheckingBroken()); return null == resp ? null : SafeEncoder.encode(resp); } public String getBulkReply() { byte[] result = this.getBinaryBulkReply(); return null != result ? SafeEncoder.encode(result) : null; } public byte[] getBinaryBulkReply() { this.flush(); --this.pipelinedCommands; return (byte[]) ((byte[]) this.readProtocolWithCheckingBroken()); } public Long getIntegerReply() { this.flush(); --this.pipelinedCommands; return (Long) this.readProtocolWithCheckingBroken(); } /* public List<String> getMultiBulkReply() { return (List) BuilderFactory.STRING_LIST.build(this.getBinaryMultiBulkReply()); }*/ public List<byte[]> getBinaryMultiBulkReply() { this.flush(); --this.pipelinedCommands; return (List) this.readProtocolWithCheckingBroken(); } public void resetPipelinedCount() { this.pipelinedCommands = 0; } public List<Object> getRawObjectMultiBulkReply() { return (List) this.readProtocolWithCheckingBroken(); } public List<Object> getObjectMultiBulkReply() { this.flush(); --this.pipelinedCommands; return this.getRawObjectMultiBulkReply(); } public List<Long> getIntegerMultiBulkReply() { this.flush(); --this.pipelinedCommands; return (List) this.readProtocolWithCheckingBroken(); } public List<Object> getAll() { return this.getAll(0); } public List<Object> getAll(int except) { ArrayList all = new ArrayList(); this.flush(); for (; this.pipelinedCommands > except; --this.pipelinedCommands) { try { all.add(this.readProtocolWithCheckingBroken()); } catch (RedisDataException var4) { all.add(var4); } } return all; } public Object getOne() { this.flush(); --this.pipelinedCommands; return this.readProtocolWithCheckingBroken(); } public boolean isBroken() { return this.broken; } protected void flush() { try { this.outputStream.flush(); } catch (IOException var2) { this.broken = true; throw new RedisConnectionException(var2); } } protected Object readProtocolWithCheckingBroken() { try { return Protocol.read(this.inputStream); } catch (RedisConnectionException var2) { this.broken = true; throw var2; } } public Connection auth() { if (this.pwd != null && !"".equals(this.pwd)) { this.sendCommand(Protocol.Command.AUTH, this.pwd); this.getStatusCodeReply(); } return this; } public Connection ping() { this.sendCommand(Protocol.Command.PING); // System.out.println("ping:" + this.getStatusCodeReply()); return this; } public Connection replconf(Long offset) { this.setOffset(offset); this.sendCommand(Protocol.Command.REPLCONF, "ACK", this.offset.toString()); return this; } }
UTF-8
Java
10,621
java
Connection.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Silas.\n * Date: 2017/3/21\n * Time: 16:47\n */\npublic cla", "end": 578, "score": 0.9953539371490479, "start": 573, "tag": "NAME", "value": "Silas" } ]
null
[]
package com.dianwoba.bigdata.redis.canal.server; import com.dianwoba.bigdata.redis.canal.server.exception.RedisConnectionException; import com.dianwoba.bigdata.redis.canal.server.exception.RedisDataException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; /** * Created by Silas. * Date: 2017/3/21 * Time: 16:47 */ public class Connection implements Closeable { private static final byte[][] EMPTY_ARGS = new byte[0][]; private String host = "localhost"; private int port = 6379; private String pwd = ""; private Socket socket; private RedisOutputStream outputStream; private RedisInputStream inputStream; private int pipelinedCommands = 0; private int connectionTimeout = 10000; private int soTimeout = 0; private boolean broken = false; private boolean ssl; private SSLSocketFactory sslSocketFactory; private SSLParameters sslParameters; private HostnameVerifier hostnameVerifier; private Long offset = -1L; public Connection() { } public Connection(String host) { this.host = host; } public Connection(String host, int port) { this.host = host; this.port = port; } public Connection(String host, int port, String pwd) { this.host = host; this.port = port; this.pwd = pwd; } public Connection(String host, int port, boolean ssl) { this.host = host; this.port = port; this.ssl = ssl; } public Connection(String host, int port, boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, HostnameVerifier hostnameVerifier) { this.host = host; this.port = port; this.ssl = ssl; this.sslSocketFactory = sslSocketFactory; this.sslParameters = sslParameters; this.hostnameVerifier = hostnameVerifier; } public Long getOffset() { return offset; } public void setOffset(Long offset) { this.offset = offset; } public Socket getSocket() { return this.socket; } public int getConnectionTimeout() { return this.connectionTimeout; } public int getSoTimeout() { return this.soTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public void setTimeoutInfinite() { try { if (!this.isConnected()) { this.connect(); } this.socket.setSoTimeout(0); } catch (SocketException var2) { this.broken = true; throw new RedisConnectionException(var2); } } public RedisInputStream getInputStream() { return inputStream; } public void rollbackTimeout() { try { this.socket.setSoTimeout(this.soTimeout); } catch (SocketException var2) { this.broken = true; throw new RedisConnectionException(var2); } } public Connection sendCommand(Protocol.Command cmd, String... args) { byte[][] bargs = new byte[args.length][]; for (int i = 0; i < args.length; ++i) { bargs[i] = SafeEncoder.encode(args[i]); } return this.sendCommand(cmd, bargs); } public Connection sendCommand(Protocol.Command cmd) { return this.sendCommand(cmd, EMPTY_ARGS); } protected Connection sendCommand(Protocol.Command cmd, byte[]... args) { try { this.connect(); Protocol.sendCommand(this.outputStream, cmd, args); ++this.pipelinedCommands; return this; } catch (RedisConnectionException var6) { RedisConnectionException ex = var6; try { String errorMessage = Protocol.readErrorLineIfPossible(this.inputStream); if (errorMessage != null && errorMessage.length() > 0) { ex = new RedisConnectionException(errorMessage, ex.getCause()); } } catch (Exception var5) { ; } this.broken = true; throw ex; } } public String getHost() { return this.host; } public void setHost(String host) { this.host = host; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public Connection connect() { if (!this.isConnected()) { try { this.socket = new Socket(); this.socket.setReuseAddress(true); this.socket.setKeepAlive(true); this.socket.setTcpNoDelay(true); this.socket.setSoLinger(true, 0); this.socket.connect(new InetSocketAddress(this.host, this.port), this.connectionTimeout); this.socket.setSoTimeout(this.soTimeout); if (this.ssl) { if (null == this.sslSocketFactory) { this.sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } this.socket = (SSLSocket) this.sslSocketFactory.createSocket(this.socket, this.host, this.port, true); if (null != this.sslParameters) { ((SSLSocket) this.socket).setSSLParameters(this.sslParameters); } if (null != this.hostnameVerifier && !this.hostnameVerifier.verify(this.host, ((SSLSocket) this.socket).getSession())) { String ex = String.format("The connection to \'%s\' failed ssl/tls hostname verification.", new Object[]{this.host}); throw new RedisConnectionException(ex); } } this.outputStream = new RedisOutputStream(this.socket.getOutputStream()); this.inputStream = new RedisInputStream(this.socket.getInputStream()); } catch (IOException var2) { this.broken = true; throw new RedisConnectionException(var2); } } return this; } public void close() { this.disconnect(); } public void disconnect() { if (this.isConnected()) { try { this.outputStream.flush(); this.socket.close(); } catch (IOException var5) { this.broken = true; throw new RedisConnectionException(var5); } finally { IOUtils.closeQuietly(this.socket); } } } public boolean isConnected() { return this.socket != null && this.socket.isBound() && !this.socket.isClosed() && this.socket.isConnected() && !this.socket.isInputShutdown() && !this.socket.isOutputShutdown(); } public String getStatusCodeReply() { this.flush(); --this.pipelinedCommands; byte[] resp = (byte[]) ((byte[]) this.readProtocolWithCheckingBroken()); return null == resp ? null : SafeEncoder.encode(resp); } public String getBulkReply() { byte[] result = this.getBinaryBulkReply(); return null != result ? SafeEncoder.encode(result) : null; } public byte[] getBinaryBulkReply() { this.flush(); --this.pipelinedCommands; return (byte[]) ((byte[]) this.readProtocolWithCheckingBroken()); } public Long getIntegerReply() { this.flush(); --this.pipelinedCommands; return (Long) this.readProtocolWithCheckingBroken(); } /* public List<String> getMultiBulkReply() { return (List) BuilderFactory.STRING_LIST.build(this.getBinaryMultiBulkReply()); }*/ public List<byte[]> getBinaryMultiBulkReply() { this.flush(); --this.pipelinedCommands; return (List) this.readProtocolWithCheckingBroken(); } public void resetPipelinedCount() { this.pipelinedCommands = 0; } public List<Object> getRawObjectMultiBulkReply() { return (List) this.readProtocolWithCheckingBroken(); } public List<Object> getObjectMultiBulkReply() { this.flush(); --this.pipelinedCommands; return this.getRawObjectMultiBulkReply(); } public List<Long> getIntegerMultiBulkReply() { this.flush(); --this.pipelinedCommands; return (List) this.readProtocolWithCheckingBroken(); } public List<Object> getAll() { return this.getAll(0); } public List<Object> getAll(int except) { ArrayList all = new ArrayList(); this.flush(); for (; this.pipelinedCommands > except; --this.pipelinedCommands) { try { all.add(this.readProtocolWithCheckingBroken()); } catch (RedisDataException var4) { all.add(var4); } } return all; } public Object getOne() { this.flush(); --this.pipelinedCommands; return this.readProtocolWithCheckingBroken(); } public boolean isBroken() { return this.broken; } protected void flush() { try { this.outputStream.flush(); } catch (IOException var2) { this.broken = true; throw new RedisConnectionException(var2); } } protected Object readProtocolWithCheckingBroken() { try { return Protocol.read(this.inputStream); } catch (RedisConnectionException var2) { this.broken = true; throw var2; } } public Connection auth() { if (this.pwd != null && !"".equals(this.pwd)) { this.sendCommand(Protocol.Command.AUTH, this.pwd); this.getStatusCodeReply(); } return this; } public Connection ping() { this.sendCommand(Protocol.Command.PING); // System.out.println("ping:" + this.getStatusCodeReply()); return this; } public Connection replconf(Long offset) { this.setOffset(offset); this.sendCommand(Protocol.Command.REPLCONF, "ACK", this.offset.toString()); return this; } }
10,621
0.589963
0.585538
367
27.940054
26.716326
185
false
false
0
0
0
0
0
0
0.498638
false
false
4
a4b37e7838c30c5aa8f16e1738cf3a9a5032c7df
25,116,968,752,200
ec2c44d8897d4382ebc0e369f40493cae566463e
/QueQiaoXian/src/zhp/iyalee2/Activity_UpdateProfile.java
1c736df28fcb432609bf398edf1a066d51d2d37e
[]
no_license
GeniusVJR/SpiritWorld
https://github.com/GeniusVJR/SpiritWorld
7cfe47c566c521b076b173cf4f19b1482a6560df
4e7c47a7f867f18b0d7deb243709e03619cca49c
refs/heads/master
2021-01-17T16:45:07.884000
2017-08-06T14:06:25
2017-08-06T14:06:25
61,274,047
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package zhp.iyalee2; import zhp.android.activities.SlidingFinishActionBarActivity; import zhp.android.data.CurrentUser; import zhp.android.utils.Utils_Activity; import zhp.iyalee2.utils.Utils_UpdateUserProfile; import android.graphics.Color; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Activity_UpdateProfile extends SlidingFinishActionBarActivity { Button btn_confirm; Toolbar toolbar; EditText et_profile; String newProfile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_profile); findViews(); initToolBar(); } /** * 找到Views */ private void findViews() { btn_confirm = (Button) findViewById(R.id.activity_updateProfile_confirm); toolbar = (Toolbar) findViewById(R.id.activity_updateProfile_toolBar); et_profile = (EditText) findViewById(R.id.activity_updateProfile_profile); } private void initToolBar() { toolbar.setTitle("修改签名"); // 需要在setSupportActionBar()之前 toolbar.setTitleTextColor(Color.rgb(255, 255, 255)); if (toolbar != null) { setSupportActionBar(toolbar); } Utils_Activity.getInstance().setToolBarBellowStateBar(this, toolbar); Utils_Activity.getInstance().setStateBarColor(this, getResources().getColor(R.color.colorPrimaryDark)); } public void onConfirmClick(View view) { newProfile = et_profile.getText().toString(); // 如果长度合法 if (newProfile != null) { btn_confirm.setEnabled(false); new Utils_UpdateUserProfile(){ @Override public void whenCannotConnToServer() { Toast.makeText(getApplication(), "无法连接服务器!", Toast.LENGTH_SHORT).show(); btn_confirm.setEnabled(true); } @Override public void whenUpdateFinish() { Toast.makeText(getApplication(), "修改完成!", Toast.LENGTH_SHORT).show(); btn_confirm.setEnabled(true); } }.update(CurrentUser.getUserName(), CurrentUser.getPassword(), newProfile); } } }
UTF-8
Java
2,218
java
Activity_UpdateProfile.java
Java
[]
null
[]
package zhp.iyalee2; import zhp.android.activities.SlidingFinishActionBarActivity; import zhp.android.data.CurrentUser; import zhp.android.utils.Utils_Activity; import zhp.iyalee2.utils.Utils_UpdateUserProfile; import android.graphics.Color; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Activity_UpdateProfile extends SlidingFinishActionBarActivity { Button btn_confirm; Toolbar toolbar; EditText et_profile; String newProfile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_profile); findViews(); initToolBar(); } /** * 找到Views */ private void findViews() { btn_confirm = (Button) findViewById(R.id.activity_updateProfile_confirm); toolbar = (Toolbar) findViewById(R.id.activity_updateProfile_toolBar); et_profile = (EditText) findViewById(R.id.activity_updateProfile_profile); } private void initToolBar() { toolbar.setTitle("修改签名"); // 需要在setSupportActionBar()之前 toolbar.setTitleTextColor(Color.rgb(255, 255, 255)); if (toolbar != null) { setSupportActionBar(toolbar); } Utils_Activity.getInstance().setToolBarBellowStateBar(this, toolbar); Utils_Activity.getInstance().setStateBarColor(this, getResources().getColor(R.color.colorPrimaryDark)); } public void onConfirmClick(View view) { newProfile = et_profile.getText().toString(); // 如果长度合法 if (newProfile != null) { btn_confirm.setEnabled(false); new Utils_UpdateUserProfile(){ @Override public void whenCannotConnToServer() { Toast.makeText(getApplication(), "无法连接服务器!", Toast.LENGTH_SHORT).show(); btn_confirm.setEnabled(true); } @Override public void whenUpdateFinish() { Toast.makeText(getApplication(), "修改完成!", Toast.LENGTH_SHORT).show(); btn_confirm.setEnabled(true); } }.update(CurrentUser.getUserName(), CurrentUser.getPassword(), newProfile); } } }
2,218
0.721038
0.715477
72
27.972221
23.915924
78
false
false
0
0
0
0
0
0
2.208333
false
false
4
031beef671675967988718a6d03d9a8411462984
24,103,356,496,099
e709b4276db0d01b7d8e1932d9ea667ea20398e4
/JAVA_COLECTIONS/queue/src/main/java/queues/Exercicio.java
2fca6aab3fd77dc496a5ab7cce1310a25c3841cf
[]
no_license
NirsoItu/Curso_Java_Basico_Avancado
https://github.com/NirsoItu/Curso_Java_Basico_Avancado
8c9cc9afd8581d168a1ff563b334037826698ba1
b85f780c75b5ab2f28eaac5ed0c582fd47b01c19
refs/heads/master
2022-12-30T05:48:57.171000
2020-10-07T02:16:21
2020-10-07T02:16:21
301,904,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package queues; import com.sun.javafx.scene.layout.region.SliceSequenceConverter; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class Exercicio { public static void main(String[] args) { Queue<String> fila = new LinkedList<>(); fila.add("Juliana"); fila.add("Pedro"); fila.add("Carlos"); fila.add("Larissa"); fila.add("João"); System.out.println("Navegando pelos nomes..."); for(String nome:fila){ System.out.println("Nome: " + nome); } System.out.println(""); String primeiroNomeDaFila = fila.peek(); System.out.println("Primeiro nome sem remover: "+primeiroNomeDaFila); System.out.println(fila); System.out.println(""); String removendoPrimeiro = fila.poll(); System.out.println("Removendo o primeiro nome: "+removendoPrimeiro); System.out.println(fila); System.out.println(""); System.out.println("Adicionando o nome Daniel"); fila.add("Daniel"); Iterator<String> iteratorFila = fila.iterator(); while (iteratorFila.hasNext()){ System.out.println(iteratorFila.next()); } System.out.printf("A lista possui %s elementos",fila.size()); System.out.println(""); if(fila.isEmpty()){ System.out.println("A lista está vazia"); } else { System.out.println("A lista não está vazia"); } if(fila.contains("Carlos")){ System.out.println("A fila contém o nome Carlos"); }else{ System.out.println("A fila não contém o nome Carlos"); } } }
UTF-8
Java
1,723
java
Exercicio.java
Java
[ { "context": "ng> fila = new LinkedList<>();\n\n fila.add(\"Juliana\");\n fila.add(\"Pedro\");\n fila.add(\"C", "end": 310, "score": 0.9997542500495911, "start": 303, "tag": "NAME", "value": "Juliana" }, { "context": ";\n\n fila.add(\"Juliana\");\n fila.add(\"Pedro\");\n fila.add(\"Carlos\");\n fila.add(\"", "end": 337, "score": 0.9997605681419373, "start": 332, "tag": "NAME", "value": "Pedro" }, { "context": "a\");\n fila.add(\"Pedro\");\n fila.add(\"Carlos\");\n fila.add(\"Larissa\");\n fila.add(", "end": 365, "score": 0.9997744560241699, "start": 359, "tag": "NAME", "value": "Carlos" }, { "context": "\");\n fila.add(\"Carlos\");\n fila.add(\"Larissa\");\n fila.add(\"João\");\n\n System.out.", "end": 394, "score": 0.9997393488883972, "start": 387, "tag": "NAME", "value": "Larissa" }, { "context": ");\n fila.add(\"Larissa\");\n fila.add(\"João\");\n\n System.out.println(\"Navegando pelos n", "end": 420, "score": 0.999791145324707, "start": 416, "tag": "NAME", "value": "João" }, { "context": ");\n\n System.out.println(\"Adicionando o nome Daniel\");\n fila.add(\"Daniel\");\n\n Iterator<", "end": 1050, "score": 0.999671459197998, "start": 1044, "tag": "NAME", "value": "Daniel" }, { "context": "n(\"Adicionando o nome Daniel\");\n fila.add(\"Daniel\");\n\n Iterator<String> iteratorFila = fila.", "end": 1078, "score": 0.9992350339889526, "start": 1072, "tag": "NAME", "value": "Daniel" }, { "context": "stá vazia\");\n }\n\n if(fila.contains(\"Carlos\")){\n System.out.println(\"A fila contém", "end": 1548, "score": 0.9992905259132385, "start": 1542, "tag": "NAME", "value": "Carlos" }, { "context": " System.out.println(\"A fila contém o nome Carlos\");\n }else{\n System.out.println(", "end": 1612, "score": 0.9992177486419678, "start": 1606, "tag": "NAME", "value": "Carlos" }, { "context": " System.out.println(\"A fila não contém o nome Carlos\");\n }\n }\n}\n", "end": 1694, "score": 0.9993661642074585, "start": 1688, "tag": "NAME", "value": "Carlos" } ]
null
[]
package queues; import com.sun.javafx.scene.layout.region.SliceSequenceConverter; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class Exercicio { public static void main(String[] args) { Queue<String> fila = new LinkedList<>(); fila.add("Juliana"); fila.add("Pedro"); fila.add("Carlos"); fila.add("Larissa"); fila.add("João"); System.out.println("Navegando pelos nomes..."); for(String nome:fila){ System.out.println("Nome: " + nome); } System.out.println(""); String primeiroNomeDaFila = fila.peek(); System.out.println("Primeiro nome sem remover: "+primeiroNomeDaFila); System.out.println(fila); System.out.println(""); String removendoPrimeiro = fila.poll(); System.out.println("Removendo o primeiro nome: "+removendoPrimeiro); System.out.println(fila); System.out.println(""); System.out.println("Adicionando o nome Daniel"); fila.add("Daniel"); Iterator<String> iteratorFila = fila.iterator(); while (iteratorFila.hasNext()){ System.out.println(iteratorFila.next()); } System.out.printf("A lista possui %s elementos",fila.size()); System.out.println(""); if(fila.isEmpty()){ System.out.println("A lista está vazia"); } else { System.out.println("A lista não está vazia"); } if(fila.contains("Carlos")){ System.out.println("A fila contém o nome Carlos"); }else{ System.out.println("A fila não contém o nome Carlos"); } } }
1,723
0.586247
0.586247
62
26.67742
22.954916
77
false
false
0
0
0
0
0
0
0.532258
false
false
4
55eaf95218b3267a6dfc3663eed38fa4bb21b32f
16,037,407,898,209
a72a51f9a50bd71a0da825e75989e3907ade3d07
/testweb/src/action/BlackBKUpdateAction.java
bf9a286c6519a47d36e137195aec2b97911e91ff
[]
no_license
DarthVadeer/testweb718a
https://github.com/DarthVadeer/testweb718a
2451e4ae54b6182c6d29969ebc29b3834c15a643
02bebe1eba3d5b56a20d0eadab99cb725aeaa570
refs/heads/master
2021-01-01T07:18:43.901000
2017-07-18T07:15:50
2017-07-18T07:15:50
97,566,481
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.BlacklistDao; import model.BlackList; import util.AppException; public class BlackBKUpdateAction extends HttpServlet { /** * Constructor of the object. */ public BlackBKUpdateAction() { super(); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); BlackList blacklist = new BlackList(); BlacklistDao bdao = new BlacklistDao(); boolean flag = false; String points = request.getParameter("BlackConPoint"); String id = request.getParameter("BlackId"); blacklist.setBlackConPoint(points); blacklist.setBlackID(id); blacklist.setBlackState(2); try { flag = bdao.BKRevokeUpdate(blacklist); } catch (AppException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter writer = response.getWriter(); if (flag) writer.println("1"); else writer.println("2"); writer.flush(); writer.close(); } }
UTF-8
Java
2,243
java
BlackBKUpdateAction.java
Java
[]
null
[]
package action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.BlacklistDao; import model.BlackList; import util.AppException; public class BlackBKUpdateAction extends HttpServlet { /** * Constructor of the object. */ public BlackBKUpdateAction() { super(); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); BlackList blacklist = new BlackList(); BlacklistDao bdao = new BlacklistDao(); boolean flag = false; String points = request.getParameter("BlackConPoint"); String id = request.getParameter("BlackId"); blacklist.setBlackConPoint(points); blacklist.setBlackID(id); blacklist.setBlackState(2); try { flag = bdao.BKRevokeUpdate(blacklist); } catch (AppException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter writer = response.getWriter(); if (flag) writer.println("1"); else writer.println("2"); writer.flush(); writer.close(); } }
2,243
0.694605
0.692822
88
24.488636
23.81319
116
false
false
0
0
0
0
0
0
1.409091
false
false
4
aa25264868c66e2f907fff348ef764b66dc73d49
31,190,052,526,355
b70f0da1b18b34b1d1964480704fa879771d0fbc
/src/main/java/cn/gaoyuan/demo/designpattern/single/enums/Singleton.java
b5ced271a57608b9d6fa57d252ed5db9c756c61b
[]
no_license
gaoyuan888/gaoyuan-demo
https://github.com/gaoyuan888/gaoyuan-demo
df4f304b0f9f2076b8b1c434bb0b01dee0a41b7a
9c3663f32cbb4f1d0a47a85b51fa073091c580a9
refs/heads/master
2022-07-01T04:44:07.611000
2020-02-27T02:21:10
2020-02-27T02:21:10
172,820,123
1
0
null
false
2022-06-21T01:59:27
2019-02-27T01:31:40
2020-02-27T02:21:21
2022-06-21T01:59:23
1,744
1
0
3
Java
false
false
package cn.gaoyuan.demo.designpattern.single.enums; /** * 功能描述: *JDK 版本:JDK1.5 起 * 是否 Lazy 初始化:否 * 是否多线程安全:是 * 实现难度:易 * @author yaoyizhou * @date 2019/4/11 15:05 * 描述:这种实现方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化。 * 这种方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。不过,由于 JDK1.5 之后才加入 enum 特性,用这种方式写不免让人感觉生疏,在实际工作中,也很少用。 * 不能通过 reflection attack 来调用私有构造方法。 */ public enum Singleton { INSTENCE; public void whateverMethod() { } }
UTF-8
Java
920
java
Singleton.java
Java
[ { "context": " * 是否 Lazy 初始化:否\n * 是否多线程安全:是\n * 实现难度:易\n * @author yaoyizhou\n * @date 2019/4/11 15:05\n * 描述:这种实现方式还没有被广泛采用,但这是", "end": 144, "score": 0.9988301396369934, "start": 135, "tag": "USERNAME", "value": "yaoyizhou" }, { "context": "简洁,自动支持序列化机制,绝对防止多次实例化。\n * 这种方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝", "end": 269, "score": 0.999228835105896, "start": 259, "tag": "NAME", "value": "Josh Bloch" } ]
null
[]
package cn.gaoyuan.demo.designpattern.single.enums; /** * 功能描述: *JDK 版本:JDK1.5 起 * 是否 Lazy 初始化:否 * 是否多线程安全:是 * 实现难度:易 * @author yaoyizhou * @date 2019/4/11 15:05 * 描述:这种实现方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化。 * 这种方式是 Effective Java 作者 <NAME> 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。不过,由于 JDK1.5 之后才加入 enum 特性,用这种方式写不免让人感觉生疏,在实际工作中,也很少用。 * 不能通过 reflection attack 来调用私有构造方法。 */ public enum Singleton { INSTENCE; public void whateverMethod() { } }
916
0.731225
0.701581
19
25.631578
33.553116
150
false
false
0
0
0
0
0
0
0.105263
false
false
4
9eff6b277c3f507badcdd996f09268003e909d07
1,236,950,627,534
e079e478034d59ac725e317cd296678497728ea3
/src/main/java/com/example/unquote/MainActivity.java
e1f75fab350d28a34d7e3ef0a91d58e94f243f32
[]
no_license
ShowBaba/Unquote
https://github.com/ShowBaba/Unquote
b6cbae51abb19feeabc2d01d052cadc467fe5233
185c0b80a59c4a1dc140dc331b3c93cc54b4e283
refs/heads/master
2022-11-14T02:13:29.092000
2020-06-24T14:36:13
2020-06-24T14:36:13
274,677,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.unquote; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.text.MessageFormat; import java.util.ArrayList; public class MainActivity<displaySize> extends AppCompatActivity { private static final String TAG = "SIZE_OF_ARRAY"; int currentQuestionIndex; int totalCorrect; int totalQuestions; ArrayList<Question> questions; // TODO 3-A: Declare View member variables ImageView questionImageView; TextView questionTextView; TextView questionsRemainingTextView; Button answer0Button; Button answer1Button; Button answer2Button; Button answer3Button; Button submitButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO 2-G: Show app icon in ActionBar getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setLogo(R.drawable.ic_unquote_icon); getSupportActionBar().setDisplayUseLogoEnabled(true); getSupportActionBar().setElevation(0); setContentView(R.layout.activity_main); // TODO 3-B: assign View member variables questionImageView = findViewById(R.id.iv_main_question_image); questionsRemainingTextView = findViewById(R.id.tv_main_questions_remaining_count); questionTextView = findViewById(R.id.tv_main_question_title); answer0Button = findViewById(R.id.btn_main_answer_0); answer1Button = findViewById(R.id.btn_main_answer_1); answer2Button = findViewById(R.id.btn_main_answer_2); answer3Button = findViewById(R.id.btn_main_answer_3); submitButton = findViewById(R.id.btn_main_submit_answer); // TODO 4-E: set onClickListener for each answer Button answer0Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(0); } }); answer1Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(1); } }); answer2Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(2); } }); answer3Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(3); } }); // TODO 5-A: set onClickListener for the submit answer Button submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSubmission(); } }); startNewGame(); } // TODO 3-F: displayQuestion(Question question) {...} void displayQuestion(Question question){ questionTextView.setText(question.questionText); questionImageView.setImageResource(question.imageId); answer0Button.setText(question.answer0); answer1Button.setText(question.answer1); answer2Button.setText(question.answer2); answer3Button.setText(question.answer3); } // TODO 3-C: displayQuestionsRemaining(int questionRemaining) {...} void displayQuestionsRemaining(int remainingQuestion){ questionsRemainingTextView.setText(String.format("%d", remainingQuestion)); } // TODO 4-A: onAnswerSelected(int answerSelected) {...} void onAnswerSelected(int playerChoice){ Question currentQuestion = getCurrentQuestion(); currentQuestion.playerAnswer = playerChoice; answer0Button.setText(currentQuestion.answer0); answer1Button.setText(currentQuestion.answer1); answer2Button.setText(currentQuestion.answer2); answer3Button.setText(currentQuestion.answer3); switch (playerChoice){ case 0: answer0Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer0)); // answer3Button.setBackgroundResource(R.color.btn_select); break; case 1: answer1Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer1)); // answer3Button.setBackgroundResource(R.color.btn_select); break; case 2: answer2Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer2)); // answer3Button.setBackgroundResource(R.color.btn_select); break; case 3: answer3Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer3)); // answer3Button.setBackgroundResource(R.color.btn_select); break; default: throw new IllegalStateException("Unexpected value: " + playerChoice); } } void onAnswerSubmission() { Question currentQuestion = getCurrentQuestion(); if (currentQuestion.isCorrect()) { totalCorrect = totalCorrect + 1; }else if (currentQuestion.playerAnswer == -1){ return; } questions.remove(currentQuestion); // TODO 3-D.i: Uncomment the line below after implementing displayQuestionsRemaining(int) displayQuestionsRemaining(questions.size()); if (questions.size() == 0) { String gameOverMessage = getGameOverMessage(totalCorrect, totalQuestions); // TODO 5-D: Show a popup instead AlertDialog.Builder gameOverDialogBuilder = new AlertDialog.Builder(MainActivity.this); gameOverDialogBuilder.setCancelable(false); gameOverDialogBuilder.setTitle("Game Over!"); gameOverDialogBuilder.setMessage(gameOverMessage); gameOverDialogBuilder.setPositiveButton("Play Again!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startNewGame(); } }); gameOverDialogBuilder.setNegativeButton("Quit Game", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { endGame(); } }); gameOverDialogBuilder.create().show(); // System.out.println(gameOverMessage); } else { chooseNewQuestion(); // TODO 3-H.i: uncomment after implementing displayQuestion(Question) displayQuestion(getCurrentQuestion()); } } // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) private void endGame() { finish(); System.exit(0); } void startNewGame() { questions = new ArrayList<>(); // TODO 2-H: Provide actual drawables for each of these questions! Question question0 = new Question(R.drawable.img_quote_0, "Pretty good advice,\n" + "and perhaps a scientist\n" + "did say it… Who\n" + "actually did?", "Albert Einstein", "Isaac Newton", "Rita Mae Brown", "Rosalind Franklin", 2); Question question1 = new Question(R.drawable.img_quote_1, "Was honest Abe\n" + "honestly quoted? Who\n" + "authored this pithy bit\n" + "of wisdom?", "Edward Stieglitz", "Maya Angelou", "Abraham Lincoln", "Ralph Waldo Emerson", 0); Question question2 = new Question(R.drawable.img_quote_2, "Easy advice to read,\n" + "difficult advice to\n" + "follow — who actually", "Martin Luther King Jr.", "Mother Teresa", "Fred Rogers", "Oprah Winfrey", 1); //question3 was removed to avoid controvasies found here: https://twitter.com/GoodPassport/status/1274310169418137600?s=20 /* Question question3 = new Question(R.drawable.img_quote_3, "Insanely inspiring,\n" + "insanely incorrect\n" + "(maybe). Who is the\n" + "true source of this\n" + "inspiration?", "Nelson Mandela", "Harriet Tubman", "Mahatma Gandhi", "Nicholas Klein", 3);*/ Question question4 = new Question(R.drawable.img_quote_4, "A peace worth striving\n" + "for — who actually\n" + "reminded us of this?", "Malala Yousafzai", "Martin Luther King Jr.", "Liu Xiaobo", "Dalai Lama", 1); Question question5 = new Question(R.drawable.img_quote_5, "Unfortunately, true —\n" + "but did Marilyn Monroe\n" + "convey it or did\n" + "someone else?", "Laurel Thatcher Ulrich", "Eleanor Roosevelt", "Marilyn Monroe", "Queen Victoria", 0); Question question6 = new Question(R.drawable.img_quote_6, "Here’s the truth, Will Smith did\n" + "say this, but in which movie?", "Independence Day", "Bad Boys", "Men In Black","The Pursuit of Happyness", 2); Question question7 = new Question(R.drawable.img_quote_7, "Which TV funny gal actually\n" + "quipped this 1-liner?", "Ellen Degeneres", "Amy Poehler", "Betty White", "Tina Fay", 3); Question question8 = new Question(R.drawable.img_quote_8, "This mayor won’t get my vote —\n" + "but did he actually give this\n" + "piece of advice? And if not, who\n" + "did?", "Forrest Gump,\n" + "Forrest Gump", "Dorry, Finding\n" + "Nemo", "Esther Williams", "The Mayor, Jaws", 1); Question question9 = new Question(R.drawable.img_quote_9, "Her heart will go on, but whose\n" + "heart is it?", "Whitney Houston", "Diana Ross", "Celine Dion", "Mariah Carey", 0); Question question10 = new Question(R.drawable.img_quote_10, "He’s the king of something\n" + "alright — to whom does this\n" + "self-titling line belong to?", "Tony Montana,\n" + "Scarface", "Joker, The Dark\n" + "Knight", "Lex Luthor,\n" + "Batman v Superman", "Jack, Titanic", 3); Question question11 = new Question(R.drawable.img_quote_11, "Is “Grey” synonymous for\n" + "“wise”? If so, maybe Gandalf did\n" + "preach this advice. If not, who\n" + "did?", "Yoda, Star Wars", "Gandalf The Grey,\n" + "Lord of the Rings", "Dumbledore, Harry\n" + "Potter", "Uncle Ben, Spider-Man", 0); Question question12 = new Question(R.drawable.img_quote_12, "Houston, we have a problem\n" + "with this quote — which\n" + "space-traveler does this\n" + "catch-phrase actually belong to?", "Han Solo, Star Wars", "Captain Kirk, Star\n" + "Trek", "Buzz Lightyear, Toy\n" + "Story", "Jim Lovell, Apollo 13", 2); questions.add(question0); questions.add(question1); questions.add(question2); // questions.add(question3); questions.add(question4); questions.add(question5); questions.add(question6); questions.add(question7); questions.add(question8); questions.add(question9); questions.add(question10); questions.add(question11); questions.add(question12); totalCorrect = 0; int questionNumToDisplay = 6; while(questionNumToDisplay > 0){ int questionIndexToRemove = generateRandomNumber(questions.size()); Log.i(TAG, "startNewGame with questions: " + questions.toString()); for (int i = 0; i < questions.size(); i++) { System.out.println(questions.get(i)); Log.i(TAG, "startNewGame: "+ questions.get(i).toString()); } questions.remove(questionIndexToRemove); questionNumToDisplay--; } totalQuestions = questions.size(); Question firstQuestion = chooseNewQuestion(); // TODO 3-D.ii: Uncomment the line below after implementing displayQuestionsRemaining(int) displayQuestionsRemaining(questions.size()); // TODO 3-H.ii: Uncomment after implementing displayQuestion(Question) displayQuestion(firstQuestion); } // int displaySize = 6; // while(displaySize > 0){ // int questionIndexToRemove = generateRandomNumber(questions.size()); // displaySize--; // } Question chooseNewQuestion() { int newQuestionIndex = generateRandomNumber(questions.size()); currentQuestionIndex = newQuestionIndex; return questions.get(currentQuestionIndex); } int generateRandomNumber(int max) { double randomNumber = Math.random(); double result = max * randomNumber; return (int) result; } Question getCurrentQuestion() { Question currentQuestion = questions.get(currentQuestionIndex); return currentQuestion; } String getGameOverMessage(int totalCorrect, int totalQuestions) { if (totalCorrect == totalQuestions) { return "You got all " + totalQuestions + " right! You won!"; } else { return "You got " + totalCorrect + " right out of " + totalQuestions + ". Better luck next time!"; } } }
UTF-8
Java
13,906
java
MainActivity.java
Java
[ { "context": "ay it… Who\\n\" +\n \"actually did?\", \"Albert Einstein\", \"Isaac Newton\", \"Rita Mae Brown\", \"Rosalind Fra", "end": 7601, "score": 0.999883770942688, "start": 7586, "tag": "NAME", "value": "Albert Einstein" }, { "context": " \"actually did?\", \"Albert Einstein\", \"Isaac Newton\", \"Rita Mae Brown\", \"Rosalind Franklin\", 2);\n ", "end": 7617, "score": 0.9998742341995239, "start": 7605, "tag": "NAME", "value": "Isaac Newton" }, { "context": "tually did?\", \"Albert Einstein\", \"Isaac Newton\", \"Rita Mae Brown\", \"Rosalind Franklin\", 2);\n Question quest", "end": 7635, "score": 0.9998773336410522, "start": 7621, "tag": "NAME", "value": "Rita Mae Brown" }, { "context": "ert Einstein\", \"Isaac Newton\", \"Rita Mae Brown\", \"Rosalind Franklin\", 2);\n Question question1 = new Question(R", "end": 7656, "score": 0.9998830556869507, "start": 7639, "tag": "NAME", "value": "Rosalind Franklin" }, { "context": "his pithy bit\\n\" +\n \"of wisdom?\", \"Edward Stieglitz\", \"Maya Angelou\", \"Abraham Lincoln\", \"Ralph Waldo", "end": 7886, "score": 0.9998651146888733, "start": 7870, "tag": "NAME", "value": "Edward Stieglitz" }, { "context": " \"of wisdom?\", \"Edward Stieglitz\", \"Maya Angelou\", \"Abraham Lincoln\", \"Ralph Waldo Emerson\", 0);\n ", "end": 7902, "score": 0.9998748898506165, "start": 7890, "tag": "NAME", "value": "Maya Angelou" }, { "context": "of wisdom?\", \"Edward Stieglitz\", \"Maya Angelou\", \"Abraham Lincoln\", \"Ralph Waldo Emerson\", 0);\n Question que", "end": 7921, "score": 0.9998694062232971, "start": 7906, "tag": "NAME", "value": "Abraham Lincoln" }, { "context": "d Stieglitz\", \"Maya Angelou\", \"Abraham Lincoln\", \"Ralph Waldo Emerson\", 0);\n Question question2 = new Question(R", "end": 7944, "score": 0.9998621344566345, "start": 7925, "tag": "NAME", "value": "Ralph Waldo Emerson" }, { "context": "to\\n\" +\n \"follow — who actually\", \"Martin Luther King Jr.\", \"Mother Teresa\", \"Fred Rogers\", \"Oprah Winfrey", "end": 8149, "score": 0.9428578615188599, "start": 8128, "tag": "NAME", "value": "Martin Luther King Jr" }, { "context": "ollow — who actually\", \"Martin Luther King Jr.\", \"Mother Teresa\", \"Fred Rogers\", \"Oprah Winfrey\", 1);\n\n //", "end": 8167, "score": 0.999869167804718, "start": 8154, "tag": "NAME", "value": "Mother Teresa" }, { "context": "lly\", \"Martin Luther King Jr.\", \"Mother Teresa\", \"Fred Rogers\", \"Oprah Winfrey\", 1);\n\n //question3 was r", "end": 8182, "score": 0.9998703002929688, "start": 8171, "tag": "NAME", "value": "Fred Rogers" }, { "context": "uther King Jr.\", \"Mother Teresa\", \"Fred Rogers\", \"Oprah Winfrey\", 1);\n\n //question3 was removed to avoid c", "end": 8199, "score": 0.9998701214790344, "start": 8186, "tag": "NAME", "value": "Oprah Winfrey" }, { "context": "void controvasies found here: https://twitter.com/GoodPassport/status/1274310169418137600?s=20\n /* Questio", "end": 8305, "score": 0.9699703454971313, "start": 8293, "tag": "USERNAME", "value": "GoodPassport" }, { "context": "rce of this\\n\" +\n \"inspiration?\", \"Nelson Mandela\", \"Harriet Tubman\", \"Mahatma Gandhi\", \"Nicholas K", "end": 8604, "score": 0.9998801350593567, "start": 8590, "tag": "NAME", "value": "Nelson Mandela" }, { "context": " \"inspiration?\", \"Nelson Mandela\", \"Harriet Tubman\", \"Mahatma Gandhi\", \"Nicholas Klein\", 3);*/\n ", "end": 8622, "score": 0.9998817443847656, "start": 8608, "tag": "NAME", "value": "Harriet Tubman" }, { "context": "spiration?\", \"Nelson Mandela\", \"Harriet Tubman\", \"Mahatma Gandhi\", \"Nicholas Klein\", 3);*/\n Question questi", "end": 8640, "score": 0.9998850226402283, "start": 8626, "tag": "NAME", "value": "Mahatma Gandhi" }, { "context": "on Mandela\", \"Harriet Tubman\", \"Mahatma Gandhi\", \"Nicholas Klein\", 3);*/\n Question question4 = new Question", "end": 8658, "score": 0.9998819828033447, "start": 8644, "tag": "NAME", "value": "Nicholas Klein" }, { "context": "lly\\n\" +\n \"reminded us of this?\", \"Malala Yousafzai\", \"Martin Luther King Jr.\", \"Liu Xiaobo\", \"Dalai ", "end": 8860, "score": 0.9998806118965149, "start": 8844, "tag": "NAME", "value": "Malala Yousafzai" }, { "context": " \"reminded us of this?\", \"Malala Yousafzai\", \"Martin Luther King Jr.\", \"Liu Xiaobo\", \"Dalai Lama\", 1);\n Quest", "end": 8884, "score": 0.9565767645835876, "start": 8864, "tag": "NAME", "value": "Martin Luther King J" }, { "context": "\", \"Malala Yousafzai\", \"Martin Luther King Jr.\", \"Liu Xiaobo\", \"Dalai Lama\", 1);\n Question question5 = ", "end": 8900, "score": 0.9998810887336731, "start": 8890, "tag": "NAME", "value": "Liu Xiaobo" }, { "context": "safzai\", \"Martin Luther King Jr.\", \"Liu Xiaobo\", \"Dalai Lama\", 1);\n Question question5 = new Question(R", "end": 8914, "score": 0.9998648166656494, "start": 8904, "tag": "NAME", "value": "Dalai Lama" }, { "context": "nfortunately, true —\\n\" +\n \"but did Marilyn Monroe\\n\" +\n \"convey it or did\\n\" +\n ", "end": 9054, "score": 0.9995596408843994, "start": 9040, "tag": "NAME", "value": "Marilyn Monroe" }, { "context": " it or did\\n\" +\n \"someone else?\", \"Laurel Thatcher Ulrich\", \"Eleanor Roosevelt\", \"Marilyn Monroe\", \"Queen V", "end": 9155, "score": 0.9998838901519775, "start": 9133, "tag": "NAME", "value": "Laurel Thatcher Ulrich" }, { "context": " \"someone else?\", \"Laurel Thatcher Ulrich\", \"Eleanor Roosevelt\", \"Marilyn Monroe\", \"Queen Victoria\", 0);\n ", "end": 9176, "score": 0.9998874068260193, "start": 9159, "tag": "NAME", "value": "Eleanor Roosevelt" }, { "context": ", \"Laurel Thatcher Ulrich\", \"Eleanor Roosevelt\", \"Marilyn Monroe\", \"Queen Victoria\", 0);\n Question question", "end": 9194, "score": 0.9998846650123596, "start": 9180, "tag": "NAME", "value": "Marilyn Monroe" }, { "context": " Ulrich\", \"Eleanor Roosevelt\", \"Marilyn Monroe\", \"Queen Victoria\", 0);\n Question question6 = new Question(R", "end": 9212, "score": 0.7514721155166626, "start": 9198, "tag": "NAME", "value": "Queen Victoria" }, { "context": "uestion(R.drawable.img_quote_6, \"Here’s the truth, Will Smith did\\n\" +\n \"say this, but in which ", "end": 9314, "score": 0.99968022108078, "start": 9304, "tag": "NAME", "value": "Will Smith" }, { "context": "ly\\n\" +\n \"quipped this 1-liner?\", \"Ellen Degeneres\", \"Amy Poehler\", \"Betty White\",\n \"", "end": 9625, "score": 0.9988783597946167, "start": 9610, "tag": "NAME", "value": "Ellen Degeneres" }, { "context": " \"quipped this 1-liner?\", \"Ellen Degeneres\", \"Amy Poehler\", \"Betty White\",\n \"Tina Fay\", 3);\n", "end": 9640, "score": 0.9998789429664612, "start": 9629, "tag": "NAME", "value": "Amy Poehler" }, { "context": "his 1-liner?\", \"Ellen Degeneres\", \"Amy Poehler\", \"Betty White\",\n \"Tina Fay\", 3);\n Questio", "end": 9655, "score": 0.9998787045478821, "start": 9644, "tag": "NAME", "value": "Betty White" }, { "context": "\", \"Amy Poehler\", \"Betty White\",\n \"Tina Fay\", 3);\n Question question8 = new Question(R", "end": 9683, "score": 0.9998780488967896, "start": 9675, "tag": "NAME", "value": "Tina Fay" }, { "context": "ce? And if not, who\\n\" +\n \"did?\", \"Forrest Gump,\\n\" +\n \"Forrest Gump\", \"Dorry, Fin", "end": 9937, "score": 0.9982848167419434, "start": 9925, "tag": "NAME", "value": "Forrest Gump" }, { "context": " \"did?\", \"Forrest Gump,\\n\" +\n \"Forrest Gump\", \"Dorry, Finding\\n\" +\n \"Nemo\", \"E", "end": 9973, "score": 0.9988125562667847, "start": 9961, "tag": "NAME", "value": "Forrest Gump" }, { "context": "rrest Gump,\\n\" +\n \"Forrest Gump\", \"Dorry, Finding\\n\" +\n \"Nemo\", \"Esther Williams\", \"", "end": 9991, "score": 0.9914807081222534, "start": 9977, "tag": "NAME", "value": "Dorry, Finding" }, { "context": "rest Gump\", \"Dorry, Finding\\n\" +\n \"Nemo\", \"Esther Williams\", \"The Mayor, Jaws\", 1);\n ", "end": 10018, "score": 0.9989534020423889, "start": 10014, "tag": "NAME", "value": "Nemo" }, { "context": "p\", \"Dorry, Finding\\n\" +\n \"Nemo\", \"Esther Williams\", \"The Mayor, Jaws\", 1);\n Question questio", "end": 10037, "score": 0.9998714327812195, "start": 10022, "tag": "NAME", "value": "Esther Williams" }, { "context": ", but whose\\n\" +\n \"heart is it?\", \"Whitney Houston\", \"Diana Ross\", \"Celine Dion\",\n \"M", "end": 10215, "score": 0.9998305439949036, "start": 10200, "tag": "NAME", "value": "Whitney Houston" }, { "context": " \"heart is it?\", \"Whitney Houston\", \"Diana Ross\", \"Celine Dion\",\n \"Mariah Carey\", ", "end": 10229, "score": 0.9998788833618164, "start": 10219, "tag": "NAME", "value": "Diana Ross" }, { "context": "\"heart is it?\", \"Whitney Houston\", \"Diana Ross\", \"Celine Dion\",\n \"Mariah Carey\", 0);\n Que", "end": 10244, "score": 0.9998915791511536, "start": 10233, "tag": "NAME", "value": "Celine Dion" }, { "context": "n\", \"Diana Ross\", \"Celine Dion\",\n \"Mariah Carey\", 0);\n Question question10 = new Question(", "end": 10276, "score": 0.9998900890350342, "start": 10264, "tag": "NAME", "value": "Mariah Carey" }, { "context": "\n \"self-titling line belong to?\", \"Tony Montana,\\n\" +\n \"Scarface\", \"Joker, The Dar", "end": 10495, "score": 0.9992746114730835, "start": 10483, "tag": "NAME", "value": "Tony Montana" }, { "context": "belong to?\", \"Tony Montana,\\n\" +\n \"Scarface\", \"Joker, The Dark\\n\" +\n \"Knight\",", "end": 10527, "score": 0.9542865753173828, "start": 10519, "tag": "NAME", "value": "Scarface" }, { "context": " \"Tony Montana,\\n\" +\n \"Scarface\", \"Joker, The Dark\\n\" +\n \"Knight\", \"Lex Lut", "end": 10536, "score": 0.9354386329650879, "start": 10531, "tag": "NAME", "value": "Joker" }, { "context": "carface\", \"Joker, The Dark\\n\" +\n \"Knight\", \"Lex Luthor,\\n\" +\n \"Batman v Sup", "end": 10575, "score": 0.6355145573616028, "start": 10570, "tag": "NAME", "value": "night" }, { "context": " \"Joker, The Dark\\n\" +\n \"Knight\", \"Lex Luthor,\\n\" +\n \"Batman v Superman\", \"Jack,", "end": 10589, "score": 0.9998111724853516, "start": 10579, "tag": "NAME", "value": "Lex Luthor" }, { "context": " \"Knight\", \"Lex Luthor,\\n\" +\n \"Batman v Superman\", \"Jack, Titanic\", 3);\n Question question1", "end": 10630, "score": 0.9108383059501648, "start": 10613, "tag": "NAME", "value": "Batman v Superman" }, { "context": "uthor,\\n\" +\n \"Batman v Superman\", \"Jack, Titanic\", 3);\n Question question11 = new Question(", "end": 10647, "score": 0.9821978211402893, "start": 10634, "tag": "NAME", "value": "Jack, Titanic" }, { "context": "ous for\\n\" +\n \"“wise”? If so, maybe Gandalf did\\n\" +\n \"preach this advic", "end": 10792, "score": 0.90101557970047, "start": 10791, "tag": "NAME", "value": "G" }, { "context": "or\\n\" +\n \"“wise”? If so, maybe Gandalf did\\n\" +\n \"preach this advice. If ", "end": 10798, "score": 0.8465022444725037, "start": 10795, "tag": "NAME", "value": "alf" }, { "context": "\\n\" +\n \"did?\", \"Yoda, Star Wars\", \"Gandalf The Grey,\\n\" +\n \"Lord of the Rings", "end": 10913, "score": 0.8006331324577332, "start": 10906, "tag": "NAME", "value": "Gandalf" }, { "context": " Grey,\\n\" +\n \"Lord of the Rings\", \"Dumbledore, Harry\\n\" +\n \"Potter\", \"Uncle Ben,", "end": 10977, "score": 0.9250632524490356, "start": 10967, "tag": "NAME", "value": "Dumbledore" }, { "context": "\n \"Lord of the Rings\", \"Dumbledore, Harry\\n\" +\n \"Potter\", \"Uncle Ben, Spider", "end": 10984, "score": 0.7253295183181763, "start": 10979, "tag": "NAME", "value": "Harry" }, { "context": " Rings\", \"Dumbledore, Harry\\n\" +\n \"Potter\", \"Uncle Ben, Spider-Man\", 0);\n Question q", "end": 11013, "score": 0.9886938333511353, "start": 11007, "tag": "NAME", "value": "Potter" }, { "context": "Dumbledore, Harry\\n\" +\n \"Potter\", \"Uncle Ben, Spider-Man\", 0);\n Question question12 = n", "end": 11026, "score": 0.7142376899719238, "start": 11017, "tag": "NAME", "value": "Uncle Ben" }, { "context": "actually belong to?\", \"Han Solo, Star Wars\", \"Captain Kirk, Star\\n\" +\n \"Trek\", \"Buzz Lightyea", "end": 11327, "score": 0.9737653136253357, "start": 11319, "tag": "NAME", "value": "ain Kirk" }, { "context": " Wars\", \"Captain Kirk, Star\\n\" +\n \"Trek\", \"Buzz Lightyear, Toy\\n\" +\n \"Stor", "end": 11360, "score": 0.6916435956954956, "start": 11356, "tag": "NAME", "value": "Trek" }, { "context": "uzz Lightyear, Toy\\n\" +\n \"Story\", \"Jim Lovell, Apollo 13\", 2);\n\n\n\n questions.add(questio", "end": 11425, "score": 0.9990681409835815, "start": 11415, "tag": "NAME", "value": "Jim Lovell" } ]
null
[]
package com.example.unquote; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.text.MessageFormat; import java.util.ArrayList; public class MainActivity<displaySize> extends AppCompatActivity { private static final String TAG = "SIZE_OF_ARRAY"; int currentQuestionIndex; int totalCorrect; int totalQuestions; ArrayList<Question> questions; // TODO 3-A: Declare View member variables ImageView questionImageView; TextView questionTextView; TextView questionsRemainingTextView; Button answer0Button; Button answer1Button; Button answer2Button; Button answer3Button; Button submitButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO 2-G: Show app icon in ActionBar getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setLogo(R.drawable.ic_unquote_icon); getSupportActionBar().setDisplayUseLogoEnabled(true); getSupportActionBar().setElevation(0); setContentView(R.layout.activity_main); // TODO 3-B: assign View member variables questionImageView = findViewById(R.id.iv_main_question_image); questionsRemainingTextView = findViewById(R.id.tv_main_questions_remaining_count); questionTextView = findViewById(R.id.tv_main_question_title); answer0Button = findViewById(R.id.btn_main_answer_0); answer1Button = findViewById(R.id.btn_main_answer_1); answer2Button = findViewById(R.id.btn_main_answer_2); answer3Button = findViewById(R.id.btn_main_answer_3); submitButton = findViewById(R.id.btn_main_submit_answer); // TODO 4-E: set onClickListener for each answer Button answer0Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(0); } }); answer1Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(1); } }); answer2Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(2); } }); answer3Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSelected(3); } }); // TODO 5-A: set onClickListener for the submit answer Button submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAnswerSubmission(); } }); startNewGame(); } // TODO 3-F: displayQuestion(Question question) {...} void displayQuestion(Question question){ questionTextView.setText(question.questionText); questionImageView.setImageResource(question.imageId); answer0Button.setText(question.answer0); answer1Button.setText(question.answer1); answer2Button.setText(question.answer2); answer3Button.setText(question.answer3); } // TODO 3-C: displayQuestionsRemaining(int questionRemaining) {...} void displayQuestionsRemaining(int remainingQuestion){ questionsRemainingTextView.setText(String.format("%d", remainingQuestion)); } // TODO 4-A: onAnswerSelected(int answerSelected) {...} void onAnswerSelected(int playerChoice){ Question currentQuestion = getCurrentQuestion(); currentQuestion.playerAnswer = playerChoice; answer0Button.setText(currentQuestion.answer0); answer1Button.setText(currentQuestion.answer1); answer2Button.setText(currentQuestion.answer2); answer3Button.setText(currentQuestion.answer3); switch (playerChoice){ case 0: answer0Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer0)); // answer3Button.setBackgroundResource(R.color.btn_select); break; case 1: answer1Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer1)); // answer3Button.setBackgroundResource(R.color.btn_select); break; case 2: answer2Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer2)); // answer3Button.setBackgroundResource(R.color.btn_select); break; case 3: answer3Button.setText(MessageFormat.format("✔{0}", currentQuestion.answer3)); // answer3Button.setBackgroundResource(R.color.btn_select); break; default: throw new IllegalStateException("Unexpected value: " + playerChoice); } } void onAnswerSubmission() { Question currentQuestion = getCurrentQuestion(); if (currentQuestion.isCorrect()) { totalCorrect = totalCorrect + 1; }else if (currentQuestion.playerAnswer == -1){ return; } questions.remove(currentQuestion); // TODO 3-D.i: Uncomment the line below after implementing displayQuestionsRemaining(int) displayQuestionsRemaining(questions.size()); if (questions.size() == 0) { String gameOverMessage = getGameOverMessage(totalCorrect, totalQuestions); // TODO 5-D: Show a popup instead AlertDialog.Builder gameOverDialogBuilder = new AlertDialog.Builder(MainActivity.this); gameOverDialogBuilder.setCancelable(false); gameOverDialogBuilder.setTitle("Game Over!"); gameOverDialogBuilder.setMessage(gameOverMessage); gameOverDialogBuilder.setPositiveButton("Play Again!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startNewGame(); } }); gameOverDialogBuilder.setNegativeButton("Quit Game", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { endGame(); } }); gameOverDialogBuilder.create().show(); // System.out.println(gameOverMessage); } else { chooseNewQuestion(); // TODO 3-H.i: uncomment after implementing displayQuestion(Question) displayQuestion(getCurrentQuestion()); } } // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) private void endGame() { finish(); System.exit(0); } void startNewGame() { questions = new ArrayList<>(); // TODO 2-H: Provide actual drawables for each of these questions! Question question0 = new Question(R.drawable.img_quote_0, "Pretty good advice,\n" + "and perhaps a scientist\n" + "did say it… Who\n" + "actually did?", "<NAME>", "<NAME>", "<NAME>", "<NAME>", 2); Question question1 = new Question(R.drawable.img_quote_1, "Was honest Abe\n" + "honestly quoted? Who\n" + "authored this pithy bit\n" + "of wisdom?", "<NAME>", "<NAME>", "<NAME>", "<NAME>", 0); Question question2 = new Question(R.drawable.img_quote_2, "Easy advice to read,\n" + "difficult advice to\n" + "follow — who actually", "<NAME>.", "<NAME>", "<NAME>", "<NAME>", 1); //question3 was removed to avoid controvasies found here: https://twitter.com/GoodPassport/status/1274310169418137600?s=20 /* Question question3 = new Question(R.drawable.img_quote_3, "Insanely inspiring,\n" + "insanely incorrect\n" + "(maybe). Who is the\n" + "true source of this\n" + "inspiration?", "<NAME>", "<NAME>", "<NAME>", "<NAME>", 3);*/ Question question4 = new Question(R.drawable.img_quote_4, "A peace worth striving\n" + "for — who actually\n" + "reminded us of this?", "<NAME>", "<NAME>r.", "<NAME>", "<NAME>", 1); Question question5 = new Question(R.drawable.img_quote_5, "Unfortunately, true —\n" + "but did <NAME>\n" + "convey it or did\n" + "someone else?", "<NAME>", "<NAME>", "<NAME>", "<NAME>", 0); Question question6 = new Question(R.drawable.img_quote_6, "Here’s the truth, <NAME> did\n" + "say this, but in which movie?", "Independence Day", "Bad Boys", "Men In Black","The Pursuit of Happyness", 2); Question question7 = new Question(R.drawable.img_quote_7, "Which TV funny gal actually\n" + "quipped this 1-liner?", "<NAME>", "<NAME>", "<NAME>", "<NAME>", 3); Question question8 = new Question(R.drawable.img_quote_8, "This mayor won’t get my vote —\n" + "but did he actually give this\n" + "piece of advice? And if not, who\n" + "did?", "<NAME>,\n" + "<NAME>", "<NAME>\n" + "Nemo", "<NAME>", "The Mayor, Jaws", 1); Question question9 = new Question(R.drawable.img_quote_9, "Her heart will go on, but whose\n" + "heart is it?", "<NAME>", "<NAME>", "<NAME>", "<NAME>", 0); Question question10 = new Question(R.drawable.img_quote_10, "He’s the king of something\n" + "alright — to whom does this\n" + "self-titling line belong to?", "<NAME>,\n" + "Scarface", "Joker, The Dark\n" + "Knight", "<NAME>,\n" + "<NAME>", "<NAME>", 3); Question question11 = new Question(R.drawable.img_quote_11, "Is “Grey” synonymous for\n" + "“wise”? If so, maybe Gandalf did\n" + "preach this advice. If not, who\n" + "did?", "Yoda, Star Wars", "Gandalf The Grey,\n" + "Lord of the Rings", "Dumbledore, Harry\n" + "Potter", "<NAME>, Spider-Man", 0); Question question12 = new Question(R.drawable.img_quote_12, "Houston, we have a problem\n" + "with this quote — which\n" + "space-traveler does this\n" + "catch-phrase actually belong to?", "Han Solo, Star Wars", "Capt<NAME>, Star\n" + "Trek", "Buzz Lightyear, Toy\n" + "Story", "<NAME>, Apollo 13", 2); questions.add(question0); questions.add(question1); questions.add(question2); // questions.add(question3); questions.add(question4); questions.add(question5); questions.add(question6); questions.add(question7); questions.add(question8); questions.add(question9); questions.add(question10); questions.add(question11); questions.add(question12); totalCorrect = 0; int questionNumToDisplay = 6; while(questionNumToDisplay > 0){ int questionIndexToRemove = generateRandomNumber(questions.size()); Log.i(TAG, "startNewGame with questions: " + questions.toString()); for (int i = 0; i < questions.size(); i++) { System.out.println(questions.get(i)); Log.i(TAG, "startNewGame: "+ questions.get(i).toString()); } questions.remove(questionIndexToRemove); questionNumToDisplay--; } totalQuestions = questions.size(); Question firstQuestion = chooseNewQuestion(); // TODO 3-D.ii: Uncomment the line below after implementing displayQuestionsRemaining(int) displayQuestionsRemaining(questions.size()); // TODO 3-H.ii: Uncomment after implementing displayQuestion(Question) displayQuestion(firstQuestion); } // int displaySize = 6; // while(displaySize > 0){ // int questionIndexToRemove = generateRandomNumber(questions.size()); // displaySize--; // } Question chooseNewQuestion() { int newQuestionIndex = generateRandomNumber(questions.size()); currentQuestionIndex = newQuestionIndex; return questions.get(currentQuestionIndex); } int generateRandomNumber(int max) { double randomNumber = Math.random(); double result = max * randomNumber; return (int) result; } Question getCurrentQuestion() { Question currentQuestion = questions.get(currentQuestionIndex); return currentQuestion; } String getGameOverMessage(int totalCorrect, int totalQuestions) { if (totalCorrect == totalQuestions) { return "You got all " + totalQuestions + " right! You won!"; } else { return "You got " + totalCorrect + " right out of " + totalQuestions + ". Better luck next time!"; } } }
13,570
0.612978
0.600937
327
41.412846
29.816425
130
false
false
0
0
0
0
0
0
0.825688
false
false
4
0fba575418a8ac4e580be4a8e1b8b778fbba6203
32,865,089,758,325
c55d5ab84c342879e30bc3f71d1121efb4449fb7
/chapter17/src/main/java/top/parak/PhantomReferenceTest.java
12c600365a02ab764c640ac10ac45f9e277df1f6
[]
no_license
Khighness/jvm-test
https://github.com/Khighness/jvm-test
c3252ab2062705da5f8c29d3e497932b684ab0e8
05e16d27fab4f37d6da7df22c3560ac553708dd0
refs/heads/master
2023-04-02T10:26:09.509000
2021-04-04T15:34:22
2021-04-04T15:34:22
341,477,463
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package top.parak; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.concurrent.TimeUnit; /** * <p> Project: jvm-test </P> * <p> Package: top.parak </p> * <p> FileName: PhantomReferenceTest <p> * <p> Description: <p> * <p> Created By IntelliJ IDEA </p> * * @author KHighness * @since 2021/3/22 */ public class PhantomReferenceTest { public static PhantomReferenceTest obj; /** * 引用队列 */ public static ReferenceQueue<PhantomReferenceTest> phantomQueue = null; public static class CheckRefQueue extends Thread { @Override public void run() { while (true) { if (phantomQueue != null) { PhantomReference<PhantomReferenceTest> objt = null; try { objt = (PhantomReference<PhantomReferenceTest>) phantomQueue.remove(); } catch (InterruptedException e) { e.printStackTrace(); } if (objt != null) { System.out.println("追踪垃圾回收过程:PhantRefernceTest实例被GC了"); } } } } } @Override protected void finalize() throws Throwable { super.finalize(); System.out.println("调用当前类的finalize()方法"); obj = this; } public static void main(String[] args) throws InterruptedException { Thread t = new CheckRefQueue(); t.setDaemon(true); // 守护线程 t.start(); phantomQueue = new ReferenceQueue<PhantomReferenceTest>(); obj = new PhantomReferenceTest(); // 构造了PhantomReference对象的虚引用,并指定了引用队列 PhantomReference<PhantomReferenceTest> phantomRef = new PhantomReference<>(obj, phantomQueue); try { // 不可获取虚引用中的对象 System.out.println("phantomRef.get() = " + phantomRef.get()); // 第一次GC,由于对象可复活,并指定了引用队列 System.out.println("=>>> 第一次GC操作"); obj = null; // 解除强引用 System.gc(); Thread.sleep(1000); System.out.println(obj == null ? "obj == null" : "obj != null"); System.out.println("=>>> 第二次GC"); obj = null; // 解除强引用 System.gc(); Thread.sleep(1000); System.out.println(obj == null ? "obj == null" : "obj != null"); } catch (Exception e) { e.printStackTrace(); } finally { } } }
UTF-8
Java
2,839
java
PhantomReferenceTest.java
Java
[ { "context": " <p> Created By IntelliJ IDEA </p>\r\n *\r\n * @author KHighness\r\n * @since 2021/3/22\r\n */\r\n\r\npublic class Phantom", "end": 409, "score": 0.9994738698005676, "start": 400, "tag": "USERNAME", "value": "KHighness" } ]
null
[]
package top.parak; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.concurrent.TimeUnit; /** * <p> Project: jvm-test </P> * <p> Package: top.parak </p> * <p> FileName: PhantomReferenceTest <p> * <p> Description: <p> * <p> Created By IntelliJ IDEA </p> * * @author KHighness * @since 2021/3/22 */ public class PhantomReferenceTest { public static PhantomReferenceTest obj; /** * 引用队列 */ public static ReferenceQueue<PhantomReferenceTest> phantomQueue = null; public static class CheckRefQueue extends Thread { @Override public void run() { while (true) { if (phantomQueue != null) { PhantomReference<PhantomReferenceTest> objt = null; try { objt = (PhantomReference<PhantomReferenceTest>) phantomQueue.remove(); } catch (InterruptedException e) { e.printStackTrace(); } if (objt != null) { System.out.println("追踪垃圾回收过程:PhantRefernceTest实例被GC了"); } } } } } @Override protected void finalize() throws Throwable { super.finalize(); System.out.println("调用当前类的finalize()方法"); obj = this; } public static void main(String[] args) throws InterruptedException { Thread t = new CheckRefQueue(); t.setDaemon(true); // 守护线程 t.start(); phantomQueue = new ReferenceQueue<PhantomReferenceTest>(); obj = new PhantomReferenceTest(); // 构造了PhantomReference对象的虚引用,并指定了引用队列 PhantomReference<PhantomReferenceTest> phantomRef = new PhantomReference<>(obj, phantomQueue); try { // 不可获取虚引用中的对象 System.out.println("phantomRef.get() = " + phantomRef.get()); // 第一次GC,由于对象可复活,并指定了引用队列 System.out.println("=>>> 第一次GC操作"); obj = null; // 解除强引用 System.gc(); Thread.sleep(1000); System.out.println(obj == null ? "obj == null" : "obj != null"); System.out.println("=>>> 第二次GC"); obj = null; // 解除强引用 System.gc(); Thread.sleep(1000); System.out.println(obj == null ? "obj == null" : "obj != null"); } catch (Exception e) { e.printStackTrace(); } finally { } } }
2,839
0.532301
0.526634
84
29.511906
23.638393
102
false
false
0
0
0
0
0
0
0.404762
false
false
4
6ea23f965413bd1ee1e83b091b15f64d4ac2d056
12,300,786,377,184
2564ff43b74a441c99c977a2362c919380158d5a
/9.0 Activ8 WORKSPACE/activ8ejb/src/com/o2hlink/activ8/client/action/SkypeContactListNewAction.java
a42e7e0358320149d57e9d723f89041056601e7b
[]
no_license
ActivaPlatform/activa
https://github.com/ActivaPlatform/activa
d2c9b7bbb943aa96ad3088d5d9a010b1de44418e
a89c584925f4bcf87d3299b400bec09189912cf6
refs/heads/master
2021-01-13T13:04:39.660000
2016-03-22T02:57:02
2016-03-22T02:57:02
54,227,645
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.o2hlink.activ8.client.action; import com.o2hlink.activ8.client.entity.User; import com.o2hlink.activ8.client.response.VoidResponse; /** * As there is no web service to retrieve the skype contacts (at least not known by July/2010), we upload the file with contacts and later on send a request to update. * @author Miguel Angel Hernandez **/ public class SkypeContactListNewAction implements Action<VoidResponse> { //FIELDS /** * */ private static final long serialVersionUID = -5215564819098861200L; /** * **/ private User user; /** * **/ private long file; //CONSTRUCTOR /** * **/ public SkypeContactListNewAction(){ } /** * **/ public SkypeContactListNewAction(User user, long file){ setUser(user); setFile(file); } //METHODS /** * @param user the user to set */ public void setUser(User user) { this.user = user; } /** * @return the user */ public User getUser() { return user; } /** * @param file the file to set */ public void setFile(long file) { this.file = file; } /** * @return the file */ public long getFile() { return file; } }
UTF-8
Java
1,136
java
SkypeContactListNewAction.java
Java
[ { "context": " and later on send a request to update.\n * @author Miguel Angel Hernandez\n **/\npublic class SkypeContactListNewAction imple", "end": 351, "score": 0.9998727440834045, "start": 329, "tag": "NAME", "value": "Miguel Angel Hernandez" } ]
null
[]
package com.o2hlink.activ8.client.action; import com.o2hlink.activ8.client.entity.User; import com.o2hlink.activ8.client.response.VoidResponse; /** * As there is no web service to retrieve the skype contacts (at least not known by July/2010), we upload the file with contacts and later on send a request to update. * @author <NAME> **/ public class SkypeContactListNewAction implements Action<VoidResponse> { //FIELDS /** * */ private static final long serialVersionUID = -5215564819098861200L; /** * **/ private User user; /** * **/ private long file; //CONSTRUCTOR /** * **/ public SkypeContactListNewAction(){ } /** * **/ public SkypeContactListNewAction(User user, long file){ setUser(user); setFile(file); } //METHODS /** * @param user the user to set */ public void setUser(User user) { this.user = user; } /** * @return the user */ public User getUser() { return user; } /** * @param file the file to set */ public void setFile(long file) { this.file = file; } /** * @return the file */ public long getFile() { return file; } }
1,120
0.658451
0.632923
63
17.031746
25.462683
167
false
false
0
0
0
0
0
0
1.111111
false
false
4
a804872789b9202833a8424a68dc71d1700904ca
24,747,601,579,596
337763e14103919415e5f5f9775593040e50194d
/application-cleaner/src/main/java/com/honeybadgers/cleaner/services/ScheduledServices.java
afbbf4875a3639b51688e79982759704abd4dbfc
[ "MIT" ]
permissive
amosproj/fau-ss2020-proj6-realtime-scheduler
https://github.com/amosproj/fau-ss2020-proj6-realtime-scheduler
f81ea4ee1da9592c7938b5f87619cfecb9a53e9b
e829dbb7ed8115563eac4b57f23d7b4fd020f123
refs/heads/master
2023-04-03T06:17:41.962000
2020-07-22T12:29:31
2020-07-22T12:29:31
359,451,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.honeybadgers.cleaner.services; import com.honeybadgers.communication.ICommunication; import com.honeybadgers.models.model.jpa.Paused; import com.honeybadgers.models.model.jpa.Task; import com.honeybadgers.postgre.repository.PausedRepository; import com.honeybadgers.postgre.repository.TaskRepository; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.TransactionException; import org.hibernate.exception.LockAcquisitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.CannotAcquireLockException; import org.springframework.orm.jpa.JpaSystemException; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class ScheduledServices { static final Logger logger = LogManager.getLogger(ScheduledServices.class); @Autowired PausedRepository pausedRepository; @Autowired TaskRepository taskRepository; @Autowired ICommunication sender; @Value("${scheduler.trigger}") String scheduler_trigger; @Value("${cleaner.finished-cleanup.enabled}") boolean taskCleanupEnabled; @Value("${cleaner.finished-cleanup.expiration-days}") int taskCleanupDays; /** * This Component check for paused Tasks and Groups and makes sure they are unlocked at specified times. */ @Scheduled(fixedRateString = "${cleaner.paused.fixed-rate}", initialDelayString = "${cleaner.paused.initial-delay}") public void cleanPausedLocks() { logger.info("Cleaner starting paused cleanup"); List<Paused> deleted = new ArrayList<>(); try { deleted = pausedRepository.deleteAllExpired(); } catch (JpaSystemException | TransactionException | CannotAcquireLockException | LockAcquisitionException exception) { logger.warn("Cleaner encountered transaction exception!"); } logger.info("Cleaner finished paused cleanup - deleted " + deleted.size() + " elements"); if (deleted.size() > 0) { sender.sendTaskToTasksQueue(scheduler_trigger); logger.info("Notified scheduler for rescheduling!"); } } /** * If enabled (in properties): * Cleans all tasks with status 'Finished' which have this status for at least N days (configured via application.properties) */ @Scheduled(fixedRateString = "${cleaner.finished-cleanup.fixed-rate}", initialDelayString = "${cleaner.finished-cleanup.initial-delay}") public void cleanFinishedTasks() { if (taskCleanupEnabled) { logger.info("Cleaner starting finished tasks cleanup"); // convert number of days to milliseconds long daysInMillis = taskCleanupDays * 24 * 60 * 60 * 1000L; List<Task> deleted = taskRepository.deleteAllTasksFinishedSinceNMilliseconds(daysInMillis); logger.info("Cleaner finished task cleanup - deleted " + deleted.size() + " tasks, which were finished for at least " + taskCleanupDays + " days."); } else { logger.info("Automated task deletion is disabled - please enable in application.properties"); } } }
UTF-8
Java
3,342
java
ScheduledServices.java
Java
[]
null
[]
package com.honeybadgers.cleaner.services; import com.honeybadgers.communication.ICommunication; import com.honeybadgers.models.model.jpa.Paused; import com.honeybadgers.models.model.jpa.Task; import com.honeybadgers.postgre.repository.PausedRepository; import com.honeybadgers.postgre.repository.TaskRepository; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.TransactionException; import org.hibernate.exception.LockAcquisitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.CannotAcquireLockException; import org.springframework.orm.jpa.JpaSystemException; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class ScheduledServices { static final Logger logger = LogManager.getLogger(ScheduledServices.class); @Autowired PausedRepository pausedRepository; @Autowired TaskRepository taskRepository; @Autowired ICommunication sender; @Value("${scheduler.trigger}") String scheduler_trigger; @Value("${cleaner.finished-cleanup.enabled}") boolean taskCleanupEnabled; @Value("${cleaner.finished-cleanup.expiration-days}") int taskCleanupDays; /** * This Component check for paused Tasks and Groups and makes sure they are unlocked at specified times. */ @Scheduled(fixedRateString = "${cleaner.paused.fixed-rate}", initialDelayString = "${cleaner.paused.initial-delay}") public void cleanPausedLocks() { logger.info("Cleaner starting paused cleanup"); List<Paused> deleted = new ArrayList<>(); try { deleted = pausedRepository.deleteAllExpired(); } catch (JpaSystemException | TransactionException | CannotAcquireLockException | LockAcquisitionException exception) { logger.warn("Cleaner encountered transaction exception!"); } logger.info("Cleaner finished paused cleanup - deleted " + deleted.size() + " elements"); if (deleted.size() > 0) { sender.sendTaskToTasksQueue(scheduler_trigger); logger.info("Notified scheduler for rescheduling!"); } } /** * If enabled (in properties): * Cleans all tasks with status 'Finished' which have this status for at least N days (configured via application.properties) */ @Scheduled(fixedRateString = "${cleaner.finished-cleanup.fixed-rate}", initialDelayString = "${cleaner.finished-cleanup.initial-delay}") public void cleanFinishedTasks() { if (taskCleanupEnabled) { logger.info("Cleaner starting finished tasks cleanup"); // convert number of days to milliseconds long daysInMillis = taskCleanupDays * 24 * 60 * 60 * 1000L; List<Task> deleted = taskRepository.deleteAllTasksFinishedSinceNMilliseconds(daysInMillis); logger.info("Cleaner finished task cleanup - deleted " + deleted.size() + " tasks, which were finished for at least " + taskCleanupDays + " days."); } else { logger.info("Automated task deletion is disabled - please enable in application.properties"); } } }
3,342
0.724416
0.720527
82
39.756096
36.78698
160
false
false
0
0
0
0
0
0
0.52439
false
false
4
44347fe5eac2a7a0c9316146d9668f4c34704329
30,580,167,202,267
0c4be958f8db579625a66dc8bb6e60c0cdf78218
/src/main/java/io/fries/reflection/metadata/ClassMetadata.java
85eef38e4a6d6e755883c97cfc3a0d2bc1c208cd
[ "WTFPL" ]
permissive
Tyumeijie/ioc-container
https://github.com/Tyumeijie/ioc-container
7586d6748c1d6025a387b4b836548495fd7c5203
0d6a4b2bd057e3c2aa2cdcda669b3976e6aa9c2c
refs/heads/master
2020-05-27T14:31:23.064000
2019-05-26T09:07:09
2019-05-26T09:07:09
188,661,265
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.fries.reflection.metadata; import java.util.Optional; import static java.util.Optional.empty; import static java.util.Optional.ofNullable; /** * Simple object storing a class' metadata. * Can be used to load the class into its {@link ClassLoader} using the {@link #load()} method. * * @version 1.0 * @since 1.0 */ public class ClassMetadata extends ResourceMetadata { static final String CLASS_FILE_EXTENSION = ".class"; private final String className; private final String packageName; /** * Create a new {@code ClassMetadata} object. * While {@link #load()} has not been called, the class is not loaded into the class loader * and thus no reference to it is held in any way. * * @param resourceName The complete name of this resource. * @param classLoader The {@code ClassLoader} object to which this resource is bound. */ public ClassMetadata(final String resourceName, final ClassLoader classLoader) { super(resourceName, classLoader); System.out.println("resourceName " + resourceName ); this.className = resourceName.substring(0, resourceName.length() - CLASS_FILE_EXTENSION.length()).replace('/', '.'); this.packageName = (className.contains(".")) ? className.substring(0, className.lastIndexOf('.')) : ""; System.out.println("className " + className + " packageName " + packageName ); } /** * Load the current class into its class loader. * * @return An {@link Optional} of the {@code Class<?>} object resulting of the class loader operation. */ public Optional<Class<?>> load() { //System.out.println("io.fries.reflection."+className); try { return ofNullable(classLoader.loadClass(className)); } catch(NoClassDefFoundError | ClassNotFoundException e) { System.out.println("load"); return empty(); } } /** * @return The fully qualified class name. */ public String getName() { return className; } /** * @return The name of the package in which the class is located. */ public String getPackage() { return packageName; } /** * @return The simple name of the class (without its package name). */ public String getSimpleName() { final int lastDollar = className.lastIndexOf('$'); return (lastDollar != -1) ? className.substring(lastDollar + 1) : packageName.isEmpty() ? className : className.substring(packageName.length() + 1); } @Override public String toString() { return className; } }
UTF-8
Java
2,437
java
ClassMetadata.java
Java
[]
null
[]
package io.fries.reflection.metadata; import java.util.Optional; import static java.util.Optional.empty; import static java.util.Optional.ofNullable; /** * Simple object storing a class' metadata. * Can be used to load the class into its {@link ClassLoader} using the {@link #load()} method. * * @version 1.0 * @since 1.0 */ public class ClassMetadata extends ResourceMetadata { static final String CLASS_FILE_EXTENSION = ".class"; private final String className; private final String packageName; /** * Create a new {@code ClassMetadata} object. * While {@link #load()} has not been called, the class is not loaded into the class loader * and thus no reference to it is held in any way. * * @param resourceName The complete name of this resource. * @param classLoader The {@code ClassLoader} object to which this resource is bound. */ public ClassMetadata(final String resourceName, final ClassLoader classLoader) { super(resourceName, classLoader); System.out.println("resourceName " + resourceName ); this.className = resourceName.substring(0, resourceName.length() - CLASS_FILE_EXTENSION.length()).replace('/', '.'); this.packageName = (className.contains(".")) ? className.substring(0, className.lastIndexOf('.')) : ""; System.out.println("className " + className + " packageName " + packageName ); } /** * Load the current class into its class loader. * * @return An {@link Optional} of the {@code Class<?>} object resulting of the class loader operation. */ public Optional<Class<?>> load() { //System.out.println("io.fries.reflection."+className); try { return ofNullable(classLoader.loadClass(className)); } catch(NoClassDefFoundError | ClassNotFoundException e) { System.out.println("load"); return empty(); } } /** * @return The fully qualified class name. */ public String getName() { return className; } /** * @return The name of the package in which the class is located. */ public String getPackage() { return packageName; } /** * @return The simple name of the class (without its package name). */ public String getSimpleName() { final int lastDollar = className.lastIndexOf('$'); return (lastDollar != -1) ? className.substring(lastDollar + 1) : packageName.isEmpty() ? className : className.substring(packageName.length() + 1); } @Override public String toString() { return className; } }
2,437
0.697989
0.694296
84
28.011906
30.531597
118
false
false
0
0
0
0
0
0
1.440476
false
false
4
11f813ec012793fec8f145180e8ad3534ab0777f
17,566,416,281,743
2c4f4b417774901cd29fa7d933ec22ce388eb6c7
/Analyses/SegmentsPlusProchesDesCentroides/GetSegmentTopicSerie.java
ccb79b8d16bd1c14618575e4920cf5c30d500d6d
[]
no_license
JFChartier/lifenessAnalysisInBiomed
https://github.com/JFChartier/lifenessAnalysisInBiomed
f4b8e7427e3d2551cb78b7e834dcd74d65c20f1d
202164d56cecc86b575d588b30aecb1c25e2eb3a
refs/heads/master
2020-04-24T13:05:19.687000
2019-02-22T01:53:59
2019-02-22T01:53:59
171,975,840
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 Analyses.SegmentsPlusProchesDesCentroides; import Corpus.CorpusUtils; import Fichier.Arff.ArffUtils; import Fichier.FileUtils; import Matrice.Vectorisateur.VecteurCreux; import Metrique.Similitude.MetriqueSim; import Metrique.Similitude.ProduitScalaire; import Tokenisation.Tokeniseur; import UtilsJFC.TrieUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Random; import java.util.Set; import java.util.concurrent.ForkJoinPool; import java.util.stream.Collectors; import weka.core.Instances; import weka.core.converters.ArffLoader; /** * * @author JF Chartier */ public class GetSegmentTopicSerie { private Map<Integer, double[]> map_idClasse_centroide; private Instances data; private Map<String, Integer> map_token_id; private final String repertoireParagSelect = CorpusUtils.getRepertoireParagrapheRevueSelectionnee().toString(); public static void main(String[] args) throws FileNotFoundException, IOException { try { // ForkJoinPool commonPool = ForkJoinPool.commonPool(); // System.out.println(commonPool.getParallelism()); File fileArffVecteurMots = new File("C:\\Users\\JF Chartier\\Google Drive\\Ordinateur\\Projet sur BioMed\\V6\\vecteursMotsAvecClasseEtNom.arff"); File fileResultat = new File ("C:\\Users\\JF Chartier\\Google Drive\\Ordinateur\\Projet sur BioMed\\V6\\Resultats.csv"); File fileParagFiltre = new File("C:\\Users\\JF Chartier\\Documents\\Collections standard\\Corpus BioMed\\paragrapheFiltreRevueSelect\\"); new GetSegmentTopicSerie().retrouverSegment(fileParagFiltre, fileArffVecteurMots, 999999, 25, new ProduitScalaire(), fileResultat); } catch (Exception e) { e.printStackTrace(); } } public void retrouverSegment (final File repertoireParagsFiltres, final File fileArffVecteurMots, int n, int k, MetriqueSim metrique, File fileResultats) throws IOException { calculerVecteurParagsEtCentroides(fileArffVecteurMots, repertoireParagsFiltres); // crer un fichier vide dans lequel ajouter les resultats if (!Files.exists(fileResultats.toPath())) Files.createFile(fileResultats.toPath()); // map_idClasse_centroide.keySet().parallelStream().map(c->getKResultats(c, repertoireParagsFiltres, metrique, k)).forEach(pq->ecrireResultat(pq, fileResultats)); // for (int idC: map_idClasse_centroide.keySet()) // { // List<Resultat> rs = getKResultats(idC, repertoireParagsFiltres, metrique, k); // ecrireResultat(idC, rs, fileResultats); // } int[] array = {17, 56, 86, 101, 125, 131}; for (int id: map_idClasse_centroide.keySet()) { System.out.println("theme: " +id); List<Resultat> rs = getKResultats(id, repertoireParagsFiltres, n, metrique, k); ecrireResultat(id, rs, fileResultats); } } class Resultat { private double sim; private File file; // private int idC; public Resultat(double sim, File file) { this.file=file; this.sim=sim; // this.idC =idC; } public File getFile() { return file; } public double getSim() { return sim; } // public double compare(Resultat o1, Resultat o2) // { // // return Double.compare(o1.getSim(), o2.getSim()); // } } public List<Resultat> getKResultats(int idC, final File reperoireParagsFiltres, int n, MetriqueSim metrique, int k) throws IOException { System.out.println("getKResultats du theme :"+ idC); PriorityQueue<Resultat> pq = new PriorityQueue<>((rs1,rs2)->Double.compare(rs1.getSim(), rs2.getSim())); // PriorityQueue<Resultat> pq = new PriorityQueue<>(); DirectoryStream<Path> stream = Files.newDirectoryStream(reperoireParagsFiltres.toPath()); int i = 0; for (Path p: stream) { if (i>n) break; i++; Set<String> tokens = Tokeniseur.extraireEnsembleToken(FileUtils.read(p.toFile())); double[] v = getSegmentVecto(tokens); double sim = metrique.calculerMetrique(v, map_idClasse_centroide.get(idC)); if (pq.size() < k) { File file = new File(repertoireParagSelect.concat("\\").concat(p.toFile().getName())); Resultat rs = new Resultat(sim, file); pq.add(rs); } else if (pq.peek().getSim()< sim) { File file = new File(repertoireParagSelect.concat("\\").concat(p.toFile().getName())); Resultat rs = new Resultat(sim, file); pq.poll(); pq.add(rs); } } stream.close(); return new ArrayList<>(pq); } public Resultat calculerSim(double[] centroide, final File fileParag, MetriqueSim metrique) { String s=""; try { s = FileUtils.read(fileParag); } catch (IOException ex) { ex.printStackTrace(); } // cette condiction est pour eviter un throw exception. Si on ne peut pas lire le fichier alors le segment est vide et on creer un Resultat avec un similarite de 0.0 if (s.isEmpty()) return new Resultat(0.0, fileParag); Set<String> tokens = Tokeniseur.extraireEnsembleToken(s); double[] v = getSegmentVecto(tokens); double sim = metrique.calculerMetrique(v, centroide); File file = new File(repertoireParagSelect.concat("\\").concat(fileParag.getName())); return new Resultat(sim, file); } public void ecrireResultat(int idC, List<Resultat> resultats, File fileResultats) throws IOException { System.out.println("ecrireResultat du theme : " + idC); StringBuilder resultat; List<String> outputCsv = new ArrayList<>(); for (Resultat rs: resultats) { resultat=new StringBuilder(100); String segment = FileUtils.read(rs.getFile()); resultat.append(idC).append(";").append(rs.getSim()).append(";").append('"').append(segment).append('"').append(";"); outputCsv.add(resultat.toString()); } Files.write(fileResultats.toPath(), outputCsv, Charset.forName("UTF-8"), StandardOpenOption.APPEND); System.out.println(outputCsv.toString()); } // public PriorityQueue<Resultat> getKResultats(int idC, final File fileParagFiltre, MetriqueSim metrique, int k) // { // PriorityQueue<Resultat> pq = new PriorityQueue<>(); // int n = 0; // // try { // DirectoryStream<Path> stream = Files.newDirectoryStream(fileParagFiltre.toPath()); // // for (Path p: stream) // { // if (n>1000) // break; // n++; // // Set<String> tokens = Tokeniseur.extraireEnsembleToken(FileUtils.read(p.toFile())); // double[] v = getSegmentVecto(tokens); // double sim = metrique.calculerMetrique(v, map_idClasse_centroide.get(idC)); // // if (pq.size() < k) // { // Resultat rs = new Resultat(sim, fileParagFiltre, idC); // pq.add(rs); // } // else if (pq.peek().getSim()< sim) // { // Resultat rs = new Resultat(sim, fileParagFiltre, idC); // pq.poll(); // pq.add(rs); // } // } // stream.close(); // } // catch (IOException ex) // { // ex.printStackTrace(); // } // // return pq; // } public void calculerVecteurParagsEtCentroides(final File fileArffVecteurMots, final File filesParagFiltre) throws FileNotFoundException, IOException { System.out.println("recupererVecteursEtCentroides"); BufferedReader reader = new BufferedReader(new FileReader(fileArffVecteurMots)); data = new ArffLoader.ArffReader(reader).getData(); reader.close(); Map<Integer, String> map_idV_classe = ArffUtils.getMap_idInstance_attribut(data, "@@class@@"); data.deleteAttributeAt(data.attribute("@@class@@").index()); Map<Integer, String> map_idV_token = ArffUtils.getMap_idInstance_attribut(data, "@@name@@"); map_token_id = TrieUtils.inverserMap(map_idV_token); data.deleteAttributeAt(data.attribute("@@name@@").index()); // Map<Integer, VecteurCreux> map_idToken_vecteur = ArffUtils.getDenseVector(data, 0.0); // centroide map_idClasse_centroide = new HashMap<>(); Map<String, Set<Integer>> map_classe_idVecteurs = TrieUtils.recupererMap_valeur_ensembleCle2(map_idV_classe); for (String c: map_classe_idVecteurs.keySet()) { // System.out.println(c); int idC = Integer.parseInt(c); map_idClasse_centroide.put(idC, calculerCentroide(data, map_classe_idVecteurs.get(c))); } } private double[] calculerCentroide(Instances data, Set<Integer> idInstances) { double[] v = new double[data.numAttributes()]; Arrays.fill(v, 0.0); for (int i: idInstances) v = VecteurCreux.additionnerVecteurs(v, data.get(i).toDoubleArray()); return VecteurCreux.normer(v); } public double[] getSegmentVecto (Set<String> tokensParag) { double[] v = new double[map_token_id.size()]; Arrays.fill(v, 0.0); for (String token: tokensParag) { v = VecteurCreux.additionnerVecteursBSurA(v, data.get(map_token_id.get(token)).toDoubleArray()); } return VecteurCreux.normer(v); } }
UTF-8
Java
11,249
java
GetSegmentTopicSerie.java
Java
[ { "context": "core.converters.ArffLoader;\r\n\r\n/**\r\n *\r\n * @author JF Chartier\r\n */\r\npublic class GetSegmentTopicSerie \r\n{\r\n pr", "end": 1299, "score": 0.901348888874054, "start": 1288, "tag": "NAME", "value": "JF Chartier" }, { "context": " File fileArffVecteurMots = new File(\"C:\\\\Users\\\\JF Chartier\\\\Google Drive\\\\Ordinateur\\\\Projet sur BioMed\\\\V6\\", "end": 1977, "score": 0.9997648596763611, "start": 1966, "tag": "NAME", "value": "JF Chartier" }, { "context": " File fileResultat = new File (\"C:\\\\Users\\\\JF Chartier\\\\Google Drive\\\\Ordinateur\\\\Projet sur BioMed\\\\V6\\", "end": 2130, "score": 0.9997577667236328, "start": 2119, "tag": "NAME", "value": "JF Chartier" }, { "context": " File fileParagFiltre = new File(\"C:\\\\Users\\\\JF Chartier\\\\Documents\\\\Collections standard\\\\Corpus BioMed\\\\", "end": 2266, "score": 0.9997836947441101, "start": 2255, "tag": "NAME", "value": "JF Chartier" } ]
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 Analyses.SegmentsPlusProchesDesCentroides; import Corpus.CorpusUtils; import Fichier.Arff.ArffUtils; import Fichier.FileUtils; import Matrice.Vectorisateur.VecteurCreux; import Metrique.Similitude.MetriqueSim; import Metrique.Similitude.ProduitScalaire; import Tokenisation.Tokeniseur; import UtilsJFC.TrieUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Random; import java.util.Set; import java.util.concurrent.ForkJoinPool; import java.util.stream.Collectors; import weka.core.Instances; import weka.core.converters.ArffLoader; /** * * @author <NAME> */ public class GetSegmentTopicSerie { private Map<Integer, double[]> map_idClasse_centroide; private Instances data; private Map<String, Integer> map_token_id; private final String repertoireParagSelect = CorpusUtils.getRepertoireParagrapheRevueSelectionnee().toString(); public static void main(String[] args) throws FileNotFoundException, IOException { try { // ForkJoinPool commonPool = ForkJoinPool.commonPool(); // System.out.println(commonPool.getParallelism()); File fileArffVecteurMots = new File("C:\\Users\\<NAME>\\Google Drive\\Ordinateur\\Projet sur BioMed\\V6\\vecteursMotsAvecClasseEtNom.arff"); File fileResultat = new File ("C:\\Users\\<NAME>\\Google Drive\\Ordinateur\\Projet sur BioMed\\V6\\Resultats.csv"); File fileParagFiltre = new File("C:\\Users\\<NAME>\\Documents\\Collections standard\\Corpus BioMed\\paragrapheFiltreRevueSelect\\"); new GetSegmentTopicSerie().retrouverSegment(fileParagFiltre, fileArffVecteurMots, 999999, 25, new ProduitScalaire(), fileResultat); } catch (Exception e) { e.printStackTrace(); } } public void retrouverSegment (final File repertoireParagsFiltres, final File fileArffVecteurMots, int n, int k, MetriqueSim metrique, File fileResultats) throws IOException { calculerVecteurParagsEtCentroides(fileArffVecteurMots, repertoireParagsFiltres); // crer un fichier vide dans lequel ajouter les resultats if (!Files.exists(fileResultats.toPath())) Files.createFile(fileResultats.toPath()); // map_idClasse_centroide.keySet().parallelStream().map(c->getKResultats(c, repertoireParagsFiltres, metrique, k)).forEach(pq->ecrireResultat(pq, fileResultats)); // for (int idC: map_idClasse_centroide.keySet()) // { // List<Resultat> rs = getKResultats(idC, repertoireParagsFiltres, metrique, k); // ecrireResultat(idC, rs, fileResultats); // } int[] array = {17, 56, 86, 101, 125, 131}; for (int id: map_idClasse_centroide.keySet()) { System.out.println("theme: " +id); List<Resultat> rs = getKResultats(id, repertoireParagsFiltres, n, metrique, k); ecrireResultat(id, rs, fileResultats); } } class Resultat { private double sim; private File file; // private int idC; public Resultat(double sim, File file) { this.file=file; this.sim=sim; // this.idC =idC; } public File getFile() { return file; } public double getSim() { return sim; } // public double compare(Resultat o1, Resultat o2) // { // // return Double.compare(o1.getSim(), o2.getSim()); // } } public List<Resultat> getKResultats(int idC, final File reperoireParagsFiltres, int n, MetriqueSim metrique, int k) throws IOException { System.out.println("getKResultats du theme :"+ idC); PriorityQueue<Resultat> pq = new PriorityQueue<>((rs1,rs2)->Double.compare(rs1.getSim(), rs2.getSim())); // PriorityQueue<Resultat> pq = new PriorityQueue<>(); DirectoryStream<Path> stream = Files.newDirectoryStream(reperoireParagsFiltres.toPath()); int i = 0; for (Path p: stream) { if (i>n) break; i++; Set<String> tokens = Tokeniseur.extraireEnsembleToken(FileUtils.read(p.toFile())); double[] v = getSegmentVecto(tokens); double sim = metrique.calculerMetrique(v, map_idClasse_centroide.get(idC)); if (pq.size() < k) { File file = new File(repertoireParagSelect.concat("\\").concat(p.toFile().getName())); Resultat rs = new Resultat(sim, file); pq.add(rs); } else if (pq.peek().getSim()< sim) { File file = new File(repertoireParagSelect.concat("\\").concat(p.toFile().getName())); Resultat rs = new Resultat(sim, file); pq.poll(); pq.add(rs); } } stream.close(); return new ArrayList<>(pq); } public Resultat calculerSim(double[] centroide, final File fileParag, MetriqueSim metrique) { String s=""; try { s = FileUtils.read(fileParag); } catch (IOException ex) { ex.printStackTrace(); } // cette condiction est pour eviter un throw exception. Si on ne peut pas lire le fichier alors le segment est vide et on creer un Resultat avec un similarite de 0.0 if (s.isEmpty()) return new Resultat(0.0, fileParag); Set<String> tokens = Tokeniseur.extraireEnsembleToken(s); double[] v = getSegmentVecto(tokens); double sim = metrique.calculerMetrique(v, centroide); File file = new File(repertoireParagSelect.concat("\\").concat(fileParag.getName())); return new Resultat(sim, file); } public void ecrireResultat(int idC, List<Resultat> resultats, File fileResultats) throws IOException { System.out.println("ecrireResultat du theme : " + idC); StringBuilder resultat; List<String> outputCsv = new ArrayList<>(); for (Resultat rs: resultats) { resultat=new StringBuilder(100); String segment = FileUtils.read(rs.getFile()); resultat.append(idC).append(";").append(rs.getSim()).append(";").append('"').append(segment).append('"').append(";"); outputCsv.add(resultat.toString()); } Files.write(fileResultats.toPath(), outputCsv, Charset.forName("UTF-8"), StandardOpenOption.APPEND); System.out.println(outputCsv.toString()); } // public PriorityQueue<Resultat> getKResultats(int idC, final File fileParagFiltre, MetriqueSim metrique, int k) // { // PriorityQueue<Resultat> pq = new PriorityQueue<>(); // int n = 0; // // try { // DirectoryStream<Path> stream = Files.newDirectoryStream(fileParagFiltre.toPath()); // // for (Path p: stream) // { // if (n>1000) // break; // n++; // // Set<String> tokens = Tokeniseur.extraireEnsembleToken(FileUtils.read(p.toFile())); // double[] v = getSegmentVecto(tokens); // double sim = metrique.calculerMetrique(v, map_idClasse_centroide.get(idC)); // // if (pq.size() < k) // { // Resultat rs = new Resultat(sim, fileParagFiltre, idC); // pq.add(rs); // } // else if (pq.peek().getSim()< sim) // { // Resultat rs = new Resultat(sim, fileParagFiltre, idC); // pq.poll(); // pq.add(rs); // } // } // stream.close(); // } // catch (IOException ex) // { // ex.printStackTrace(); // } // // return pq; // } public void calculerVecteurParagsEtCentroides(final File fileArffVecteurMots, final File filesParagFiltre) throws FileNotFoundException, IOException { System.out.println("recupererVecteursEtCentroides"); BufferedReader reader = new BufferedReader(new FileReader(fileArffVecteurMots)); data = new ArffLoader.ArffReader(reader).getData(); reader.close(); Map<Integer, String> map_idV_classe = ArffUtils.getMap_idInstance_attribut(data, "@@class@@"); data.deleteAttributeAt(data.attribute("@@class@@").index()); Map<Integer, String> map_idV_token = ArffUtils.getMap_idInstance_attribut(data, "@@name@@"); map_token_id = TrieUtils.inverserMap(map_idV_token); data.deleteAttributeAt(data.attribute("@@name@@").index()); // Map<Integer, VecteurCreux> map_idToken_vecteur = ArffUtils.getDenseVector(data, 0.0); // centroide map_idClasse_centroide = new HashMap<>(); Map<String, Set<Integer>> map_classe_idVecteurs = TrieUtils.recupererMap_valeur_ensembleCle2(map_idV_classe); for (String c: map_classe_idVecteurs.keySet()) { // System.out.println(c); int idC = Integer.parseInt(c); map_idClasse_centroide.put(idC, calculerCentroide(data, map_classe_idVecteurs.get(c))); } } private double[] calculerCentroide(Instances data, Set<Integer> idInstances) { double[] v = new double[data.numAttributes()]; Arrays.fill(v, 0.0); for (int i: idInstances) v = VecteurCreux.additionnerVecteurs(v, data.get(i).toDoubleArray()); return VecteurCreux.normer(v); } public double[] getSegmentVecto (Set<String> tokensParag) { double[] v = new double[map_token_id.size()]; Arrays.fill(v, 0.0); for (String token: tokensParag) { v = VecteurCreux.additionnerVecteursBSurA(v, data.get(map_token_id.get(token)).toDoubleArray()); } return VecteurCreux.normer(v); } }
11,229
0.583163
0.578363
289
36.923874
35.629307
177
false
false
0
0
0
0
0
0
0.775087
false
false
4
5f8e614aa6e1127d6cb1b2a2834af63cbcfc8ddb
27,522,150,447,953
dc0eb7b407cfed446ab90221352c59a20f9f3189
/app/src/main/java/com/example/schoolshop/entity/HomeDataEntity.java
76cd3a3c40160c5340eea52cc7c3cf8acd321b04
[]
no_license
xyj155/SchoolShop
https://github.com/xyj155/SchoolShop
fd232e2826e978135c664f702a27a1c55979f8a1
34805349842113c3aed8057c9d2d2ad19561e52b
refs/heads/master
2020-04-06T13:40:14.844000
2018-11-23T01:55:43
2018-11-23T01:55:43
155,573,398
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.schoolshop.entity; import com.example.schoolshop.gson.BannerGson; import com.example.schoolshop.gson.GoodGson; import java.util.List; /** * Created by Administrator on 2018/11/3. */ public class HomeDataEntity { private List<GoodGson.GoodsBean> goodGson; public HomeDataEntity(List<GoodGson.GoodsBean> goodGson, List<BannerGson> bannerGsons) { this.goodGson = goodGson; this.bannerGsons = bannerGsons; } public List<GoodGson.GoodsBean> getGoodGson() { return goodGson; } public void setGoodGson(List<GoodGson.GoodsBean> goodGson) { this.goodGson = goodGson; } public List<BannerGson> getBannerGsons() { return bannerGsons; } public void setBannerGsons(List<BannerGson> bannerGsons) { this.bannerGsons = bannerGsons; } private List<BannerGson> bannerGsons; }
UTF-8
Java
887
java
HomeDataEntity.java
Java
[ { "context": "odGson;\n\nimport java.util.List;\n\n/**\n * Created by Administrator on 2018/11/3.\n */\n\npublic class HomeDataEntity {\n", "end": 188, "score": 0.626459538936615, "start": 175, "tag": "USERNAME", "value": "Administrator" } ]
null
[]
package com.example.schoolshop.entity; import com.example.schoolshop.gson.BannerGson; import com.example.schoolshop.gson.GoodGson; import java.util.List; /** * Created by Administrator on 2018/11/3. */ public class HomeDataEntity { private List<GoodGson.GoodsBean> goodGson; public HomeDataEntity(List<GoodGson.GoodsBean> goodGson, List<BannerGson> bannerGsons) { this.goodGson = goodGson; this.bannerGsons = bannerGsons; } public List<GoodGson.GoodsBean> getGoodGson() { return goodGson; } public void setGoodGson(List<GoodGson.GoodsBean> goodGson) { this.goodGson = goodGson; } public List<BannerGson> getBannerGsons() { return bannerGsons; } public void setBannerGsons(List<BannerGson> bannerGsons) { this.bannerGsons = bannerGsons; } private List<BannerGson> bannerGsons; }
887
0.700113
0.692221
38
22.342106
23.575497
92
false
false
0
0
0
0
0
0
0.342105
false
false
4
71e3b4758ac64782a848cee4a6c244941801a1e5
10,831,907,588,766
25c181b1272ad2efa6c8a0f3c644800e8e20e619
/racket 3/src/state/racket/ServiceState.java
a3cc9555a2bee61ef43ac1ce821c91ea7769310c
[]
no_license
Haseeb1111/WEEK-6-racket
https://github.com/Haseeb1111/WEEK-6-racket
25c95db17363ea295e1976cb1263a2ad505494e3
6db178f03d20a5f104d9fe33affd8fc451c6190d
refs/heads/main
2023-08-12T07:01:45.278000
2021-10-08T21:11:00
2021-10-08T21:11:00
415,126,668
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package state.racket; public class ServiceState implements State { Racket racket; public ServiceState(Racket racket) { this.racket = racket; } @Override public void CreateRacket() { System.out.println("Racket already brought"); racket.setState(racket.getCreateState()); } @Override public void playRacket() { System.out.println("Rackets are played in pairs along with a shuttle cock"); racket.setState(racket.getPlayState()); } @Override public void serviceRacket() { System.out.println("Racket broken, We can not play with it"); } @Override public void idleRacket() { System.out.println("racket broke"); racket.setState(racket.getIdleState()); } public String toString() { return "Racket maintaining"; } }
UTF-8
Java
856
java
ServiceState.java
Java
[]
null
[]
package state.racket; public class ServiceState implements State { Racket racket; public ServiceState(Racket racket) { this.racket = racket; } @Override public void CreateRacket() { System.out.println("Racket already brought"); racket.setState(racket.getCreateState()); } @Override public void playRacket() { System.out.println("Rackets are played in pairs along with a shuttle cock"); racket.setState(racket.getPlayState()); } @Override public void serviceRacket() { System.out.println("Racket broken, We can not play with it"); } @Override public void idleRacket() { System.out.println("racket broke"); racket.setState(racket.getIdleState()); } public String toString() { return "Racket maintaining"; } }
856
0.632009
0.632009
38
21.526316
21.620819
84
false
false
0
0
0
0
0
0
0.315789
false
false
4
2962d4166b286aacecb805ef34ed751af235ce12
30,614,526,942,449
cf9edcfe475aa9e5523cf35e8cf3a4cdab248ca5
/src/mysterydungeon/entity/Entity.java
3dac5798d6faf551943ea2684b399c7655d17fc6
[]
no_license
Lucbui/Mystery-Dungeon
https://github.com/Lucbui/Mystery-Dungeon
9a59c17fac6aa360d159389be89bf4844eb846ee
e2c92d8f704e211d6a77925f488cd7bec0f81c6b
refs/heads/master
2021-05-04T10:09:03.915000
2016-05-11T22:00:36
2016-05-11T22:00:36
52,830,237
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 mysterydungeon.entity; import java.awt.image.BufferedImage; import java.util.ArrayList; import mysterydungeon.dungeon.Dungeon; import mysterydungeon.dungeon.Node; import mysterydungeon.dungeon.RoomNode; /** * Represents a basic Entity. * This class is used to bridge the gap between a class, and its appearance * in the dungeon. * @author jlamanna */ public interface Entity { /** * Get the X value of the entity. * @return The X value of the entity, in pixels. */ int getX(); /** * Get the Y value of the entity. * @return The Y value of the entity, in pixels. */ int getY(); /** * Get how this entity should be drawn. * @return The image of this entity. */ BufferedImage getImage(); /** * Generates a random node. * More specifically, this picks a random room, then a random * number inside that. It makes no distinction on whether the * node is occupied or not. * @param dungeon The dungeon the entity is in. * @return A random node of a random room. */ static Node generateRandomLocation(Dungeon dungeon) { ArrayList<RoomNode> rooms = dungeon.getRooms(); int randomRoom = Dungeon.PRNG.nextInt(rooms.size()); RoomNode room = rooms.get(randomRoom); ArrayList<Node> nodes = room.getNodes(); int randomNode = Dungeon.PRNG.nextInt(nodes.size()); return nodes.get(randomNode); } }
UTF-8
Java
1,659
java
Entity.java
Java
[ { "context": ", and its appearance\n * in the dungeon.\n * @author jlamanna\n */\npublic interface Entity\n{\n /**\n * Get ", "end": 546, "score": 0.9996084570884705, "start": 538, "tag": "USERNAME", "value": "jlamanna" } ]
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 mysterydungeon.entity; import java.awt.image.BufferedImage; import java.util.ArrayList; import mysterydungeon.dungeon.Dungeon; import mysterydungeon.dungeon.Node; import mysterydungeon.dungeon.RoomNode; /** * Represents a basic Entity. * This class is used to bridge the gap between a class, and its appearance * in the dungeon. * @author jlamanna */ public interface Entity { /** * Get the X value of the entity. * @return The X value of the entity, in pixels. */ int getX(); /** * Get the Y value of the entity. * @return The Y value of the entity, in pixels. */ int getY(); /** * Get how this entity should be drawn. * @return The image of this entity. */ BufferedImage getImage(); /** * Generates a random node. * More specifically, this picks a random room, then a random * number inside that. It makes no distinction on whether the * node is occupied or not. * @param dungeon The dungeon the entity is in. * @return A random node of a random room. */ static Node generateRandomLocation(Dungeon dungeon) { ArrayList<RoomNode> rooms = dungeon.getRooms(); int randomRoom = Dungeon.PRNG.nextInt(rooms.size()); RoomNode room = rooms.get(randomRoom); ArrayList<Node> nodes = room.getNodes(); int randomNode = Dungeon.PRNG.nextInt(nodes.size()); return nodes.get(randomNode); } }
1,659
0.660036
0.660036
57
28.105263
22.283409
79
false
false
0
0
0
0
0
0
0.403509
false
false
4
0a393ea3e0491fad8fa27c8949288608ed4e0838
20,306,605,428,276
81819a17b92ad596e22ea851b20f307a35d18d4c
/java01-bit/src/step16/Test02_6_out.java
5ca330537da67d94fbbebe757ff318f96da5fd4b
[]
no_license
eomjinyoung/java93
https://github.com/eomjinyoung/java93
cd05b4565249771a47f4ceb1f108acfb0d8004ce
7a71a2bedbc99a9f222564ebbfbe69ed423511ac
refs/heads/master
2021-01-22T17:47:48.636000
2017-10-23T10:32:14
2017-10-23T10:32:14
85,033,606
3
7
null
null
null
null
null
null
null
null
null
null
null
null
null
/* File I/O : 바이트 스트림 클래스 - DataOutputStream * => 상속이 아닌 위임이라는 방법을 사용해서 기능 확장하기 */ package step16; import java.io.FileOutputStream; public class Test02_6_out { public static void main(String[] args) throws Exception { FileOutputStream out0 = new FileOutputStream("test02_6.data"); DataOutputStream out = new DataOutputStream(out0); byte b = 0x11; out.writeByte(b); short s = 0x2233; out.writeShort(s); int i = 0x44556677; out.writeInt(i); String str = "ABC가각간"; out.writeUTF(str); out.close(); System.out.println("파일 출력 완료!"); } }
UTF-8
Java
705
java
Test02_6_out.java
Java
[]
null
[]
/* File I/O : 바이트 스트림 클래스 - DataOutputStream * => 상속이 아닌 위임이라는 방법을 사용해서 기능 확장하기 */ package step16; import java.io.FileOutputStream; public class Test02_6_out { public static void main(String[] args) throws Exception { FileOutputStream out0 = new FileOutputStream("test02_6.data"); DataOutputStream out = new DataOutputStream(out0); byte b = 0x11; out.writeByte(b); short s = 0x2233; out.writeShort(s); int i = 0x44556677; out.writeInt(i); String str = "ABC가각간"; out.writeUTF(str); out.close(); System.out.println("파일 출력 완료!"); } }
705
0.619583
0.576244
30
19.466667
18.21489
66
false
false
0
0
0
0
0
0
0.466667
false
false
4
36b64da2aeed7cd826d752da00d344b42373dabd
14,860,586,878,778
b3768ea3ca7aaf66402c80275505433dee9932db
/src/main/java/top/yunshu/shw/server/cas/JwtCasCallBackImpl.java
509040bfa577f693b528d86d78115be43a3a063c
[ "Apache-2.0" ]
permissive
HXCI-Studio/shw_server
https://github.com/HXCI-Studio/shw_server
ce92a0c152f4049ed8ea66fafcf4deb352ae13b8
f81dcaafa310fb075bd7c06806346bec2757828d
refs/heads/master
2021-08-07T16:48:40.693000
2020-06-06T08:51:02
2020-06-06T08:51:02
186,948,967
0
1
Apache-2.0
true
2020-06-06T08:51:03
2019-05-16T04:06:49
2019-06-23T08:19:52
2020-06-06T08:51:03
17,672
0
1
0
Java
false
false
package top.yunshu.shw.server.cas; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import top.itning.cas.CasProperties; import top.itning.cas.callback.AbstractCasCallBackImpl; import top.yunshu.shw.server.dao.StudentDao; import top.yunshu.shw.server.entity.LoginUser; import top.yunshu.shw.server.entity.RestModel; import top.yunshu.shw.server.entity.Student; import top.yunshu.shw.server.util.JwtUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.Arrays; import java.util.Map; /** * Jwt实现 * * @author itning */ @Component public class JwtCasCallBackImpl extends AbstractCasCallBackImpl { private static final Logger logger = LoggerFactory.getLogger(JwtCasCallBackImpl.class); private static final String LOGIN_NAME = "loginName"; private static final String STUDENT_USER_TYPE = "99"; private final StudentDao studentDao; @Autowired public JwtCasCallBackImpl(CasProperties casProperties, StudentDao studentDao) { super(casProperties); this.studentDao = studentDao; } @Override public void onLoginSuccess(HttpServletResponse resp, HttpServletRequest req, Map<String, String> attributesMap) throws IOException { if (attributesMap.isEmpty()) { sendRefresh2Response(resp); return; } LoginUser loginUser = map2userLoginEntity(attributesMap); if (STUDENT_USER_TYPE.equals(loginUser.getUserType())) { Student student = new Student(); student.setNo(loginUser.getNo()); student.setLoginName(loginUser.getLoginName()); student.setName(loginUser.getName()); student.setClazzId(loginUser.getClazzId()); studentDao.saveAndFlush(student); } String jwt = JwtUtils.buildJwt(loginUser); //重定向到登陆成功需要跳转的地址 resp.sendRedirect(casProperties.getLoginSuccessUrl().toString() + "/token/" + jwt); } @Override public void onLoginFailure(HttpServletResponse resp, HttpServletRequest req, Exception e) throws IOException { sendRefresh2Response(resp); } @Override public void onNeverLogin(HttpServletResponse resp, HttpServletRequest req) throws IOException { allowCors(resp, req); writeJson2Response(resp, HttpStatus.UNAUTHORIZED, "请先登录"); } /** * 将Map集合转换成{@link LoginUser} * * @param map 要转换的Map集合 * @return {@link LoginUser} */ private LoginUser map2userLoginEntity(Map<String, String> map) { LoginUser loginUser = new LoginUser(); Class<LoginUser> loginUserClass = LoginUser.class; Arrays.stream(loginUserClass.getDeclaredFields()).forEach(field -> { try { field.setAccessible(true); String name = field.getName(); String value = map.get(name); if (LOGIN_NAME.equals(name)) { value = map.get("login_name"); } if (value != null) { field.set(loginUser, value); } } catch (Exception e) { logger.error("map2userLoginEntity error: ", e); } }); return loginUser; } /** * 将消息转换成JSON并写入到{@link HttpServletResponse}中 * * @param resp {@link HttpServletResponse} * @param httpStatus {@link HttpStatus} * @param msg 消息 * @throws IOException IOException */ private void writeJson2Response(HttpServletResponse resp, HttpStatus httpStatus, String msg) throws IOException { resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); resp.setStatus(httpStatus.value()); RestModel<Void> restModel = new RestModel<>(); restModel.setCode(httpStatus.value()); restModel.setMsg(msg); String json = MAPPER.writeValueAsString(restModel); PrintWriter writer = resp.getWriter(); writer.write(json); writer.flush(); writer.close(); } /** * 登陆失败时 * * @param resp {@link HttpServletResponse} * @throws IOException IOException */ private void sendRefresh2Response(HttpServletResponse resp) throws IOException { resp.setCharacterEncoding("utf-8"); String location = casProperties.getLoginUrl() + "?service=" + URLEncoder.encode(casProperties.getLocalServerUrl().toString(), "UTF-8"); PrintWriter writer = resp.getWriter(); writer.write("<!DOCTYPE html><html><head><meta charset=\"UTF-8\">\n" + "<meta http-equiv=\"refresh\" content=\"3;url=" + location + "\">" + "<title>身份信息获取失败</title></head><body>" + "身份信息获取失败,3秒后重试..." + "</body></html>"); writer.flush(); writer.close(); } }
UTF-8
Java
5,278
java
JwtCasCallBackImpl.java
Java
[ { "context": "\nimport java.util.Map;\n\n/**\n * Jwt实现\n *\n * @author itning\n */\n@Component\npublic class JwtCasCallBackImpl ex", "end": 872, "score": 0.9995691180229187, "start": 866, "tag": "USERNAME", "value": "itning" } ]
null
[]
package top.yunshu.shw.server.cas; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import top.itning.cas.CasProperties; import top.itning.cas.callback.AbstractCasCallBackImpl; import top.yunshu.shw.server.dao.StudentDao; import top.yunshu.shw.server.entity.LoginUser; import top.yunshu.shw.server.entity.RestModel; import top.yunshu.shw.server.entity.Student; import top.yunshu.shw.server.util.JwtUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.Arrays; import java.util.Map; /** * Jwt实现 * * @author itning */ @Component public class JwtCasCallBackImpl extends AbstractCasCallBackImpl { private static final Logger logger = LoggerFactory.getLogger(JwtCasCallBackImpl.class); private static final String LOGIN_NAME = "loginName"; private static final String STUDENT_USER_TYPE = "99"; private final StudentDao studentDao; @Autowired public JwtCasCallBackImpl(CasProperties casProperties, StudentDao studentDao) { super(casProperties); this.studentDao = studentDao; } @Override public void onLoginSuccess(HttpServletResponse resp, HttpServletRequest req, Map<String, String> attributesMap) throws IOException { if (attributesMap.isEmpty()) { sendRefresh2Response(resp); return; } LoginUser loginUser = map2userLoginEntity(attributesMap); if (STUDENT_USER_TYPE.equals(loginUser.getUserType())) { Student student = new Student(); student.setNo(loginUser.getNo()); student.setLoginName(loginUser.getLoginName()); student.setName(loginUser.getName()); student.setClazzId(loginUser.getClazzId()); studentDao.saveAndFlush(student); } String jwt = JwtUtils.buildJwt(loginUser); //重定向到登陆成功需要跳转的地址 resp.sendRedirect(casProperties.getLoginSuccessUrl().toString() + "/token/" + jwt); } @Override public void onLoginFailure(HttpServletResponse resp, HttpServletRequest req, Exception e) throws IOException { sendRefresh2Response(resp); } @Override public void onNeverLogin(HttpServletResponse resp, HttpServletRequest req) throws IOException { allowCors(resp, req); writeJson2Response(resp, HttpStatus.UNAUTHORIZED, "请先登录"); } /** * 将Map集合转换成{@link LoginUser} * * @param map 要转换的Map集合 * @return {@link LoginUser} */ private LoginUser map2userLoginEntity(Map<String, String> map) { LoginUser loginUser = new LoginUser(); Class<LoginUser> loginUserClass = LoginUser.class; Arrays.stream(loginUserClass.getDeclaredFields()).forEach(field -> { try { field.setAccessible(true); String name = field.getName(); String value = map.get(name); if (LOGIN_NAME.equals(name)) { value = map.get("login_name"); } if (value != null) { field.set(loginUser, value); } } catch (Exception e) { logger.error("map2userLoginEntity error: ", e); } }); return loginUser; } /** * 将消息转换成JSON并写入到{@link HttpServletResponse}中 * * @param resp {@link HttpServletResponse} * @param httpStatus {@link HttpStatus} * @param msg 消息 * @throws IOException IOException */ private void writeJson2Response(HttpServletResponse resp, HttpStatus httpStatus, String msg) throws IOException { resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); resp.setStatus(httpStatus.value()); RestModel<Void> restModel = new RestModel<>(); restModel.setCode(httpStatus.value()); restModel.setMsg(msg); String json = MAPPER.writeValueAsString(restModel); PrintWriter writer = resp.getWriter(); writer.write(json); writer.flush(); writer.close(); } /** * 登陆失败时 * * @param resp {@link HttpServletResponse} * @throws IOException IOException */ private void sendRefresh2Response(HttpServletResponse resp) throws IOException { resp.setCharacterEncoding("utf-8"); String location = casProperties.getLoginUrl() + "?service=" + URLEncoder.encode(casProperties.getLocalServerUrl().toString(), "UTF-8"); PrintWriter writer = resp.getWriter(); writer.write("<!DOCTYPE html><html><head><meta charset=\"UTF-8\">\n" + "<meta http-equiv=\"refresh\" content=\"3;url=" + location + "\">" + "<title>身份信息获取失败</title></head><body>" + "身份信息获取失败,3秒后重试..." + "</body></html>"); writer.flush(); writer.close(); } }
5,278
0.652123
0.648617
141
35.411346
28.167198
143
false
false
0
0
0
0
0
0
0.595745
false
false
4
1735c8aa7a148cf655e1487d2eab51a44c8ea3a5
17,059,610,152,437
6f132924090b0fcc8e371ef16808036d9c00557e
/src/main/java/com/renew/updateserver/resource/OpenResource.java
250fc7a21971c0d85e81547fe5e78d51939949e6
[]
no_license
Guoyadong/asm
https://github.com/Guoyadong/asm
1dc191bd0a01a1a0b998522539d1602925ff71c9
85ca41037e17aceccaa77a57e0c0635fadb95859
refs/heads/master
2021-01-10T17:46:49.559000
2015-10-22T23:58:46
2015-10-22T23:58:46
44,779,757
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.renew.updateserver.resource; import com.renew.config.GlobalSetting; import com.renew.result.ResultError; import com.renew.updateserver.entity.App; import com.renew.updateserver.entity.Version; import com.renew.updateserver.service.AppService; import com.renew.updateserver.service.CacheService; import com.renew.updateserver.service.VersionService; import com.renew.utils.CheckedException; import com.renew.utils.PublicUtils; import com.renew.utils.SpringContextHelper; import lombok.Data; import lombok.extern.log4j.Log4j; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; @Log4j @Path("open") @Produces("text/plain") @Consumes("text/plain") public class OpenResource { private CacheService cacheService = SpringContextHelper.getBean(CacheService.class); @Path("cacheClear") @GET public void cacheClear() { cacheService.cacheClear(); } }
UTF-8
Java
1,127
java
OpenResource.java
Java
[]
null
[]
package com.renew.updateserver.resource; import com.renew.config.GlobalSetting; import com.renew.result.ResultError; import com.renew.updateserver.entity.App; import com.renew.updateserver.entity.Version; import com.renew.updateserver.service.AppService; import com.renew.updateserver.service.CacheService; import com.renew.updateserver.service.VersionService; import com.renew.utils.CheckedException; import com.renew.utils.PublicUtils; import com.renew.utils.SpringContextHelper; import lombok.Data; import lombok.extern.log4j.Log4j; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; @Log4j @Path("open") @Produces("text/plain") @Consumes("text/plain") public class OpenResource { private CacheService cacheService = SpringContextHelper.getBean(CacheService.class); @Path("cacheClear") @GET public void cacheClear() { cacheService.cacheClear(); } }
1,127
0.795918
0.793256
39
27.897436
19.735163
89
false
false
0
0
0
0
0
0
0.589744
false
false
4
69f563b7840e6085cf96109319e9efcd8794bc3d
14,181,982,064,981
35b909ec5677f8a3f8d97b4c32aa3abf502a40b5
/app/src/main/java/com/example/android/moviesapp/FavouriteMoviesActivity.java
5505a53a34f6e3511a333b2c4d0fdeb96f003513
[]
no_license
pryshankar/Popular-Movies-Stage-2
https://github.com/pryshankar/Popular-Movies-Stage-2
e4e940a55a0f72f0eaf6eaffe2ad07bf0d51fdf5
af93298b3372bd64908d8fd45355f1ddd1c9cfe8
refs/heads/master
2020-03-20T19:18:42.002000
2018-06-29T11:14:17
2018-06-29T11:14:17
137,631,826
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.moviesapp; import android.app.LoaderManager; import android.content.ContentUris; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import com.example.android.moviesapp.data.MoviesDbHelper; import com.example.android.moviesapp.data.MoviesContract.MoviesEntry; public class FavouriteMoviesActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** Database helper that will provide us access to the database */ private MoviesDbHelper mDbHelper; MoviesCursorAdapter mCursorAdapter; // this will be our adapter for gridview private static final int MOVIES_ITEM_LOADER = 0; // It can be set as any other unique integer private ProgressBar loadingInProgress; RelativeLayout movielist_parent; GridView displayView; private static final int SEARCH_QUERY_DEFAULT = 500; private static final int SEARCH_QUERY_MOST_POPULAR_MOVIES = 500; private static final int SEARCH_QUERY_HIGHEST_RATED_MOVIES = 501; private static final String SEARCH_KEY = "SEARCH_KEY"; private int latestSearch = SEARCH_QUERY_DEFAULT; private SharedPreferences prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.movies_activity); prefs = getSharedPreferences("SearchQuery", Context.MODE_PRIVATE); Intent intentThatStartedThisActivity = getIntent(); // To access our database, we instantiate our subclass of SQLiteOpenHelper // and pass the context, which is the current activity. mDbHelper = new MoviesDbHelper(this); // find the gridView which will be populated with the movies data displayView = (GridView) findViewById(R.id.list); //Setup an adapter to create a gridItem for each row of movies data in the cursor //there is no movies data yet (until the loader finishes) so pass in null for the cursor mCursorAdapter = new MoviesCursorAdapter(this,null); displayView.setAdapter(mCursorAdapter); //set up item click listener displayView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Create new intent to go to MovieDetails Activity Intent intent = new Intent(FavouriteMoviesActivity.this,MovieDetails.class); //Form the Content URI that represents the specific item that was clicked on //by appending the "id" (passed as input to this method) onto the MoviesEntry.CONTENT_URI //For example, the URI would be "content://com.example.android.moviesapp/movies/2" //if the item with id 2 was clicked on Uri currentItemUri = ContentUris.withAppendedId(MoviesEntry.CONTENT_URI,id); intent.putExtra(getString(R.string.unique_id),getString(R.string.Load_From_Movies_Table)); //set the Uri on the data field of the intent intent.setData(currentItemUri); //launch the MovieDetails to display the data for the current movie startActivity(intent); } }); //kick off the loader (cursorLoader) getLoaderManager().initLoader(MOVIES_ITEM_LOADER, null, this); } @Override public Loader<Cursor> onCreateLoader(int loaderID, Bundle args) { // Define a projection that specifies the columns from the table we care about String[] projection = { MoviesEntry._ID, MoviesEntry.COLUMN_ITEM_POSTER, MoviesEntry.COLUMN_ITEM_TITLE, MoviesEntry.COLUMN_ITEM_BACKGROUND_PICTURE, MoviesEntry.COLUMN_RELEASE_DATE, MoviesEntry.COLUMN_USER_RATING, MoviesEntry.COLUMN_PLOT_SYNOPSIS }; //This loader will execute the ContentProvider's query method on a background thread return new CursorLoader(this, // Parent activity context MoviesEntry.CONTENT_URI, //Provider content URI to query projection, // columns to include in the resulting cursor null, // no selection clause null, // no selection arguments null); // default sort order } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { loadingInProgress = (ProgressBar) findViewById(R.id.loadingInProgress); loadingInProgress.setVisibility(View.GONE); movielist_parent = (RelativeLayout) findViewById(R.id.movielist_parent); // update MoviesCursorAdapter with this new cursor containing movies data mCursorAdapter.swapCursor(cursor); if(cursor == null || cursor.getCount()<1){ movielist_parent.setBackgroundResource(R.drawable.empty_movies_list); }else{ movielist_parent.setBackgroundResource(0); } } @Override public void onLoaderReset(Loader<Cursor> loader) { //callback called when the data needs to be deleted mCursorAdapter.swapCursor(null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_movies_activity, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); //if user is inside FavouriteMoviesActivity, hide refresh option MenuItem menuItem = menu.findItem(R.id.action_refresh_internet_connection); menuItem.setVisible(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent startMoviesActivityIntent; // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Most Popular Movies" menu option case R.id.action_search_most_popular_movies: latestSearch = SEARCH_QUERY_MOST_POPULAR_MOVIES; saveLatestSearchPreference(); //search for most popular movies using API in MoviesActivity class startMoviesActivityIntent = new Intent(FavouriteMoviesActivity.this, MoviesActivity.class); startActivity(startMoviesActivityIntent); return true; // Respond to a click on the "Highest Rated Movies" menu option case R.id.action_search_highest_rated_movies: latestSearch = SEARCH_QUERY_HIGHEST_RATED_MOVIES; saveLatestSearchPreference(); //search for highest rated movies using API in MoviesActivity class startMoviesActivityIntent = new Intent(FavouriteMoviesActivity.this, MoviesActivity.class); startActivity(startMoviesActivityIntent); return true; case R.id.action_open_user_favourite_movies: //open user's favourite movies return true; case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public void saveLatestSearchPreference(){ SharedPreferences.Editor editor = prefs.edit(); editor.putInt(SEARCH_KEY, latestSearch).apply(); } @Override public void onBackPressed() { super.onBackPressed(); } }
UTF-8
Java
8,204
java
FavouriteMoviesActivity.java
Java
[]
null
[]
package com.example.android.moviesapp; import android.app.LoaderManager; import android.content.ContentUris; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import com.example.android.moviesapp.data.MoviesDbHelper; import com.example.android.moviesapp.data.MoviesContract.MoviesEntry; public class FavouriteMoviesActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** Database helper that will provide us access to the database */ private MoviesDbHelper mDbHelper; MoviesCursorAdapter mCursorAdapter; // this will be our adapter for gridview private static final int MOVIES_ITEM_LOADER = 0; // It can be set as any other unique integer private ProgressBar loadingInProgress; RelativeLayout movielist_parent; GridView displayView; private static final int SEARCH_QUERY_DEFAULT = 500; private static final int SEARCH_QUERY_MOST_POPULAR_MOVIES = 500; private static final int SEARCH_QUERY_HIGHEST_RATED_MOVIES = 501; private static final String SEARCH_KEY = "SEARCH_KEY"; private int latestSearch = SEARCH_QUERY_DEFAULT; private SharedPreferences prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.movies_activity); prefs = getSharedPreferences("SearchQuery", Context.MODE_PRIVATE); Intent intentThatStartedThisActivity = getIntent(); // To access our database, we instantiate our subclass of SQLiteOpenHelper // and pass the context, which is the current activity. mDbHelper = new MoviesDbHelper(this); // find the gridView which will be populated with the movies data displayView = (GridView) findViewById(R.id.list); //Setup an adapter to create a gridItem for each row of movies data in the cursor //there is no movies data yet (until the loader finishes) so pass in null for the cursor mCursorAdapter = new MoviesCursorAdapter(this,null); displayView.setAdapter(mCursorAdapter); //set up item click listener displayView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Create new intent to go to MovieDetails Activity Intent intent = new Intent(FavouriteMoviesActivity.this,MovieDetails.class); //Form the Content URI that represents the specific item that was clicked on //by appending the "id" (passed as input to this method) onto the MoviesEntry.CONTENT_URI //For example, the URI would be "content://com.example.android.moviesapp/movies/2" //if the item with id 2 was clicked on Uri currentItemUri = ContentUris.withAppendedId(MoviesEntry.CONTENT_URI,id); intent.putExtra(getString(R.string.unique_id),getString(R.string.Load_From_Movies_Table)); //set the Uri on the data field of the intent intent.setData(currentItemUri); //launch the MovieDetails to display the data for the current movie startActivity(intent); } }); //kick off the loader (cursorLoader) getLoaderManager().initLoader(MOVIES_ITEM_LOADER, null, this); } @Override public Loader<Cursor> onCreateLoader(int loaderID, Bundle args) { // Define a projection that specifies the columns from the table we care about String[] projection = { MoviesEntry._ID, MoviesEntry.COLUMN_ITEM_POSTER, MoviesEntry.COLUMN_ITEM_TITLE, MoviesEntry.COLUMN_ITEM_BACKGROUND_PICTURE, MoviesEntry.COLUMN_RELEASE_DATE, MoviesEntry.COLUMN_USER_RATING, MoviesEntry.COLUMN_PLOT_SYNOPSIS }; //This loader will execute the ContentProvider's query method on a background thread return new CursorLoader(this, // Parent activity context MoviesEntry.CONTENT_URI, //Provider content URI to query projection, // columns to include in the resulting cursor null, // no selection clause null, // no selection arguments null); // default sort order } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { loadingInProgress = (ProgressBar) findViewById(R.id.loadingInProgress); loadingInProgress.setVisibility(View.GONE); movielist_parent = (RelativeLayout) findViewById(R.id.movielist_parent); // update MoviesCursorAdapter with this new cursor containing movies data mCursorAdapter.swapCursor(cursor); if(cursor == null || cursor.getCount()<1){ movielist_parent.setBackgroundResource(R.drawable.empty_movies_list); }else{ movielist_parent.setBackgroundResource(0); } } @Override public void onLoaderReset(Loader<Cursor> loader) { //callback called when the data needs to be deleted mCursorAdapter.swapCursor(null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_movies_activity, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); //if user is inside FavouriteMoviesActivity, hide refresh option MenuItem menuItem = menu.findItem(R.id.action_refresh_internet_connection); menuItem.setVisible(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent startMoviesActivityIntent; // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Most Popular Movies" menu option case R.id.action_search_most_popular_movies: latestSearch = SEARCH_QUERY_MOST_POPULAR_MOVIES; saveLatestSearchPreference(); //search for most popular movies using API in MoviesActivity class startMoviesActivityIntent = new Intent(FavouriteMoviesActivity.this, MoviesActivity.class); startActivity(startMoviesActivityIntent); return true; // Respond to a click on the "Highest Rated Movies" menu option case R.id.action_search_highest_rated_movies: latestSearch = SEARCH_QUERY_HIGHEST_RATED_MOVIES; saveLatestSearchPreference(); //search for highest rated movies using API in MoviesActivity class startMoviesActivityIntent = new Intent(FavouriteMoviesActivity.this, MoviesActivity.class); startActivity(startMoviesActivityIntent); return true; case R.id.action_open_user_favourite_movies: //open user's favourite movies return true; case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public void saveLatestSearchPreference(){ SharedPreferences.Editor editor = prefs.edit(); editor.putInt(SEARCH_KEY, latestSearch).apply(); } @Override public void onBackPressed() { super.onBackPressed(); } }
8,204
0.659922
0.658094
222
35.954956
32.051727
114
false
false
0
0
0
0
0
0
0.513514
false
false
4
c11ddb7f3fc44c37e1db61849cc81a3f0abec821
17,411,797,485,387
3b765a74291ec5d29a08c01cc87e9d7871c51acf
/HtmlNativeAndroid/htmlnative-lib/src/main/java/com/mozz/htmlnative/attrshandler/AttrsHelper.java
91478b91a9cc192b5821a2fe845d4703761a940e
[ "Apache-2.0" ]
permissive
yuanwofei/HtmlNative
https://github.com/yuanwofei/HtmlNative
984f9f95c78636bceb466750099740eb3d40dace
c8c9b6747f1f91b3bf654a4edd52a2d10fbb6623
refs/heads/master
2020-12-30T14:55:23.298000
2017-05-12T09:18:27
2017-05-12T09:18:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mozz.htmlnative.attrshandler; import android.graphics.Paint; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextPaint; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.TextView; import java.util.HashMap; import java.util.Map; /** * @author Yang Tao, 17/3/22. */ public final class AttrsHelper { private AttrsHelper() { } @NonNull private static Map<Class<? extends View>, AttrHandler> sAttrHandlerCache = new HashMap<>(); private static Map<Class<? extends View>, AttrHandler> sExtraAttrHandlerCache = new HashMap<>(); public static void setPadding(View view, int padding) { if (view != null) { view.setPadding(padding, padding, padding, padding); } } public static void setPadding(View view, int topBottomPadding, int leftRightPadding) { if (view != null) { view.setPadding(leftRightPadding, topBottomPadding, leftRightPadding, topBottomPadding); } } public static void setPadding(View view, int top, int left, int bottom, int right) { if (view != null) { view.setPadding(left, top, right, bottom); } } public static void setTopPadding(View v, int top) { if (v != null) { v.setPadding(v.getPaddingLeft(), top, v.getPaddingRight(), v.getPaddingBottom()); } } public static void setLeftPadding(View v, int left) { if (v != null) { v.setPadding(left, v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom()); } } public static void setRightPadding(View v, int right) { if (v != null) { v.setPadding(v.getPaddingLeft(), v.getPaddingTop(), right, v.getPaddingBottom()); } } public static void setBottomPadding(View v, int bottom) { if (v != null) { v.setPadding(v.getPaddingLeft(), v.getPaddingTop(), v.getPaddingRight(), bottom); } } public static void setBold(TextView textView) { if (textView != null) { TextPaint paint = textView.getPaint(); paint.setFakeBoldText(true); } } public static void setUnderLine(TextView textView) { textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); } @Nullable public static AttrHandler getAttrHandler(View view) { Class<? extends View> vClazz = view.getClass(); AttrHandler attrHandler = sAttrHandlerCache.get(vClazz); if (attrHandler == null) { attrHandler = AttrsHandlerFactory.getAttrHandlerFromView(vClazz); if (attrHandler != null) { sAttrHandlerCache.put(vClazz, attrHandler); } } return attrHandler; } public static LayoutAttrHandler getParentAttrHandler(View view) { ViewParent parent = view.getParent(); if (parent instanceof ViewGroup) { AttrHandler parentAttrHandler = AttrsHelper.getAttrHandler((View) parent); LayoutAttrHandler parentLayoutAttr = null; if (parentAttrHandler instanceof LayoutAttrHandler) { parentLayoutAttr = (LayoutAttrHandler) parentAttrHandler; } return parentLayoutAttr; } else { return null; } } @Nullable public static AttrHandler getExtraAttrHandler(View view) { return sExtraAttrHandlerCache.get(view.getClass()); } public static AttrHandler registerExtraAttrHandler(Class<? extends View> viewClass, AttrHandler attrHandler) { return sExtraAttrHandlerCache.put(viewClass, attrHandler); } public static void clear() { sExtraAttrHandlerCache.clear(); sAttrHandlerCache.clear(); } }
UTF-8
Java
3,901
java
AttrsHelper.java
Java
[ { "context": "til.HashMap;\nimport java.util.Map;\n\n/**\n * @author Yang Tao, 17/3/22.\n */\n\npublic final class AttrsHelper {\n\n", "end": 386, "score": 0.999779999256134, "start": 378, "tag": "NAME", "value": "Yang Tao" } ]
null
[]
package com.mozz.htmlnative.attrshandler; import android.graphics.Paint; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextPaint; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.TextView; import java.util.HashMap; import java.util.Map; /** * @author <NAME>, 17/3/22. */ public final class AttrsHelper { private AttrsHelper() { } @NonNull private static Map<Class<? extends View>, AttrHandler> sAttrHandlerCache = new HashMap<>(); private static Map<Class<? extends View>, AttrHandler> sExtraAttrHandlerCache = new HashMap<>(); public static void setPadding(View view, int padding) { if (view != null) { view.setPadding(padding, padding, padding, padding); } } public static void setPadding(View view, int topBottomPadding, int leftRightPadding) { if (view != null) { view.setPadding(leftRightPadding, topBottomPadding, leftRightPadding, topBottomPadding); } } public static void setPadding(View view, int top, int left, int bottom, int right) { if (view != null) { view.setPadding(left, top, right, bottom); } } public static void setTopPadding(View v, int top) { if (v != null) { v.setPadding(v.getPaddingLeft(), top, v.getPaddingRight(), v.getPaddingBottom()); } } public static void setLeftPadding(View v, int left) { if (v != null) { v.setPadding(left, v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom()); } } public static void setRightPadding(View v, int right) { if (v != null) { v.setPadding(v.getPaddingLeft(), v.getPaddingTop(), right, v.getPaddingBottom()); } } public static void setBottomPadding(View v, int bottom) { if (v != null) { v.setPadding(v.getPaddingLeft(), v.getPaddingTop(), v.getPaddingRight(), bottom); } } public static void setBold(TextView textView) { if (textView != null) { TextPaint paint = textView.getPaint(); paint.setFakeBoldText(true); } } public static void setUnderLine(TextView textView) { textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); } @Nullable public static AttrHandler getAttrHandler(View view) { Class<? extends View> vClazz = view.getClass(); AttrHandler attrHandler = sAttrHandlerCache.get(vClazz); if (attrHandler == null) { attrHandler = AttrsHandlerFactory.getAttrHandlerFromView(vClazz); if (attrHandler != null) { sAttrHandlerCache.put(vClazz, attrHandler); } } return attrHandler; } public static LayoutAttrHandler getParentAttrHandler(View view) { ViewParent parent = view.getParent(); if (parent instanceof ViewGroup) { AttrHandler parentAttrHandler = AttrsHelper.getAttrHandler((View) parent); LayoutAttrHandler parentLayoutAttr = null; if (parentAttrHandler instanceof LayoutAttrHandler) { parentLayoutAttr = (LayoutAttrHandler) parentAttrHandler; } return parentLayoutAttr; } else { return null; } } @Nullable public static AttrHandler getExtraAttrHandler(View view) { return sExtraAttrHandlerCache.get(view.getClass()); } public static AttrHandler registerExtraAttrHandler(Class<? extends View> viewClass, AttrHandler attrHandler) { return sExtraAttrHandlerCache.put(viewClass, attrHandler); } public static void clear() { sExtraAttrHandlerCache.clear(); sAttrHandlerCache.clear(); } }
3,899
0.632146
0.630864
124
30.459677
29.397552
100
false
false
0
0
0
0
0
0
0.612903
false
false
4
9154b577302fb9180e7ec7f10a8df75c9d637ebb
17,411,797,484,483
d947f2a52245291c9eb784935a68da60f508f2db
/Practice_Chap34(IO기반 입출력)/src/sec01/exam04_writer_write/WriteExample03.java
5e9bb9b5ff65093bec1cadbe9e9cc9aa6c8d7f3c
[]
no_license
ColossusCMS/Eclipse_Prac
https://github.com/ColossusCMS/Eclipse_Prac
064755afa996a063aeeb9aeb9b093c62de4685a0
e40e189c201ce80d9c218467ea29accf6049a67e
refs/heads/master
2020-05-17T22:23:27.175000
2020-01-07T15:44:37
2020-01-07T15:44:37
183,992,653
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sec01.exam04_writer_write; import java.io.FileWriter; import java.io.Writer; public class WriteExample03 { public static void main(String[] args) throws Exception { Writer writer = new FileWriter("c:/temp.txt"); char[] cbuf = "¿ÀŽñâ".toCharArray(); writer.write(cbuf, 1, 2); writer.flush(); writer.close(); } }
WINDOWS-1252
Java
344
java
WriteExample03.java
Java
[]
null
[]
package sec01.exam04_writer_write; import java.io.FileWriter; import java.io.Writer; public class WriteExample03 { public static void main(String[] args) throws Exception { Writer writer = new FileWriter("c:/temp.txt"); char[] cbuf = "¿ÀŽñâ".toCharArray(); writer.write(cbuf, 1, 2); writer.flush(); writer.close(); } }
344
0.702381
0.675595
14
23
17.752264
58
false
false
0
0
0
0
0
0
1.571429
false
false
4
c0e5fc413dfe4ad9d84ca59bec85de58814c17b6
27,144,193,343,083
4f6e97094fd67910e1527c50c550152b20c0e081
/20170310/src/pkg_animal/Monkey.java
0e79a21e84a9b21801f0ffcaf4d9b6d45786a4e0
[]
no_license
SeungwanHong/JAVA
https://github.com/SeungwanHong/JAVA
ef020e5ee8e7ed7860bb652b673781ae9c00f78e
db1f5e8bdb860ef514f77add17bb730a294db205
refs/heads/master
2021-01-22T23:29:18.407000
2017-04-07T08:57:43
2017-04-07T08:57:43
85,641,117
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pkg_animal; public class Monkey extends Omnivo{ @Override public void eat() { // TODO Auto-generated method stub System.out.println("원숭이가 밥을 쩝쩝 먹는다."); } @Override public void run() { // TODO Auto-generated method stub super.run(); System.out.println("뛴다."); } public void climmingTree(){ System.out.println("나무 타기"); } }
UHC
Java
391
java
Monkey.java
Java
[]
null
[]
package pkg_animal; public class Monkey extends Omnivo{ @Override public void eat() { // TODO Auto-generated method stub System.out.println("원숭이가 밥을 쩝쩝 먹는다."); } @Override public void run() { // TODO Auto-generated method stub super.run(); System.out.println("뛴다."); } public void climmingTree(){ System.out.println("나무 타기"); } }
391
0.663866
0.663866
22
15.227273
14.071027
40
false
false
0
0
0
0
0
0
1.227273
false
false
4
f158d9f7fb0256186ff0008a2b91f40d0e2ae74e
17,317,308,185,675
6b2c17b1b0e1fcafca79b8f2500d19e319dba853
/src/Receptionists/newPatient.java
3c9492a7c53efeff47fe3df5cbb1f6a7ce7663db
[]
no_license
anotherwebguy/Hospital-Management-System
https://github.com/anotherwebguy/Hospital-Management-System
071851dc3d91cbba6894ed3331e7428cf11b4081
bc6a808fa33292ceccdcb3ad48c679d21a8ef978
refs/heads/master
2023-05-05T03:57:23.338000
2021-05-25T10:41:52
2021-05-25T10:41:52
370,656,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Receptionists; import Main.Hospital; import Main.Connector; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author Sajeeb */ public class newPatient extends javax.swing.JFrame { Connection connection = null; PreparedStatement prp = null; public newPatient() { initComponents(); ImageIcon ic = new ImageIcon(getClass().getResource("/Images/hospital.png")); this.setIconImage(ic.getImage()); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); pDateField = new javax.swing.JTextField(); pIdField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); pNameField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); pAgeField = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); pAddressField = new javax.swing.JTextField(); Gender = new javax.swing.JLabel(); pPhoneField = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); pDiseaseField = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); pRoomField = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); pGenderField = new javax.swing.JComboBox<>(); pStatusField = new javax.swing.JComboBox<>(); jPanel6 = new javax.swing.JPanel(); addDctorbtn = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); clearPbtn = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Add New Patient !"); jPanel1.setBackground(new java.awt.Color(204, 255, 204)); pDateField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pDateFieldActionPerformed(evt); } }); pIdField.setText("sjb0HMS"); pIdField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pIdFieldActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Id"); pNameField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pNameFieldActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Name"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText("Age"); pAgeField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pAgeFieldActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel5.setText("Gender"); pAddressField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pAddressFieldActionPerformed(evt); } }); Gender.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N Gender.setText("Address"); pPhoneField.setText("+880"); pPhoneField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pPhoneFieldActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel7.setText("Phone Number"); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel8.setText("Maritial Status"); pDiseaseField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pDiseaseFieldActionPerformed(evt); } }); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel9.setText("Disease Name"); pRoomField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pRoomFieldActionPerformed(evt); } }); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setText("Ward/Room no"); pGenderField.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Item", "Male", "Female" })); pGenderField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pGenderFieldActionPerformed(evt); } }); pStatusField.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Item", "Single", "Married", "Divorced" })); pStatusField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pStatusFieldActionPerformed(evt); } }); jPanel6.setBackground(new java.awt.Color(0, 0, 0)); jPanel6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jPanel6MouseClicked(evt); } }); addDctorbtn.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N addDctorbtn.setForeground(new java.awt.Color(255, 255, 255)); addDctorbtn.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); addDctorbtn.setText("Add"); addDctorbtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addDctorbtnMouseClicked(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addComponent(addDctorbtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(addDctorbtn)) ); jPanel7.setBackground(new java.awt.Color(0, 0, 0)); jPanel7.setPreferredSize(new java.awt.Dimension(100, 100)); jPanel7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jPanel7MouseClicked(evt); } }); jPanel7.setLayout(null); clearPbtn.setBackground(new java.awt.Color(0, 0, 0)); clearPbtn.setFont(new java.awt.Font("Arial", 0, 23)); // NOI18N clearPbtn.setForeground(new java.awt.Color(255, 255, 255)); clearPbtn.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); clearPbtn.setText("Clear"); clearPbtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { clearPbtnMouseClicked(evt); } }); jPanel7.add(clearPbtn); clearPbtn.setBounds(0, 0, 260, 30); jLabel6.setBackground(new java.awt.Color(102, 0, 102)); jLabel6.setFont(new java.awt.Font("BankGothic Md BT", 0, 35)); // NOI18N jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("ADD NEW PATIENT"); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel10.setText("Date"); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icon/backs.png"))); // NOI18N jLabel1.setText("jLabel1"); jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(94, 94, 94) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(pGenderField, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(pAgeField))) .addGap(40, 40, 40))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Gender, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pAddressField) .addComponent(pPhoneField) .addComponent(pStatusField, 0, 182, Short.MAX_VALUE) .addComponent(pDiseaseField) .addComponent(pRoomField)) .addGap(167, 167, 167)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(319, 319, 319) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 843, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Gender) .addComponent(pAddressField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(pIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(pPhoneField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(pNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8) .addComponent(pStatusField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel9) .addComponent(pDiseaseField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pAgeField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel13) .addComponent(pRoomField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pGenderField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 920, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void pDateFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pDateFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pDateFieldActionPerformed private void pIdFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pIdFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pIdFieldActionPerformed private void pNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pNameFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pNameFieldActionPerformed private void pAgeFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pAgeFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pAgeFieldActionPerformed private void pAddressFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pAddressFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pAddressFieldActionPerformed private void pPhoneFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pPhoneFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pPhoneFieldActionPerformed private void pDiseaseFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pDiseaseFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pDiseaseFieldActionPerformed private void pRoomFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pRoomFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pRoomFieldActionPerformed private void pGenderFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pGenderFieldActionPerformed }//GEN-LAST:event_pGenderFieldActionPerformed private void pStatusFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pStatusFieldActionPerformed }//GEN-LAST:event_pStatusFieldActionPerformed private void addDctorbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addDctorbtnMouseClicked connection = Connector.ConnectDb(); if (connection != null) { String date = pDateField.getText(); String id = pIdField.getText(); String name = pNameField.getText(); int age = Integer.parseInt(pAgeField.getText()); String gender = (String) pGenderField.getSelectedItem(); String address = pAddressField.getText(); String phone = pPhoneField.getText(); String status = (String) pStatusField.getSelectedItem(); String disease = pDiseaseField.getText(); int room = Integer.parseInt(pRoomField.getText()); String sql = "insert into patient(date,id,name,age,gender,address,phone,status,disease,room) values (?,?,?,?,?,?,?,?,?,?)"; try { prp = connection.prepareStatement(sql); prp.setString(1, date); prp.setString(2, id); prp.setString(3, name); prp.setInt(4, age); prp.setString(5, gender); prp.setString(6, address); prp.setString(7, phone); prp.setString(8, status); prp.setString(9, disease); prp.setInt(10, room); prp.execute(); JOptionPane.showMessageDialog(null, "Data Saved"); } catch (SQLException e) { } } }//GEN-LAST:event_addDctorbtnMouseClicked private void clearPbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearPbtnMouseClicked pDateField.setText(""); pNameField.setText(""); pAgeField.setText(""); pAddressField.setText(""); pPhoneField.setText(""); pDiseaseField.setText(""); pRoomField.setText(""); pIdField.setText("sjb0HMS"); pGenderField.setSelectedIndex(0); pStatusField.setSelectedIndex(0); }//GEN-LAST:event_clearPbtnMouseClicked private void jPanel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel7MouseClicked pDateField.setText(""); pNameField.setText(""); pAgeField.setText(""); pIdField.setText("sjb0HMS"); pAddressField.setText(""); pPhoneField.setText(""); pDiseaseField.setText(""); pRoomField.setText(""); pGenderField.setSelectedIndex(0); pStatusField.setSelectedIndex(0); }//GEN-LAST:event_jPanel7MouseClicked private void jPanel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel6MouseClicked }//GEN-LAST:event_jPanel6MouseClicked private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked ReceptionistActivity ra = new ReceptionistActivity(); ra.setVisible(true); dispose(); }//GEN-LAST:event_jLabel1MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(() -> { new newPatient().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Gender; private javax.swing.JLabel addDctorbtn; private javax.swing.JLabel clearPbtn; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JTextField pAddressField; private javax.swing.JTextField pAgeField; private javax.swing.JTextField pDateField; private javax.swing.JTextField pDiseaseField; private javax.swing.JComboBox<String> pGenderField; private javax.swing.JTextField pIdField; private javax.swing.JTextField pNameField; private javax.swing.JTextField pPhoneField; private javax.swing.JTextField pRoomField; private javax.swing.JComboBox<String> pStatusField; // End of variables declaration//GEN-END:variables }
UTF-8
Java
25,868
java
newPatient.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author Sajeeb\n */\npublic class newPatient extends javax.sw", "end": 244, "score": 0.691421389579773, "start": 243, "tag": "NAME", "value": "S" }, { "context": "port javax.swing.JOptionPane;\n\n/**\n *\n * @author Sajeeb\n */\npublic class newPatient extends javax.swing.J", "end": 249, "score": 0.7416712045669556, "start": 244, "tag": "USERNAME", "value": "ajeeb" } ]
null
[]
package Receptionists; import Main.Hospital; import Main.Connector; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author Sajeeb */ public class newPatient extends javax.swing.JFrame { Connection connection = null; PreparedStatement prp = null; public newPatient() { initComponents(); ImageIcon ic = new ImageIcon(getClass().getResource("/Images/hospital.png")); this.setIconImage(ic.getImage()); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); pDateField = new javax.swing.JTextField(); pIdField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); pNameField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); pAgeField = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); pAddressField = new javax.swing.JTextField(); Gender = new javax.swing.JLabel(); pPhoneField = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); pDiseaseField = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); pRoomField = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); pGenderField = new javax.swing.JComboBox<>(); pStatusField = new javax.swing.JComboBox<>(); jPanel6 = new javax.swing.JPanel(); addDctorbtn = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); clearPbtn = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Add New Patient !"); jPanel1.setBackground(new java.awt.Color(204, 255, 204)); pDateField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pDateFieldActionPerformed(evt); } }); pIdField.setText("sjb0HMS"); pIdField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pIdFieldActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel2.setText("Id"); pNameField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pNameFieldActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Name"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText("Age"); pAgeField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pAgeFieldActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel5.setText("Gender"); pAddressField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pAddressFieldActionPerformed(evt); } }); Gender.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N Gender.setText("Address"); pPhoneField.setText("+880"); pPhoneField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pPhoneFieldActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel7.setText("Phone Number"); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel8.setText("Maritial Status"); pDiseaseField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pDiseaseFieldActionPerformed(evt); } }); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel9.setText("Disease Name"); pRoomField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pRoomFieldActionPerformed(evt); } }); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel13.setText("Ward/Room no"); pGenderField.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Item", "Male", "Female" })); pGenderField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pGenderFieldActionPerformed(evt); } }); pStatusField.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Item", "Single", "Married", "Divorced" })); pStatusField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pStatusFieldActionPerformed(evt); } }); jPanel6.setBackground(new java.awt.Color(0, 0, 0)); jPanel6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jPanel6MouseClicked(evt); } }); addDctorbtn.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N addDctorbtn.setForeground(new java.awt.Color(255, 255, 255)); addDctorbtn.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); addDctorbtn.setText("Add"); addDctorbtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addDctorbtnMouseClicked(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addComponent(addDctorbtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(addDctorbtn)) ); jPanel7.setBackground(new java.awt.Color(0, 0, 0)); jPanel7.setPreferredSize(new java.awt.Dimension(100, 100)); jPanel7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jPanel7MouseClicked(evt); } }); jPanel7.setLayout(null); clearPbtn.setBackground(new java.awt.Color(0, 0, 0)); clearPbtn.setFont(new java.awt.Font("Arial", 0, 23)); // NOI18N clearPbtn.setForeground(new java.awt.Color(255, 255, 255)); clearPbtn.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); clearPbtn.setText("Clear"); clearPbtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { clearPbtnMouseClicked(evt); } }); jPanel7.add(clearPbtn); clearPbtn.setBounds(0, 0, 260, 30); jLabel6.setBackground(new java.awt.Color(102, 0, 102)); jLabel6.setFont(new java.awt.Font("BankGothic Md BT", 0, 35)); // NOI18N jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("ADD NEW PATIENT"); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel10.setText("Date"); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icon/backs.png"))); // NOI18N jLabel1.setText("jLabel1"); jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(94, 94, 94) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(pGenderField, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(pAgeField))) .addGap(40, 40, 40))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Gender, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pAddressField) .addComponent(pPhoneField) .addComponent(pStatusField, 0, 182, Short.MAX_VALUE) .addComponent(pDiseaseField) .addComponent(pRoomField)) .addGap(167, 167, 167)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(319, 319, 319) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 843, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pDateField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Gender) .addComponent(pAddressField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(pIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(pPhoneField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(pNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8) .addComponent(pStatusField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel9) .addComponent(pDiseaseField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pAgeField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel13) .addComponent(pRoomField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pGenderField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 920, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void pDateFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pDateFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pDateFieldActionPerformed private void pIdFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pIdFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pIdFieldActionPerformed private void pNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pNameFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pNameFieldActionPerformed private void pAgeFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pAgeFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pAgeFieldActionPerformed private void pAddressFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pAddressFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pAddressFieldActionPerformed private void pPhoneFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pPhoneFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pPhoneFieldActionPerformed private void pDiseaseFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pDiseaseFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pDiseaseFieldActionPerformed private void pRoomFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pRoomFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pRoomFieldActionPerformed private void pGenderFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pGenderFieldActionPerformed }//GEN-LAST:event_pGenderFieldActionPerformed private void pStatusFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pStatusFieldActionPerformed }//GEN-LAST:event_pStatusFieldActionPerformed private void addDctorbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addDctorbtnMouseClicked connection = Connector.ConnectDb(); if (connection != null) { String date = pDateField.getText(); String id = pIdField.getText(); String name = pNameField.getText(); int age = Integer.parseInt(pAgeField.getText()); String gender = (String) pGenderField.getSelectedItem(); String address = pAddressField.getText(); String phone = pPhoneField.getText(); String status = (String) pStatusField.getSelectedItem(); String disease = pDiseaseField.getText(); int room = Integer.parseInt(pRoomField.getText()); String sql = "insert into patient(date,id,name,age,gender,address,phone,status,disease,room) values (?,?,?,?,?,?,?,?,?,?)"; try { prp = connection.prepareStatement(sql); prp.setString(1, date); prp.setString(2, id); prp.setString(3, name); prp.setInt(4, age); prp.setString(5, gender); prp.setString(6, address); prp.setString(7, phone); prp.setString(8, status); prp.setString(9, disease); prp.setInt(10, room); prp.execute(); JOptionPane.showMessageDialog(null, "Data Saved"); } catch (SQLException e) { } } }//GEN-LAST:event_addDctorbtnMouseClicked private void clearPbtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearPbtnMouseClicked pDateField.setText(""); pNameField.setText(""); pAgeField.setText(""); pAddressField.setText(""); pPhoneField.setText(""); pDiseaseField.setText(""); pRoomField.setText(""); pIdField.setText("sjb0HMS"); pGenderField.setSelectedIndex(0); pStatusField.setSelectedIndex(0); }//GEN-LAST:event_clearPbtnMouseClicked private void jPanel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel7MouseClicked pDateField.setText(""); pNameField.setText(""); pAgeField.setText(""); pIdField.setText("sjb0HMS"); pAddressField.setText(""); pPhoneField.setText(""); pDiseaseField.setText(""); pRoomField.setText(""); pGenderField.setSelectedIndex(0); pStatusField.setSelectedIndex(0); }//GEN-LAST:event_jPanel7MouseClicked private void jPanel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel6MouseClicked }//GEN-LAST:event_jPanel6MouseClicked private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked ReceptionistActivity ra = new ReceptionistActivity(); ra.setVisible(true); dispose(); }//GEN-LAST:event_jLabel1MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(() -> { new newPatient().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Gender; private javax.swing.JLabel addDctorbtn; private javax.swing.JLabel clearPbtn; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JTextField pAddressField; private javax.swing.JTextField pAgeField; private javax.swing.JTextField pDateField; private javax.swing.JTextField pDiseaseField; private javax.swing.JComboBox<String> pGenderField; private javax.swing.JTextField pIdField; private javax.swing.JTextField pNameField; private javax.swing.JTextField pPhoneField; private javax.swing.JTextField pRoomField; private javax.swing.JComboBox<String> pStatusField; // End of variables declaration//GEN-END:variables }
25,868
0.653355
0.634954
492
51.577236
38.891659
180
false
false
0
0
0
0
0
0
0.900406
false
false
4
4dd4f6cd5d332b87e5f1b555b72bbdf62f088bc6
27,839,978,042,432
503ea1d0ae89b0d19f42aded72892da07a802cc3
/08 TuSDK/tusdkjar by bhavik/org-core/lasque/tusdk/core/http/StringEntity.java
7ab727d6e4b31ed8653ce0a11296a8ce7279d6d7
[]
no_license
amitkarn/VideoEditorDemos
https://github.com/amitkarn/VideoEditorDemos
acaff418cfe65badfcdb21e29d4a8d8edd9d69be
a4bf1835028c2ab1072ede44a2bd0c1a17f5ad23
refs/heads/master
2022-02-21T15:40:56.633000
2019-10-05T04:57:45
2019-10-05T04:57:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.lasque.tusdk.core.http; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import org.lasque.tusdk.core.utils.ReflectUtils; public class StringEntity extends AbstractHttpEntity implements Cloneable { public static final String TEXT_PLAIN = "text/plain"; protected final byte[] content; public StringEntity(String paramString1, String paramString2, String paramString3) { ReflectUtils.notNull(paramString1, "Source string"); String str1 = paramString2 != null ? paramString2 : "text/plain"; String str2 = paramString3 != null ? paramString3 : "UTF-8"; this.content = paramString1.getBytes(str2); setContentType(str1 + "; " + str2); } public StringEntity(String paramString1, String paramString2) { this(paramString1, null, paramString2); } public StringEntity(String paramString) { this(paramString, null); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.content.length; } public InputStream getContent() { return new ByteArrayInputStream(this.content); } public void writeTo(OutputStream paramOutputStream) { ReflectUtils.notNull(paramOutputStream, "Output stream"); paramOutputStream.write(this.content); paramOutputStream.flush(); } public boolean isStreaming() { return false; } public Object clone() { return super.clone(); } } /* Location: C:\Users\OM\Desktop\tusdkjar\TuSDKCore-3.1.0.jar!\org\lasque\tusdk\core\http\StringEntity.class * Java compiler version: 7 (51.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
1,678
java
StringEntity.java
Java
[]
null
[]
package org.lasque.tusdk.core.http; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import org.lasque.tusdk.core.utils.ReflectUtils; public class StringEntity extends AbstractHttpEntity implements Cloneable { public static final String TEXT_PLAIN = "text/plain"; protected final byte[] content; public StringEntity(String paramString1, String paramString2, String paramString3) { ReflectUtils.notNull(paramString1, "Source string"); String str1 = paramString2 != null ? paramString2 : "text/plain"; String str2 = paramString3 != null ? paramString3 : "UTF-8"; this.content = paramString1.getBytes(str2); setContentType(str1 + "; " + str2); } public StringEntity(String paramString1, String paramString2) { this(paramString1, null, paramString2); } public StringEntity(String paramString) { this(paramString, null); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.content.length; } public InputStream getContent() { return new ByteArrayInputStream(this.content); } public void writeTo(OutputStream paramOutputStream) { ReflectUtils.notNull(paramOutputStream, "Output stream"); paramOutputStream.write(this.content); paramOutputStream.flush(); } public boolean isStreaming() { return false; } public Object clone() { return super.clone(); } } /* Location: C:\Users\OM\Desktop\tusdkjar\TuSDKCore-3.1.0.jar!\org\lasque\tusdk\core\http\StringEntity.class * Java compiler version: 7 (51.0) * JD-Core Version: 0.7.1 */
1,678
0.700238
0.682956
71
22.647888
24.403936
121
false
false
0
0
0
0
0
0
0.43662
false
false
4
45b035a7764998cf73b023fbbc7a1cdce78292f9
26,328,149,573,659
883eda1bfd6044e5928099efe480a65ddb18db30
/src/evolutionaryAlgorithm/reproduction/ReproductionFactory.java
6f20bec508873b9c1eb6d6c2ce8dd44745afe2e6
[]
no_license
baryz/EvolutionaryAlgorithms
https://github.com/baryz/EvolutionaryAlgorithms
6089040e84b3f4f77127efcd6428c40ee1ac04a1
fa0881b12ad7264ddae3a5a7376c9d1298b68c36
refs/heads/master
2021-01-19T13:41:57.039000
2015-10-26T10:15:26
2015-10-26T10:15:26
82,410,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package evolutionaryAlgorithm.reproduction; public class ReproductionFactory implements IReproductionFactory { @Override public Reproduction produceReproduction(ReproductionType type, int... quantityTournament){ Reproduction resultReproduction=null; switch(type){ case RANK:{ resultReproduction=new RankReproduction(); break; } case TOURNAMENT:{ resultReproduction = new TournamentReproduction(quantityTournament); break; } case ROULLETEWHEEL:{ resultReproduction = new RoulleteWheelReproduction(); break; } } return resultReproduction; } }
UTF-8
Java
604
java
ReproductionFactory.java
Java
[]
null
[]
package evolutionaryAlgorithm.reproduction; public class ReproductionFactory implements IReproductionFactory { @Override public Reproduction produceReproduction(ReproductionType type, int... quantityTournament){ Reproduction resultReproduction=null; switch(type){ case RANK:{ resultReproduction=new RankReproduction(); break; } case TOURNAMENT:{ resultReproduction = new TournamentReproduction(quantityTournament); break; } case ROULLETEWHEEL:{ resultReproduction = new RoulleteWheelReproduction(); break; } } return resultReproduction; } }
604
0.748344
0.748344
28
20.571428
24.864531
91
false
false
0
0
0
0
0
0
2.392857
false
false
4
33ff53204af17469f38966d50690d5aaa38c888b
14,671,608,345,936
bd825faab5e2dd568ed138b531833c6fc0fec5e6
/app/src/main/java/fr/bowserf/testsoundsystem/spectrum/SpectrumRenderer.java
f003c1bfb8389b640ac5384dabf8b681c09b2f36
[]
no_license
bowserf/Mini-sound-system
https://github.com/bowserf/Mini-sound-system
8a0fa79218fde9b8088f3a904c3a3d8836e4bf43
f38b3d3439ead64d40763ae052d6c38ea2dc9c1c
refs/heads/master
2021-01-11T02:49:07.804000
2017-06-02T09:33:45
2017-06-02T09:33:45
70,921,233
9
1
null
false
2017-06-16T15:53:27
2016-10-14T15:08:53
2017-04-11T13:06:20
2017-06-16T15:53:27
1,152
2
0
0
C++
null
null
package fr.bowserf.testsoundsystem.spectrum; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /* package */ class SpectrumRenderer implements GLSurfaceView.Renderer { @SuppressWarnings("unused") private static final String TAG = "SpectrumRenderer"; private Line mLine; @Override public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); mLine = new Line(); } @Override public void onSurfaceChanged(GL10 gl10, int width, int height) { GLES20.glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 gl10) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); mLine.draw(); } /* package */ void drawData(short[] data, int desiredNumberData){ mLine.drawData(data, desiredNumberData); } }
UTF-8
Java
980
java
SpectrumRenderer.java
Java
[]
null
[]
package fr.bowserf.testsoundsystem.spectrum; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /* package */ class SpectrumRenderer implements GLSurfaceView.Renderer { @SuppressWarnings("unused") private static final String TAG = "SpectrumRenderer"; private Line mLine; @Override public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); mLine = new Line(); } @Override public void onSurfaceChanged(GL10 gl10, int width, int height) { GLES20.glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 gl10) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); mLine.draw(); } /* package */ void drawData(short[] data, int desiredNumberData){ mLine.drawData(data, desiredNumberData); } }
980
0.686735
0.652041
41
22.902439
22.598083
68
false
false
0
0
0
0
0
0
0.585366
false
false
4
ece58b6d34d679519f59878cea236a4875019154
32,280,974,226,406
c17b5a6c8ef971db81bd254e5d0fe84d1b2fc154
/app/src/main/java/com/OpenSource/engine/utils/PowerManagerUtility.java
d6f4138d46b22d2b557a8b42af8c47e1177056fe
[]
no_license
paragsarkar/OpenSource
https://github.com/paragsarkar/OpenSource
d6cfb0ca66de3e0a36fd6ec87e106ac58f155d64
092bd25f1c09cf72a6e044f057013790d6c3889b
refs/heads/master
2021-01-11T15:10:15.313000
2017-01-29T05:35:47
2017-01-29T05:35:47
80,305,582
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.OpenSource.engine.utils; import android.os.PowerManager; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.SystemService; /** * Created by parag_sarkar on 27-01-2017. */ @EBean public class PowerManagerUtility { PowerManager.WakeLock wakeLock; @SystemService PowerManager powerManager; @AfterInject void afterInject() { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PowerManagerUtility"); wakeLock.setReferenceCounted(true); } public void acquirePartialWakeLock() { if (wakeLock.isHeld() == false) { wakeLock.acquire(); } } public void releasePartialWakeLock() { if (wakeLock.isHeld() == true) { wakeLock.release(); } } }
UTF-8
Java
877
java
PowerManagerUtility.java
Java
[ { "context": "ions.annotations.SystemService;\n\n/**\n * Created by parag_sarkar on 27-01-2017.\n */\n\n\n@EBean\npublic class PowerMan", "end": 263, "score": 0.9570443630218506, "start": 251, "tag": "USERNAME", "value": "parag_sarkar" } ]
null
[]
package com.OpenSource.engine.utils; import android.os.PowerManager; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.SystemService; /** * Created by parag_sarkar on 27-01-2017. */ @EBean public class PowerManagerUtility { PowerManager.WakeLock wakeLock; @SystemService PowerManager powerManager; @AfterInject void afterInject() { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PowerManagerUtility"); wakeLock.setReferenceCounted(true); } public void acquirePartialWakeLock() { if (wakeLock.isHeld() == false) { wakeLock.acquire(); } } public void releasePartialWakeLock() { if (wakeLock.isHeld() == true) { wakeLock.release(); } } }
877
0.684151
0.675029
39
21.487179
22.301973
99
false
false
0
0
0
0
0
0
0.307692
false
false
4
b3fa87040e95569fd0b63bd97028454bc21f4a23
32,280,974,225,349
04743df248a4e82b8aa3450fd77222b49290294a
/app/src/main/java/com/quark/model/Function.java
19f07d1e9b47f846b00b32847f3207429498fa53
[]
no_license
ptjob/GoldAssistant2
https://github.com/ptjob/GoldAssistant2
e4c660df76b7f4cb91551dcec7204c3a8968ed4a
30fd06fdc5c8acdeb9ba97fb9e8b976362a6a7aa
refs/heads/master
2020-05-20T11:16:04.368000
2015-08-24T11:52:32
2015-08-24T11:52:32
40,306,486
2
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.quark.model; import java.io.Serializable; public class Function implements Serializable { /** * @author 商家端---我 */ private static final long serialVersionUID = -719887608260606653L; private float money; private String name; private String avatar; private int status; private int company_status; private float point; private int followers; private int type; public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getCompany_status() { return company_status; } public void setCompany_status(int company_status) { this.company_status = company_status; } public float getPoint() { return point; } public void setPoint(float point) { this.point = point; } public int getFollowers() { return followers; } public void setFollowers(int followers) { this.followers = followers; } public int getType() { return type; } public void setType(int type) { this.type = type; } @Override public String toString() { return "Function [money=" + money + ", name=" + name + ", avatar=" + avatar + ", status=" + status + "]"; } }
UTF-8
Java
1,667
java
Function.java
Java
[]
null
[]
package com.quark.model; import java.io.Serializable; public class Function implements Serializable { /** * @author 商家端---我 */ private static final long serialVersionUID = -719887608260606653L; private float money; private String name; private String avatar; private int status; private int company_status; private float point; private int followers; private int type; public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getCompany_status() { return company_status; } public void setCompany_status(int company_status) { this.company_status = company_status; } public float getPoint() { return point; } public void setPoint(float point) { this.point = point; } public int getFollowers() { return followers; } public void setFollowers(int followers) { this.followers = followers; } public int getType() { return type; } public void setType(int type) { this.type = type; } @Override public String toString() { return "Function [money=" + money + ", name=" + name + ", avatar=" + avatar + ", status=" + status + "]"; } }
1,667
0.611212
0.600362
89
16.64045
16.483732
68
false
false
0
0
0
0
0
0
1
false
false
4
3b6b369f49570861fb00e927d4be3eacfe4e5285
16,647,293,250,970
2370b8432cde74cb1e639585cb7cf27e2ce7cc3d
/src/servicios/PedidoService.java
5e7616952248a3d036d40e8d27fa5f0ba40aada7
[]
no_license
MatiasHillar/TPDIED
https://github.com/MatiasHillar/TPDIED
41f539811341d858a63ee64b81742565114fb5cf
cc494196d6adb4bf5bae2976aa51094a4b320424
refs/heads/master
2022-11-30T13:09:50.649000
2020-08-11T02:49:35
2020-08-11T02:49:35
280,318,624
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package servicios; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; import dao.PedidoDao; import dao.PedidoDaoPostgreSQL; import dominio.*; import gui.util.*; public class PedidoService { private PedidoDao pedidoDao; private PlantaService plantaService; private CamionService camionService; private MapaService mapaService; // private StockService stockService; public PedidoService(){ pedidoDao = new PedidoDaoPostgreSQL(); plantaService = new PlantaService(); camionService = new CamionService(); mapaService = new MapaService(); } public Pedido crearPedido(Pedido p) { p.setEstado(Estado.CREADO); p.setFechaSolicitud(LocalDate.now()); return pedidoDao.saveOrUpdate(p); } public Pedido crearPedido(Pedido p, LocalDate fechaSolicitud) { p.setEstado(Estado.CREADO); p.setFechaSolicitud(fechaSolicitud); return pedidoDao.saveOrUpdate(p); } public Pedido entregarPedido(Pedido p) { p.setEstado(Estado.ENTREGADO); for(ItemPedido ipp: p.getListaItems()) { List<Stock> s = p.getPlantaDestino().getListaStock().stream().filter(ss-> ss.getInsumo().equals(ipp.getInsumo())).collect(Collectors.toList()); if(s.isEmpty()) p.getPlantaDestino().getListaStock().add(new Stock(ipp.getInsumo(), ipp.getCtidad(),ipp.getCtidad() , p.getPlantaDestino())); else s.get(0).setCtidad(s.get(0).getCtidad() + ipp.getCtidad()); } // p.getPlantaDestino().getListaStock().stream().filter(ss-> ss.getInsumo().equals(ipp.getInsumo())).forEach(ss-> ss.setCtidad(ss.getCtidad()-ipp.getCtidad())); return pedidoDao.saveOrUpdate(p); } public List<Pedido> buscarTodosCreados() { return pedidoDao.filtrarCreadas(); } public List<Pedido> buscarTodosProcesados() { return pedidoDao.filtrarProcesadas(); } public List<Planta> buscarPlantasParaPedido(Pedido p) { // List<Planta> resultado= plantaService.buscarPlantasParaPedido(p.getNroPedido()); List<Planta> resultado= pedidoDao.checkPlantas(p.getNroPedido()); if(resultado.isEmpty()) { p.setEstado(Estado.CANCELADO); pedidoDao.saveOrUpdate(p); } return resultado; } public void asignarCamion(Pedido p) throws NoHayCamionesException { PriorityQueue<Camion> pq = new PriorityQueue<Camion>((c1,c2)-> c1.getKmRecorridos().compareTo(c2.getKmRecorridos())); pq.addAll(this.camionService.buscarTodos()); if(pq.isEmpty()) throw new NoHayCamionesException(); Camion c = pq.poll(); p.setCamion(c); c.setKmRecorridos(c.getKmRecorridos() + mapaService.getKm(p.getRuta())); p.setCostoEnvio((c.getCostoKm()* mapaService.getKm(p.getRuta())) + (c.getCostoHora() * mapaService.getHs(p.getRuta())) ); p.setEstado(Estado.PROCESADO); pedidoDao.saveOrUpdate(p); Planta origen=p.getRuta().get(0).getPlantaOrigen(); for(ItemPedido ipp: p.getListaItems()) { origen.getListaStock().stream().filter(ss-> ss.getInsumo().equals(ipp.getInsumo())).forEach(ss-> ss.setCtidad(ss.getCtidad()-ipp.getCtidad())); } plantaService.crearPlanta(origen); } }
UTF-8
Java
3,007
java
PedidoService.java
Java
[]
null
[]
package servicios; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; import dao.PedidoDao; import dao.PedidoDaoPostgreSQL; import dominio.*; import gui.util.*; public class PedidoService { private PedidoDao pedidoDao; private PlantaService plantaService; private CamionService camionService; private MapaService mapaService; // private StockService stockService; public PedidoService(){ pedidoDao = new PedidoDaoPostgreSQL(); plantaService = new PlantaService(); camionService = new CamionService(); mapaService = new MapaService(); } public Pedido crearPedido(Pedido p) { p.setEstado(Estado.CREADO); p.setFechaSolicitud(LocalDate.now()); return pedidoDao.saveOrUpdate(p); } public Pedido crearPedido(Pedido p, LocalDate fechaSolicitud) { p.setEstado(Estado.CREADO); p.setFechaSolicitud(fechaSolicitud); return pedidoDao.saveOrUpdate(p); } public Pedido entregarPedido(Pedido p) { p.setEstado(Estado.ENTREGADO); for(ItemPedido ipp: p.getListaItems()) { List<Stock> s = p.getPlantaDestino().getListaStock().stream().filter(ss-> ss.getInsumo().equals(ipp.getInsumo())).collect(Collectors.toList()); if(s.isEmpty()) p.getPlantaDestino().getListaStock().add(new Stock(ipp.getInsumo(), ipp.getCtidad(),ipp.getCtidad() , p.getPlantaDestino())); else s.get(0).setCtidad(s.get(0).getCtidad() + ipp.getCtidad()); } // p.getPlantaDestino().getListaStock().stream().filter(ss-> ss.getInsumo().equals(ipp.getInsumo())).forEach(ss-> ss.setCtidad(ss.getCtidad()-ipp.getCtidad())); return pedidoDao.saveOrUpdate(p); } public List<Pedido> buscarTodosCreados() { return pedidoDao.filtrarCreadas(); } public List<Pedido> buscarTodosProcesados() { return pedidoDao.filtrarProcesadas(); } public List<Planta> buscarPlantasParaPedido(Pedido p) { // List<Planta> resultado= plantaService.buscarPlantasParaPedido(p.getNroPedido()); List<Planta> resultado= pedidoDao.checkPlantas(p.getNroPedido()); if(resultado.isEmpty()) { p.setEstado(Estado.CANCELADO); pedidoDao.saveOrUpdate(p); } return resultado; } public void asignarCamion(Pedido p) throws NoHayCamionesException { PriorityQueue<Camion> pq = new PriorityQueue<Camion>((c1,c2)-> c1.getKmRecorridos().compareTo(c2.getKmRecorridos())); pq.addAll(this.camionService.buscarTodos()); if(pq.isEmpty()) throw new NoHayCamionesException(); Camion c = pq.poll(); p.setCamion(c); c.setKmRecorridos(c.getKmRecorridos() + mapaService.getKm(p.getRuta())); p.setCostoEnvio((c.getCostoKm()* mapaService.getKm(p.getRuta())) + (c.getCostoHora() * mapaService.getHs(p.getRuta())) ); p.setEstado(Estado.PROCESADO); pedidoDao.saveOrUpdate(p); Planta origen=p.getRuta().get(0).getPlantaOrigen(); for(ItemPedido ipp: p.getListaItems()) { origen.getListaStock().stream().filter(ss-> ss.getInsumo().equals(ipp.getInsumo())).forEach(ss-> ss.setCtidad(ss.getCtidad()-ipp.getCtidad())); } plantaService.crearPlanta(origen); } }
3,007
0.736615
0.734287
87
33.563217
34.840424
161
false
false
0
0
0
0
0
0
2.08046
false
false
4
6616e5d3e245e5842fe80c89b3616e895970cea9
25,271,587,631,994
18c267316085f9f6df83e13ba50a0455e6386d45
/_51Park/src/main/java/com/uubee/prepay/model/PayInfo.java
bc661a14b569051dff6da8d2ccb7ca53355c2851
[]
no_license
Sunnyfor/51Park
https://github.com/Sunnyfor/51Park
e2fae32728bbca2f28c3f10b5d87365368794333
8c8a9cb31fcf8e53b06762b62b93006d4abcd533
refs/heads/master
2020-09-30T10:17:27.233000
2019-12-11T03:07:41
2019-12-11T03:07:41
227,263,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uubee.prepay.model; import com.uubee.prepay.model.BaseInfo; public class PayInfo extends BaseInfo { private String sign_type; private String sign; private String busi_partner; private String no_order; private String dt_order; private String money_order; private String notify_url; private String valid_order; public PayInfo() { } public String getSign_type() { return this.sign_type; } public void setSign_type(String sign_type) { this.sign_type = sign_type; } public String getSign() { return this.sign; } public void setSign(String sign) { this.sign = sign; } public String getBusi_partner() { return this.busi_partner; } public void setBusi_partner(String busi_partner) { this.busi_partner = busi_partner; } public String getNo_order() { return this.no_order; } public void setNo_order(String no_order) { this.no_order = no_order; } public String getDt_order() { return this.dt_order; } public void setDt_order(String dt_order) { this.dt_order = dt_order; } public String getMoney_order() { return this.money_order; } public void setMoney_order(String money_order) { this.money_order = money_order; } public String getNotify_url() { return this.notify_url; } public void setNotify_url(String notify_url) { this.notify_url = notify_url; } public String getValid_order() { return this.valid_order; } public void setValid_order(String valid_order) { this.valid_order = valid_order; } }
UTF-8
Java
1,712
java
PayInfo.java
Java
[]
null
[]
package com.uubee.prepay.model; import com.uubee.prepay.model.BaseInfo; public class PayInfo extends BaseInfo { private String sign_type; private String sign; private String busi_partner; private String no_order; private String dt_order; private String money_order; private String notify_url; private String valid_order; public PayInfo() { } public String getSign_type() { return this.sign_type; } public void setSign_type(String sign_type) { this.sign_type = sign_type; } public String getSign() { return this.sign; } public void setSign(String sign) { this.sign = sign; } public String getBusi_partner() { return this.busi_partner; } public void setBusi_partner(String busi_partner) { this.busi_partner = busi_partner; } public String getNo_order() { return this.no_order; } public void setNo_order(String no_order) { this.no_order = no_order; } public String getDt_order() { return this.dt_order; } public void setDt_order(String dt_order) { this.dt_order = dt_order; } public String getMoney_order() { return this.money_order; } public void setMoney_order(String money_order) { this.money_order = money_order; } public String getNotify_url() { return this.notify_url; } public void setNotify_url(String notify_url) { this.notify_url = notify_url; } public String getValid_order() { return this.valid_order; } public void setValid_order(String valid_order) { this.valid_order = valid_order; } }
1,712
0.616238
0.616238
81
20.148148
17.374674
54
false
false
0
0
0
0
0
0
0.320988
false
false
4
08aa4fee7c5e2c31ee55970f52343be7947ab040
3,143,916,079,478
e6d111d14fe7bcf84fdf3eccffdc09639b7392c5
/src/com/ipso/jdbc/dao/IStudentDao.java
719d3d67ee85b1ed8b1987a5c4ab98bc6155ab72
[]
no_license
ipsozzZ/JDBC-DEMO
https://github.com/ipsozzZ/JDBC-DEMO
7d1dcd971ebbcae560fe0bf3768516a0793a605f
d41acf947f086f44988f62307268dee02acf4784
refs/heads/master
2020-07-09T09:12:09.911000
2019-08-31T05:35:06
2019-08-31T05:35:06
203,936,963
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ipso.jdbc.dao; import com.ipso.jdbc.domain.Student; import java.util.List; public interface IStudentDao { void save(Student stu); void update(int id, Student stu); Boolean delete(int id); Student getOne(int id); List<Student> getAll(); }
UTF-8
Java
268
java
IStudentDao.java
Java
[]
null
[]
package com.ipso.jdbc.dao; import com.ipso.jdbc.domain.Student; import java.util.List; public interface IStudentDao { void save(Student stu); void update(int id, Student stu); Boolean delete(int id); Student getOne(int id); List<Student> getAll(); }
268
0.712687
0.712687
13
19.615385
13.45956
36
false
false
0
0
0
0
0
0
0.692308
false
false
4
6c48dd592234c73caf72c8df84c31f4acb833be7
21,904,333,264,014
de4eefb1db199acce83bee0df89c53d1cf66a90a
/src/edu/hm/frank/arch/subsumption_architecture/behavior/TickBehavior.java
fcb7c4e8855f27716a2aca155db888456705000c
[]
no_license
FlorianFrank/SubsumptionArchitektur
https://github.com/FlorianFrank/SubsumptionArchitektur
d7d40b9dec400282e121168bd8bc0bf97c00992c
4b0f589a008f982b08973c44347dc17aba3f630c
refs/heads/master
2020-02-29T23:26:22.265000
2016-06-19T18:02:31
2016-06-19T18:02:31
61,046,416
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.hm.frank.arch.subsumption_architecture.behavior; import edu.hm.frank.arch.subsumption_architecture.arbitrator.Arbitrator; import edu.hm.frank.arch.subsumption_architecture.arbitrator.Wish; /** * Objekte der Klasse Tick zählen die Anzahl gleicher nacheinander folgender gleicher Events. * Werden 5 gleiche Events gezählt, so wird dem Arbitrator das Event Beep übergeben. */ class TickBehavior extends Behavior { /** * Nummer der gleichen nacheinanderfolgenden Events nach denen der Arbitrator benachrichtigt wird. */ private static final int NR_EVENTS = 5; /** * Zählt die Anzahl gleicher Events nacheinander. */ private int eventCounter; /** * Konstruktor setzt den Rang und den Arbitrator des Objekts. * * @param arbitrator mit Objekt verknpüfter Arbitrator * @param rank priorität des erzeugten Objektes. */ TickBehavior(Arbitrator arbitrator, int rank) { super(arbitrator, rank); eventCounter = 0; } @Override public synchronized void acceptReading(Reading event) { setCurrentReading(event); notifyAll(); } @Override public synchronized Reading getEvent() { try { while (getCurrentReading() != Reading.C) wait(); } catch (InterruptedException ignored) { interrupt(); } return getCurrentReading(); } @Override public void run() { while (!isInterrupted()) { final Reading event = getEvent(); if (event == Reading.C) { eventCounter++; setCurrentReading(null); } if (eventCounter == NR_EVENTS) { eventCounter = 0; sendWish(Wish.Beep); sendWish(Wish.Nop); } } } }
UTF-8
Java
1,866
java
TickBehavior.java
Java
[]
null
[]
package edu.hm.frank.arch.subsumption_architecture.behavior; import edu.hm.frank.arch.subsumption_architecture.arbitrator.Arbitrator; import edu.hm.frank.arch.subsumption_architecture.arbitrator.Wish; /** * Objekte der Klasse Tick zählen die Anzahl gleicher nacheinander folgender gleicher Events. * Werden 5 gleiche Events gezählt, so wird dem Arbitrator das Event Beep übergeben. */ class TickBehavior extends Behavior { /** * Nummer der gleichen nacheinanderfolgenden Events nach denen der Arbitrator benachrichtigt wird. */ private static final int NR_EVENTS = 5; /** * Zählt die Anzahl gleicher Events nacheinander. */ private int eventCounter; /** * Konstruktor setzt den Rang und den Arbitrator des Objekts. * * @param arbitrator mit Objekt verknpüfter Arbitrator * @param rank priorität des erzeugten Objektes. */ TickBehavior(Arbitrator arbitrator, int rank) { super(arbitrator, rank); eventCounter = 0; } @Override public synchronized void acceptReading(Reading event) { setCurrentReading(event); notifyAll(); } @Override public synchronized Reading getEvent() { try { while (getCurrentReading() != Reading.C) wait(); } catch (InterruptedException ignored) { interrupt(); } return getCurrentReading(); } @Override public void run() { while (!isInterrupted()) { final Reading event = getEvent(); if (event == Reading.C) { eventCounter++; setCurrentReading(null); } if (eventCounter == NR_EVENTS) { eventCounter = 0; sendWish(Wish.Beep); sendWish(Wish.Nop); } } } }
1,866
0.609677
0.607527
65
27.615385
25.055441
102
false
false
0
0
0
0
0
0
0.323077
false
false
4
64bb7d95df8eba60f6b2adb5ec22a941ffbfb11b
27,839,978,052,172
35f5c65cf7e670e6e10538633e9ac89c982f2e8a
/bookstore/app/models/Book.java
9ad457b214d92a988b6e614809c0df7a69da552a
[]
no_license
budiyona/PBO2018
https://github.com/budiyona/PBO2018
107a0bd19be54810e5c2f3123ce795010c5204d8
7301d9ec937a71eb7b98d5ca205f27661245af22
refs/heads/master
2020-03-07T20:01:50.803000
2018-04-26T14:17:43
2018-04-26T14:17:43
127,686,300
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; import java.util.*; import javax.persistence.*; import play.db.ebean.Model; import play.db.ebean.*; @Entity public class Book extends Model { @Id public Integer id; public Integer price; public String title; public String author; public static Finder<Integer, Book> find = new Finder<Integer, Book>(Integer.class,Book.class); }
UTF-8
Java
360
java
Book.java
Java
[]
null
[]
package models; import java.util.*; import javax.persistence.*; import play.db.ebean.Model; import play.db.ebean.*; @Entity public class Book extends Model { @Id public Integer id; public Integer price; public String title; public String author; public static Finder<Integer, Book> find = new Finder<Integer, Book>(Integer.class,Book.class); }
360
0.736111
0.736111
21
16.047619
21.052036
96
false
false
0
0
0
0
0
0
0.952381
false
false
4
d6a5bb52f56277f6b438e7bced8bb928d4a73b53
13,108,240,209,289
86b824cd9ec696f38bacc71fd6d7e32341fffa4c
/DummyLanguage-master/src/test/java/semantic/MainAppTests.java
ce0d3a90a26c2413e51f621df8587c87b4b9ba6c
[]
no_license
Krystian95/Progetto-Compilatori-e-Interpreti
https://github.com/Krystian95/Progetto-Compilatori-e-Interpreti
1b00e2157a2e252e32509bcb8bce7dd39163d22e
c7b20cd7e379c087e8ac32ab826e825a4363bb7b
refs/heads/master
2022-04-04T10:15:45.516000
2020-02-20T16:22:53
2020-02-20T16:22:53
196,425,288
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package semantic; import models.compiler.*; import models.compiler.statements.StmtBlock; import models.compiler.VisitorImpl; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import parser.ComplexStaticAnalysisLexer; import parser.ComplexStaticAnalysisParser; import util.SemanticError; import util.Strings; import util.TypeCheckException; import java.io.IOException; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class MainAppTests { private final String baseTestsRoot = "src/test/samples/"; private StmtBlock getAST(String fileName){ try { CharStream is = CharStreams.fromFileName(fileName); ComplexStaticAnalysisLexer lexer = new ComplexStaticAnalysisLexer(is); CommonTokenStream tokens = new CommonTokenStream(lexer); ComplexStaticAnalysisParser parser = new ComplexStaticAnalysisParser(tokens); VisitorImpl visitor = new VisitorImpl(); return visitor.visitBlock(parser.block()); } catch (IOException e) { e.printStackTrace(); } return null; } @Test void example_1() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_1.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(2, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "z", errors.get(1).toString()); } @Test void example_2() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_2.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "z", errors.get(0).toString()); } @Test void example_3() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_3.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_FUNCTION_HAS_BEEN_DELETED + "f", errors.get(0).toString()); } @Test void example_4() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_4.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_FUNCTION_HAS_BEEN_DELETED + "f", errors.get(0).toString()); } @Test void example_5() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_5.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_6() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_6.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_7() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_7.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_8() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_8.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_9() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_9.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_10() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_10.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_11() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_11.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_12() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_12.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "z", errors.get(0).toString()); } @Test void example_13() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_13.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(2, errors.size()); assertEquals(Strings.ERROR_GLOBAL_VAR_AS_PARAMETER + "x", errors.get(0).toString()); assertEquals(Strings.ERROR_DANGEROUS_USE_OF_PARAMETER + "x", errors.get(1).toString()); } @Test void example_14() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_14.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_15() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_15.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_16() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_16.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_17() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_17.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_ALREADY_DECLARED_IDENTIFIER + "f", errors.get(0).toString()); } @Test void example_18() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_18.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_IDENTIFIER_DOESNT_EXIST + "g", errors.get(0).toString()); } @Test void example_19() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_19.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Bool, got Int", exception.getMessage()); } @Test void example_20() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_20.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Int, got Bool", exception.getMessage()); } @Test void example_21() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_21.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Int, got Bool", exception.getMessage()); } @Test void example_22() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_22.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Bool, got Int", exception.getMessage()); } @Test void example_23() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_23.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_24() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_24.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_25() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_25.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_26() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_26.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_27() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_27.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType: var Int, got: right term Int", exception.getMessage()); } @Test void example_28() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_28.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_29() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_29.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void code_generation_1() { StmtBlock mainBlock = getAST(baseTestsRoot + "code_generation_1.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void code_generation_2() { StmtBlock mainBlock = getAST(baseTestsRoot + "code_generation_2.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void code_generation_3() { StmtBlock mainBlock = getAST(baseTestsRoot + "code_generation_3.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } }
UTF-8
Java
14,370
java
MainAppTests.java
Java
[]
null
[]
package semantic; import models.compiler.*; import models.compiler.statements.StmtBlock; import models.compiler.VisitorImpl; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import parser.ComplexStaticAnalysisLexer; import parser.ComplexStaticAnalysisParser; import util.SemanticError; import util.Strings; import util.TypeCheckException; import java.io.IOException; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class MainAppTests { private final String baseTestsRoot = "src/test/samples/"; private StmtBlock getAST(String fileName){ try { CharStream is = CharStreams.fromFileName(fileName); ComplexStaticAnalysisLexer lexer = new ComplexStaticAnalysisLexer(is); CommonTokenStream tokens = new CommonTokenStream(lexer); ComplexStaticAnalysisParser parser = new ComplexStaticAnalysisParser(tokens); VisitorImpl visitor = new VisitorImpl(); return visitor.visitBlock(parser.block()); } catch (IOException e) { e.printStackTrace(); } return null; } @Test void example_1() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_1.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(2, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "z", errors.get(1).toString()); } @Test void example_2() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_2.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "z", errors.get(0).toString()); } @Test void example_3() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_3.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_FUNCTION_HAS_BEEN_DELETED + "f", errors.get(0).toString()); } @Test void example_4() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_4.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_FUNCTION_HAS_BEEN_DELETED + "f", errors.get(0).toString()); } @Test void example_5() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_5.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_6() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_6.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_7() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_7.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_8() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_8.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_9() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_9.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_10() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_10.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_11() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_11.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_12() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_12.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "z", errors.get(0).toString()); } @Test void example_13() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_13.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(2, errors.size()); assertEquals(Strings.ERROR_GLOBAL_VAR_AS_PARAMETER + "x", errors.get(0).toString()); assertEquals(Strings.ERROR_DANGEROUS_USE_OF_PARAMETER + "x", errors.get(1).toString()); } @Test void example_14() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_14.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_15() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_15.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_16() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_16.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_17() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_17.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_ALREADY_DECLARED_IDENTIFIER + "f", errors.get(0).toString()); } @Test void example_18() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_18.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_IDENTIFIER_DOESNT_EXIST + "g", errors.get(0).toString()); } @Test void example_19() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_19.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Bool, got Int", exception.getMessage()); } @Test void example_20() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_20.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Int, got Bool", exception.getMessage()); } @Test void example_21() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_21.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Int, got Bool", exception.getMessage()); } @Test void example_22() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_22.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType Bool, got Int", exception.getMessage()); } @Test void example_23() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_23.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_24() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_24.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(1, errors.size()); assertEquals(Strings.ERROR_VARIABLE_HAS_BEEN_DELETED + "x", errors.get(0).toString()); } @Test void example_25() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_25.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals(Strings.ERROR_BEHAVIOR_MISMATCH, exception.getMessage()); } @Test void example_26() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_26.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_27() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_27.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); Throwable exception = assertThrows(TypeCheckException.class, mainBlock::typeCheck); assertEquals("ExpectedType: var Int, got: right term Int", exception.getMessage()); } @Test void example_28() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_28.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void example_29() { StmtBlock mainBlock = getAST(baseTestsRoot + "EXAMPLE_29.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void code_generation_1() { StmtBlock mainBlock = getAST(baseTestsRoot + "code_generation_1.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void code_generation_2() { StmtBlock mainBlock = getAST(baseTestsRoot + "code_generation_2.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } @Test void code_generation_3() { StmtBlock mainBlock = getAST(baseTestsRoot + "code_generation_3.spl"); Environment e = new Environment(); assertNotNull(mainBlock); List<SemanticError> errors = mainBlock.checkSemantics(e); assertEquals(0, errors.size()); assertDoesNotThrow((Executable) mainBlock::typeCheck); } }
14,370
0.655115
0.644468
377
37.119362
28.181847
96
false
false
0
0
0
0
0
0
0.790451
false
false
4
2fe952e7d3390362e65e209cbc2342a30eeb23e1
13,417,477,886,751
ecb5a4bedd50b52086edbd151c2c6fcdf6536fde
/src/main/java/edu/cibertec/capitulo3/dao/UsuarioDAO.java
dfd84eaf70c17fb14e7e7185edcac56ed10ded79
[]
no_license
UserPabloJuarez/SpringMVC
https://github.com/UserPabloJuarez/SpringMVC
34764a1b4018ece3dfdd190a2626ce4ad3d90805
09aee7f419825a211b02123f8dabcd756ecb79b2
refs/heads/master
2023-02-06T04:49:50.083000
2021-01-02T15:46:35
2021-01-02T15:46:35
326,214,773
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.cibertec.capitulo3.dao; import edu.cibertec.capitulo3.entity.UsuarioEntity; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class UsuarioDAO { private static List<UsuarioEntity> listaUsuarios; static { listaUsuarios = new ArrayList<>(); listaUsuarios.add(new UsuarioEntity("jose", "12345", "Jose Perez")); listaUsuarios.add(new UsuarioEntity("maria", "54321", "maria Gonzales")); } public void insertaUsuario(UsuarioEntity ue) { listaUsuarios.add(ue); } public List<UsuarioEntity> getListaUsuarios(){ return listaUsuarios; } public UsuarioEntity validarLogin(UsuarioEntity usuario) { if (usuario.getUsuario().equalsIgnoreCase("user") && usuario.getClave().equals("12345")) usuario.setNombreCompleto("Nombre completo del usuario"); else usuario = null; return usuario; } }
UTF-8
Java
1,049
java
UsuarioDAO.java
Java
[ { "context": ">();\n listaUsuarios.add(new UsuarioEntity(\"jose\", \"12345\", \"Jose Perez\"));\n listaUsuarios.", "end": 394, "score": 0.99885094165802, "start": 390, "tag": "USERNAME", "value": "jose" }, { "context": "aUsuarios.add(new UsuarioEntity(\"jose\", \"12345\", \"Jose Perez\"));\n listaUsuarios.add(new UsuarioEntity(\"", "end": 417, "score": 0.9998792409896851, "start": 407, "tag": "NAME", "value": "Jose Perez" }, { "context": "\"));\n listaUsuarios.add(new UsuarioEntity(\"maria\", \"54321\", \"maria Gonzales\"));\n }\n \n pub", "end": 472, "score": 0.9901391267776489, "start": 467, "tag": "USERNAME", "value": "maria" }, { "context": "Usuarios.add(new UsuarioEntity(\"maria\", \"54321\", \"maria Gonzales\"));\n }\n \n public void insertaUsuario(Usu", "end": 499, "score": 0.9998666644096375, "start": 485, "tag": "NAME", "value": "maria Gonzales" }, { "context": " if (usuario.getUsuario().equalsIgnoreCase(\"user\") &&\n usuario.getClave().equals(\"1", "end": 830, "score": 0.8660578727722168, "start": 826, "tag": "USERNAME", "value": "user" } ]
null
[]
package edu.cibertec.capitulo3.dao; import edu.cibertec.capitulo3.entity.UsuarioEntity; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class UsuarioDAO { private static List<UsuarioEntity> listaUsuarios; static { listaUsuarios = new ArrayList<>(); listaUsuarios.add(new UsuarioEntity("jose", "12345", "<NAME>")); listaUsuarios.add(new UsuarioEntity("maria", "54321", "<NAME>")); } public void insertaUsuario(UsuarioEntity ue) { listaUsuarios.add(ue); } public List<UsuarioEntity> getListaUsuarios(){ return listaUsuarios; } public UsuarioEntity validarLogin(UsuarioEntity usuario) { if (usuario.getUsuario().equalsIgnoreCase("user") && usuario.getClave().equals("12345")) usuario.setNombreCompleto("Nombre completo del usuario"); else usuario = null; return usuario; } }
1,037
0.645377
0.629171
40
25.225
23.812273
81
false
false
0
0
0
0
0
0
0.45
false
false
4
e84ebb7a8267035e957278146ee811699c015a60
33,517,924,779,073
23392c55920e4d80e5b40bc5435f2e57d85fffa8
/try/src/main/java/com/service/GoService.java
9f755bd5f72a829dccd0033f6d3b71be7f884493
[]
no_license
KeepHorse/Super5-Statistics
https://github.com/KeepHorse/Super5-Statistics
9f68e6ebbf51b9523502570dcc3800d9d4671bb7
169dfb57855f91ac9736ad666d863a179b35a311
HEAD
2018-04-20T22:35:16.006000
2017-04-18T13:59:21
2017-04-18T13:59:21
90,881,147
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.service; public interface GoService { String gogogo(); }
UTF-8
Java
78
java
GoService.java
Java
[]
null
[]
package com.service; public interface GoService { String gogogo(); }
78
0.679487
0.679487
7
9.428572
11.03057
28
false
false
0
0
0
0
0
0
0.428571
false
false
4
71741d90d968dfcc87b375fe1283bceb91d73ee1
23,794,118,856,414
490ba979ecb23c2d37c29a77c6db2410a0441a29
/src/com/poo/practica8/figs_abstractas/Triangulo.java
8b100d586fb889a1f08b6bfb06631366593eeb37
[]
no_license
CiberSword/Figuras_geometricas
https://github.com/CiberSword/Figuras_geometricas
3600b5aa2d839f191f52329e4e0802392f68a71c
89a24363cc1ddcb692de75800f100f846d8c331c
refs/heads/master
2023-01-28T01:11:28.044000
2020-11-29T02:46:53
2020-11-29T02:46:53
316,720,030
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.poo.practica8.figs_abstractas; public abstract class Triangulo extends Poligono { private double alpha, beta, gamma; //Angulos en grados private double a, b, c; // Angulos en radianes private double ladoA, ladoB, ladoC; public double getAlpha() { return alpha; } public void setAlpha(double alpha) { this.alpha = alpha; } public double getBeta() { return beta; } public void setBeta(double beta) { this.beta = beta; } public double getGamma() { return gamma; } public void setGamma(double gamma) { this.gamma = gamma; } public double getLadoA() { return ladoA; } public void setLadoA(double ladoA) { this.ladoA = ladoA; } public double getLadoB() { return ladoB; } public void setLadoB(double ladoB) { this.ladoB = ladoB; } public double getLadoC() { return ladoC; } public void setLadoC(double ladoC) { this.ladoC = ladoC; } public String toString() { return "Triangulo"; } public double leySeno(double ladoA, double alpha, double beta) { return (Math.sin(beta) * ladoA) / Math.sin(alpha); } }
UTF-8
Java
1,263
java
Triangulo.java
Java
[]
null
[]
package com.poo.practica8.figs_abstractas; public abstract class Triangulo extends Poligono { private double alpha, beta, gamma; //Angulos en grados private double a, b, c; // Angulos en radianes private double ladoA, ladoB, ladoC; public double getAlpha() { return alpha; } public void setAlpha(double alpha) { this.alpha = alpha; } public double getBeta() { return beta; } public void setBeta(double beta) { this.beta = beta; } public double getGamma() { return gamma; } public void setGamma(double gamma) { this.gamma = gamma; } public double getLadoA() { return ladoA; } public void setLadoA(double ladoA) { this.ladoA = ladoA; } public double getLadoB() { return ladoB; } public void setLadoB(double ladoB) { this.ladoB = ladoB; } public double getLadoC() { return ladoC; } public void setLadoC(double ladoC) { this.ladoC = ladoC; } public String toString() { return "Triangulo"; } public double leySeno(double ladoA, double alpha, double beta) { return (Math.sin(beta) * ladoA) / Math.sin(alpha); } }
1,263
0.585907
0.585115
63
19.063492
18.278162
68
false
false
0
0
0
0
0
0
0.412698
false
false
4
298ca6748ac35435ec696371d52c3f853bf8de9a
29,386,166,241,415
d307249a77a3eee2fd983344897d74c77687c93a
/app/src/main/java/com/example/rent/Controller/login/LoginViewModel.java
d997ec36dd6005907d7377be8092ba232fc2f3fd
[]
no_license
belladwir/rental
https://github.com/belladwir/rental
4febe8e2eacfa1c7ea7299bb6d622c633b1818be
7f775a3ecfb6bc53668f474ab2471c02e38776a0
refs/heads/master
2020-09-07T00:01:01.117000
2019-11-23T08:02:19
2019-11-23T08:02:19
220,596,131
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.rent.Controller.login; import androidx.annotation.NonNull; import androidx.lifecycle.ViewModel; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class LoginViewModel extends ViewModel { LoginCallback loginCallback; public void setLoginCallback(LoginCallback loginCallback) { this.loginCallback = loginCallback; } public void signIn(final String email, String password) { FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { System.out.println("signInWithEmail:success"); loginCallback.onSucceed(FirebaseAuth.getInstance().getCurrentUser()); } else { loginCallback.onFailed(task.getException()); } } }); } }
UTF-8
Java
1,238
java
LoginViewModel.java
Java
[]
null
[]
package com.example.rent.Controller.login; import androidx.annotation.NonNull; import androidx.lifecycle.ViewModel; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class LoginViewModel extends ViewModel { LoginCallback loginCallback; public void setLoginCallback(LoginCallback loginCallback) { this.loginCallback = loginCallback; } public void signIn(final String email, String password) { FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { System.out.println("signInWithEmail:success"); loginCallback.onSucceed(FirebaseAuth.getInstance().getCurrentUser()); } else { loginCallback.onFailed(task.getException()); } } }); } }
1,238
0.62601
0.62601
34
35.411766
28.024273
97
false
false
0
0
0
0
0
0
0.441176
false
false
4
facd5ea097b1f96a3364dc6317058bca9ba4942f
29,386,166,245,227
64f21b39f6c425c6a3f08c54cf39a043e548cfb0
/CrackingCodingInt/src/arraysAndStrings/oneaway/OneAwayTest.java
a77b41411ea1dfea08a17f9064f818fad4f99efe
[]
no_license
Efitiii/CrackingCodingInt
https://github.com/Efitiii/CrackingCodingInt
ac5a096c09dd2ec79f1530a41037cb7f1e3f2f3c
fffdf64ec7f00640d940d286f814d8d360d05cf9
refs/heads/master
2020-03-20T23:20:43.554000
2019-03-25T21:18:48
2019-03-25T21:18:48
137,841,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package arraysAndStrings.oneaway; import org.testng.annotations.Test; import junit.framework.TestCase; public class OneAwayTest extends TestCase { @Test public void isOneAwayTest(){ OneAway oneA= new OneAway(); assertTrue(oneA.checkOneAway("pale", "bale")); } }
UTF-8
Java
275
java
OneAwayTest.java
Java
[]
null
[]
package arraysAndStrings.oneaway; import org.testng.annotations.Test; import junit.framework.TestCase; public class OneAwayTest extends TestCase { @Test public void isOneAwayTest(){ OneAway oneA= new OneAway(); assertTrue(oneA.checkOneAway("pale", "bale")); } }
275
0.752727
0.752727
15
17.333334
17.82757
48
false
false
0
0
0
0
0
0
0.933333
false
false
4
384b5a7e9ba0e3fb2b239f70999b2cd8fcb9d823
28,406,913,740,004
921b84350d78f96a856b542c2f20c4f07d4bdb3b
/autoWorld/app/src/main/java/com/amper88/autoworld/ui/cars/abw/CarListFragment.java
5e3cc974711ceb8daeea0e965a42a5f93e9ad112
[]
no_license
amper1988/autoWorld
https://github.com/amper1988/autoWorld
500c5c3f80d28c491654d204dd14903b6075cb63
9ddc3c349c963b771c86ff7a27d929481d08c7c9
refs/heads/master
2016-08-12T05:45:04.644000
2016-03-24T17:41:44
2016-03-24T17:41:44
53,955,994
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amper88.autoworld.ui.cars.abw; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.amper88.autoworld.R; import com.amper88.autoworld.data.model.OrderInfo; import com.amper88.autoworld.ui.cars.CarListAdapter; import com.amper88.autoworld.ui.cars.CarListView; import com.amper88.autoworld.ui.rx.RecyclerViewEndScrollEvent; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import rx.Subscriber; public class CarListFragment extends Fragment implements CarListView { @Bind(R.id.car_list) RecyclerView mCarList; private CarListPresenter mPresenter; private CarListAdapter mAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_car_list, container, false); ButterKnife.bind(this, view); mPresenter = new CarListPresenter(this); initViews(); return view; } private void initViews() { mAdapter = new CarListAdapter(); mCarList.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); mCarList.setLayoutManager(linearLayoutManager); mCarList.setAdapter(mAdapter); RecyclerViewEndScrollEvent.onScrollEnd(mCarList).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer pageId) { getNextPage(pageId); } }); } private void getNextPage(Integer pageId) { mPresenter.getNextPage(pageId); } @Override public void onStart() { super.onStart(); mPresenter.onStart(); } @Override public void showCars(List<OrderInfo> list) { mAdapter.add(list); } @Override public void showError() { Toast.makeText(getActivity(), "Smth. wrong", Toast.LENGTH_SHORT).show(); } @Override public void setProgress(boolean isProgress) { } }
UTF-8
Java
2,483
java
CarListFragment.java
Java
[ { "context": "up;\nimport android.widget.Toast;\n\nimport com.amper88.autoworld.R;\nimport com.amper88.autoworld.data.m", "end": 395, "score": 0.5301387906074524, "start": 394, "tag": "USERNAME", "value": "8" }, { "context": "\n\nimport com.amper88.autoworld.R;\nimport com.amper88.autoworld.data.model.OrderInfo;\nimport com.amper", "end": 427, "score": 0.5069040060043335, "start": 426, "tag": "USERNAME", "value": "8" } ]
null
[]
package com.amper88.autoworld.ui.cars.abw; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.amper88.autoworld.R; import com.amper88.autoworld.data.model.OrderInfo; import com.amper88.autoworld.ui.cars.CarListAdapter; import com.amper88.autoworld.ui.cars.CarListView; import com.amper88.autoworld.ui.rx.RecyclerViewEndScrollEvent; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import rx.Subscriber; public class CarListFragment extends Fragment implements CarListView { @Bind(R.id.car_list) RecyclerView mCarList; private CarListPresenter mPresenter; private CarListAdapter mAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_car_list, container, false); ButterKnife.bind(this, view); mPresenter = new CarListPresenter(this); initViews(); return view; } private void initViews() { mAdapter = new CarListAdapter(); mCarList.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); mCarList.setLayoutManager(linearLayoutManager); mCarList.setAdapter(mAdapter); RecyclerViewEndScrollEvent.onScrollEnd(mCarList).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer pageId) { getNextPage(pageId); } }); } private void getNextPage(Integer pageId) { mPresenter.getNextPage(pageId); } @Override public void onStart() { super.onStart(); mPresenter.onStart(); } @Override public void showCars(List<OrderInfo> list) { mAdapter.add(list); } @Override public void showError() { Toast.makeText(getActivity(), "Smth. wrong", Toast.LENGTH_SHORT).show(); } @Override public void setProgress(boolean isProgress) { } }
2,483
0.68828
0.682239
90
26.588888
23.661451
103
false
false
0
0
0
0
0
0
0.511111
false
false
4
e15f69c20dc8c0c78b5281116f45ad650f6e238d
6,055,903,922,329
f132d3d928da00d2907d3f61bde7033c6e196d3c
/revisao/Animal.java
539a73df2215cb68ae57935c50db6509b0e58949
[]
no_license
LeandroJOA/UNIDESC-POO
https://github.com/LeandroJOA/UNIDESC-POO
75ecd1b6a0ee4ef7f3565ca01f0dbc55b78a4028
fca29294cd262e1f78be5622ac163d6ec7c37ac3
refs/heads/master
2023-01-13T18:20:08.413000
2020-11-17T18:08:37
2020-11-17T18:08:37
297,534,859
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.edu.unidesc.exercicio.revisao; public class Animal { public String Teste; private String raca; private int idade; public String getRaca() { return raca; } public void setRaca(String raca) { this.raca = raca; } public int getIdade() { return idade; } public void setIdade(int idade) { this.idade = idade; } public void emitirSom() { System.out.println("Animal Emitindo som:"); } }
UTF-8
Java
491
java
Animal.java
Java
[]
null
[]
package br.edu.unidesc.exercicio.revisao; public class Animal { public String Teste; private String raca; private int idade; public String getRaca() { return raca; } public void setRaca(String raca) { this.raca = raca; } public int getIdade() { return idade; } public void setIdade(int idade) { this.idade = idade; } public void emitirSom() { System.out.println("Animal Emitindo som:"); } }
491
0.588595
0.588595
29
15.931034
15.021665
51
false
false
0
0
0
0
0
0
0.310345
false
false
4
3e5dfaf9841c08fd1fab035c0734340122ae6c82
6,055,903,919,405
c6f2562769e8eef6f774e5908816a183888d0633
/eclipse-workspace/eclipse-workspace/Pong/MainElements.java
3bc789a1b27d64079646beeeb315b2d70909447c
[]
no_license
khan101101/Repo3
https://github.com/khan101101/Repo3
504e6849d1f37d0457bf85c1d545b6238f8fbe42
9cf7f7c1969fbfcf0a58a13c6b8e94ab459adfe8
refs/heads/master
2022-07-17T08:13:31.898000
2020-05-22T14:08:21
2020-05-22T14:08:21
262,343,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.effect.Reflection; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class MainElements { StackPane stack = new StackPane(); static Button start = new Button("Start"); static Button statistics = new Button("Statistics"); static Button exit = new Button("Exit"); /** * * @return * @throws MalformedURLException */ public Scene insert() throws MalformedURLException{ VBox buttonPane = new VBox(); buttonPane.setSpacing(10); buttonPane.setPadding(new Insets(15,10, 15,10)); BorderPane titel = new BorderPane(); titel.setMinSize(1280, 300); BorderPane startButtonPane = new BorderPane(); BorderPane statisticsButtonPane = new BorderPane(); BorderPane exitButtonPane = new BorderPane(); File file = new File("pong2.jpg"); String localUrl = file.toURI().toURL().toString(); Image image = new Image(localUrl); ImageView imageView = new ImageView(image); Reflection reflection = new Reflection(); reflection.setBottomOpacity(0.0); reflection.setTopOpacity(0.5); reflection.setTopOffset(10); reflection.setFraction(0.7); Text text = new Text(); text.setX(20.0); text.setY(90.0); text.setCache(true); text.setText("Pong"); text.setFill(Color.web("0x99FF00")); text.setFont(Font.font(null, FontWeight.BOLD, 80)); text.setEffect(reflection); titel.setCenter(text); buttonPane.getChildren().addAll(titel); start.setPrefSize(500, 50); statistics.setPrefSize(500, 50); exit.setPrefSize(500, 50); startButtonPane.setCenter(start); statisticsButtonPane.setCenter(statistics); exitButtonPane.setCenter(exit); buttonPane.getChildren().add(startButtonPane); buttonPane.getChildren().add(statisticsButtonPane); buttonPane.getChildren().add(exitButtonPane); stack.getChildren().add(imageView); stack.getChildren().add(buttonPane); Scene scene = new Scene(stack,1280,720); MainButtons(); return scene; } /** * */ public static void MainButtons(){ MainWindow gui =new MainWindow(); start.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { StartElements se = new StartElements(); try { gui.stage.setScene(se.insert()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } gui.stage.show(); } }); statistics.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { statisticElements se = new statisticElements(); gui.stage.setScene(se.insert()); gui.stage.show(); } }); exit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { gui.stage.close(); } }); } }
UTF-8
Java
3,331
java
MainElements.java
Java
[]
null
[]
import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.effect.Reflection; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class MainElements { StackPane stack = new StackPane(); static Button start = new Button("Start"); static Button statistics = new Button("Statistics"); static Button exit = new Button("Exit"); /** * * @return * @throws MalformedURLException */ public Scene insert() throws MalformedURLException{ VBox buttonPane = new VBox(); buttonPane.setSpacing(10); buttonPane.setPadding(new Insets(15,10, 15,10)); BorderPane titel = new BorderPane(); titel.setMinSize(1280, 300); BorderPane startButtonPane = new BorderPane(); BorderPane statisticsButtonPane = new BorderPane(); BorderPane exitButtonPane = new BorderPane(); File file = new File("pong2.jpg"); String localUrl = file.toURI().toURL().toString(); Image image = new Image(localUrl); ImageView imageView = new ImageView(image); Reflection reflection = new Reflection(); reflection.setBottomOpacity(0.0); reflection.setTopOpacity(0.5); reflection.setTopOffset(10); reflection.setFraction(0.7); Text text = new Text(); text.setX(20.0); text.setY(90.0); text.setCache(true); text.setText("Pong"); text.setFill(Color.web("0x99FF00")); text.setFont(Font.font(null, FontWeight.BOLD, 80)); text.setEffect(reflection); titel.setCenter(text); buttonPane.getChildren().addAll(titel); start.setPrefSize(500, 50); statistics.setPrefSize(500, 50); exit.setPrefSize(500, 50); startButtonPane.setCenter(start); statisticsButtonPane.setCenter(statistics); exitButtonPane.setCenter(exit); buttonPane.getChildren().add(startButtonPane); buttonPane.getChildren().add(statisticsButtonPane); buttonPane.getChildren().add(exitButtonPane); stack.getChildren().add(imageView); stack.getChildren().add(buttonPane); Scene scene = new Scene(stack,1280,720); MainButtons(); return scene; } /** * */ public static void MainButtons(){ MainWindow gui =new MainWindow(); start.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { StartElements se = new StartElements(); try { gui.stage.setScene(se.insert()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } gui.stage.show(); } }); statistics.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { statisticElements se = new statisticElements(); gui.stage.setScene(se.insert()); gui.stage.show(); } }); exit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { gui.stage.close(); } }); } }
3,331
0.704593
0.68628
130
24.63077
17.42065
58
false
false
0
0
0
0
0
0
2.384615
false
false
4
308a0652921e4c18715d594d99416469fd7e3749
15,066,745,316,365
58a6e87d33cdd2860b6934f96fa4e4dd3cfb4b1e
/java/com/example/kappa/assignment/DBHelper.java
a80af51b321555b32d14d652c567441b62bfef72
[]
no_license
KappaSkadoosh/ASSIGNMENT1
https://github.com/KappaSkadoosh/ASSIGNMENT1
39566f0b12bffd17a7891d1fdf3807efc9e6b4b5
bfd97732d20552d6ece98f09e6ec26ce5e58ef32
refs/heads/master
2021-01-17T08:47:02.393000
2017-03-07T08:34:47
2017-03-07T08:34:47
83,962,759
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.kappa.assignment; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created by Kappa on 3/3/2017. */ public class DBHelper extends SQLiteOpenHelper { private static String DB_PATH = "/data/data/com.example.kappa.assignment/databases/"; private static String DB_NAME = "Question.db"; private static final String TABLE = "questions"; private SQLiteDatabase myDataBase; private final Context myContext; public DBHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; } //Creates a empty database on the system and rewrites it with your own database. public void createDataBase() throws IOException{ boolean dbExist = checkDataBase(); if(dbExist){ }else{ this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } //Check if the database already exist to avoid re-copying the file each time you open the application. //return true if it exists, false if it doesn't private boolean checkDataBase(){ SQLiteDatabase checkDB = null; try{ String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); }catch(SQLiteException e){ //database does't exist yet. } if(checkDB != null){ checkDB.close(); } return checkDB != null ? true : false; } private void copyDataBase() throws IOException{ //Open your local databaseb as the input stream InputStream myInput = myContext.getAssets().open(DB_NAME); // Path to the just created empty databaseb String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public List<Question> getAllQuestions(){ //open database String Path = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(Path, null, SQLiteDatabase.OPEN_READONLY); //create list List<Question> QList = new ArrayList<Question>(); String Query = "SELECT * FROM " + TABLE; //make cursor get data Cursor cursor = myDataBase.rawQuery(Query, null); if (cursor.moveToFirst()){ do{ Question question= new Question(); question.setID(cursor.getInt(0)); question.setQuestion(cursor.getString(1)); question.setAnswer(cursor.getString(2)); question.setOption1(cursor.getString(3)); question.setOption2(cursor.getString(4)); question.setImage(cursor.getString(5)); QList.add(question); }while(cursor.moveToNext()); } cursor.close(); myDataBase.close(); return QList; } public void openDataBase() throws SQLException { //access the database String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { if(myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion>oldVersion){ myContext.deleteDatabase(DB_NAME); try{ copyDataBase(); } catch (IOException e){ e.printStackTrace(); } }else{ } } }
UTF-8
Java
4,795
java
DBHelper.java
Java
[ { "context": "\r\nimport android.util.Log;\r\n\r\n\r\n/**\r\n * Created by Kappa on 3/3/2017.\r\n */\r\n\r\npublic class DBHelper extend", "end": 561, "score": 0.9433847665786743, "start": 556, "tag": "USERNAME", "value": "Kappa" } ]
null
[]
package com.example.kappa.assignment; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created by Kappa on 3/3/2017. */ public class DBHelper extends SQLiteOpenHelper { private static String DB_PATH = "/data/data/com.example.kappa.assignment/databases/"; private static String DB_NAME = "Question.db"; private static final String TABLE = "questions"; private SQLiteDatabase myDataBase; private final Context myContext; public DBHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; } //Creates a empty database on the system and rewrites it with your own database. public void createDataBase() throws IOException{ boolean dbExist = checkDataBase(); if(dbExist){ }else{ this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } //Check if the database already exist to avoid re-copying the file each time you open the application. //return true if it exists, false if it doesn't private boolean checkDataBase(){ SQLiteDatabase checkDB = null; try{ String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); }catch(SQLiteException e){ //database does't exist yet. } if(checkDB != null){ checkDB.close(); } return checkDB != null ? true : false; } private void copyDataBase() throws IOException{ //Open your local databaseb as the input stream InputStream myInput = myContext.getAssets().open(DB_NAME); // Path to the just created empty databaseb String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public List<Question> getAllQuestions(){ //open database String Path = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(Path, null, SQLiteDatabase.OPEN_READONLY); //create list List<Question> QList = new ArrayList<Question>(); String Query = "SELECT * FROM " + TABLE; //make cursor get data Cursor cursor = myDataBase.rawQuery(Query, null); if (cursor.moveToFirst()){ do{ Question question= new Question(); question.setID(cursor.getInt(0)); question.setQuestion(cursor.getString(1)); question.setAnswer(cursor.getString(2)); question.setOption1(cursor.getString(3)); question.setOption2(cursor.getString(4)); question.setImage(cursor.getString(5)); QList.add(question); }while(cursor.moveToNext()); } cursor.close(); myDataBase.close(); return QList; } public void openDataBase() throws SQLException { //access the database String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public synchronized void close() { if(myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion>oldVersion){ myContext.deleteDatabase(DB_NAME); try{ copyDataBase(); } catch (IOException e){ e.printStackTrace(); } }else{ } } }
4,795
0.591658
0.587278
175
25.4
23.945892
106
false
false
0
0
0
0
0
0
0.451429
false
false
4
e272df68526b0d0d945073ec7e0553beecb0d2f8
23,321,672,478,811
2f11a67a7a11ac23c202bfe9992be729861124a5
/studentmanager/src/studentmanager/StudentManager.java
01af744e3922cf261c6e0c868e72fa59b00c5b0d
[]
no_license
AyushWalekar/upgrad-assignment
https://github.com/AyushWalekar/upgrad-assignment
c97c7d98747ae4e01ee08b4e14ea823ec2930e3d
b2c99af031a7ac1203fdb90ec65832b454c6d88c
refs/heads/master
2020-05-04T11:00:52.422000
2019-04-02T19:51:44
2019-04-02T19:51:44
179,099,013
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 studentmanager; import java.util.Scanner; /** * StudentManger - Main class to run the application. * @author ayush */ public class StudentManager { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int noOfTestCase; //input for number of test cases noOfTestCase = sc.nextInt(); String inputStr; String[] inputs; String name; float cgpa; int tokenNumber; while (noOfTestCase-- >= 0) { try { inputStr = sc.nextLine(); inputs = inputStr.split(" "); switch (inputs[0].toUpperCase()) { case "ENTER": name = inputs[1]; cgpa = Float.parseFloat(inputs[2]); tokenNumber = Integer.parseInt(inputs[3]); StudentQueue.enter(new Student(name, cgpa, tokenNumber)); break; case "SERVED": StudentQueue.serve(); break; default: //INVALID Input } }catch(Exception e){ //To catch exception due to Unexpected error while parsing Input } } //print the remaning the students list StudentQueue.printList(); } }
UTF-8
Java
1,654
java
StudentManager.java
Java
[ { "context": "er - Main class to run the application.\n * @author ayush\n */\npublic class StudentManager {\n\n /**\n *", "end": 311, "score": 0.9873712062835693, "start": 306, "tag": "USERNAME", "value": "ayush" } ]
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 studentmanager; import java.util.Scanner; /** * StudentManger - Main class to run the application. * @author ayush */ public class StudentManager { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int noOfTestCase; //input for number of test cases noOfTestCase = sc.nextInt(); String inputStr; String[] inputs; String name; float cgpa; int tokenNumber; while (noOfTestCase-- >= 0) { try { inputStr = sc.nextLine(); inputs = inputStr.split(" "); switch (inputs[0].toUpperCase()) { case "ENTER": name = inputs[1]; cgpa = Float.parseFloat(inputs[2]); tokenNumber = Integer.parseInt(inputs[3]); StudentQueue.enter(new Student(name, cgpa, tokenNumber)); break; case "SERVED": StudentQueue.serve(); break; default: //INVALID Input } }catch(Exception e){ //To catch exception due to Unexpected error while parsing Input } } //print the remaning the students list StudentQueue.printList(); } }
1,654
0.512697
0.509674
55
29.072727
21.249903
81
false
false
0
0
0
0
0
0
0.454545
false
false
4
035af2fcb16939c84dfc0b6664aba87480c7be67
32,375,463,538,194
5630be2e07f71cbee3376ebac9126fccba9ceea9
/app/src/main/java/com/example/gbooks/googlebooksclient/other/di/search/SearchComponent.java
28e930fbbea9cd31b24198c6a1c06d183bbb0702
[]
no_license
a23sokolov/Google-Books-Client
https://github.com/a23sokolov/Google-Books-Client
768fe1634aa3d72a3a72d239c819fea2e599402c
da1f0c5be8284eae33d42d108a73214ca3b083d1
refs/heads/master
2021-09-04T00:12:43.641000
2017-10-10T09:54:07
2017-10-10T09:54:07
104,646,409
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.gbooks.googlebooksclient.other.di.search; import com.example.gbooks.googlebooksclient.view.activity.SearchActivity; import javax.inject.Singleton; import dagger.Component; /** * Created by a23sokolov on 29/09/2017. */ @Singleton @Component(modules = {SearchViewModule.class}) public interface SearchComponent { void inject(SearchActivity searchActivity); }
UTF-8
Java
387
java
SearchComponent.java
Java
[ { "context": "eton;\n\nimport dagger.Component;\n\n/**\n * Created by a23sokolov on 29/09/2017.\n */\n@Singleton\n@Component(modules ", "end": 224, "score": 0.9996752142906189, "start": 214, "tag": "USERNAME", "value": "a23sokolov" } ]
null
[]
package com.example.gbooks.googlebooksclient.other.di.search; import com.example.gbooks.googlebooksclient.view.activity.SearchActivity; import javax.inject.Singleton; import dagger.Component; /** * Created by a23sokolov on 29/09/2017. */ @Singleton @Component(modules = {SearchViewModule.class}) public interface SearchComponent { void inject(SearchActivity searchActivity); }
387
0.795866
0.770026
16
23.1875
23.775562
73
false
false
0
0
0
0
0
0
0.3125
false
false
4
334e2913c4900eea5eb2d807ece45f3797eaa5f5
25,924,422,648,289
07c60af90bd758fa491d79d81433aacdcdd534b1
/src/main/java/com/example/favorites/web/exception/GlobalExceptionHandler.java
3c2aa8c964a6f0c2c40f51595210af79f91995fd
[]
no_license
Joylice/favorites-html
https://github.com/Joylice/favorites-html
f59dcdf227d0e6cdb9bb36ae31b83bdd5c608462
ef05410822dc6d2542f6694eaedfe26a7daf1a4b
refs/heads/master
2021-09-02T14:43:58.516000
2018-01-03T08:25:38
2018-01-03T08:25:38
109,950,458
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.favorites.web.exception; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; /** * Created by cuiyy on 2018/1/3. */ //使用该注解,不用任何的配置, //只要把这个类放在项目中,Spring能扫描到的地方, //就可以实现全局异常的回调。 @ControllerAdvice public class GlobalExceptionHandler { protected Logger logger = Logger.getLogger(this.getClass()); public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(Exception e, HttpServletRequest request) { logger.info("请求地址" + request.getRequestURL()); ModelAndView modelAndView = new ModelAndView(); logger.error("异常信息:" + e); modelAndView.setViewName(DEFAULT_ERROR_VIEW); return modelAndView; } }
UTF-8
Java
1,080
java
GlobalExceptionHandler.java
Java
[ { "context": "ervlet.http.HttpServletRequest;\n\n/**\n * Created by cuiyy on 2018/1/3.\n */\n//使用该注解,不用任何的配置,\n//只要把这个类放在项目中,S", "end": 332, "score": 0.9995935559272766, "start": 327, "tag": "USERNAME", "value": "cuiyy" } ]
null
[]
package com.example.favorites.web.exception; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; /** * Created by cuiyy on 2018/1/3. */ //使用该注解,不用任何的配置, //只要把这个类放在项目中,Spring能扫描到的地方, //就可以实现全局异常的回调。 @ControllerAdvice public class GlobalExceptionHandler { protected Logger logger = Logger.getLogger(this.getClass()); public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(Exception e, HttpServletRequest request) { logger.info("请求地址" + request.getRequestURL()); ModelAndView modelAndView = new ModelAndView(); logger.error("异常信息:" + e); modelAndView.setViewName(DEFAULT_ERROR_VIEW); return modelAndView; } }
1,080
0.752066
0.744835
31
30.225807
25.006721
86
false
false
0
0
0
0
0
0
0.451613
false
false
4
17824419c750b0e0f62235440050c3a68353da93
10,969,346,541,237
076af6d7f6461447a949ddb85fcde75ac9f0b8a4
/issuetrackapp/src/main/java/com/visa/prj/dao/IssueDao.java
2c7b71b292cfaea0b7340fa73d0be0d2c359d855
[]
no_license
abhi608/visa_tutorial
https://github.com/abhi608/visa_tutorial
67cdfaa9ba2e2bff8cd8c2bdbd1e51b081e3ff7f
a5499ce5d13aa48784df2e80f57512c5fa81dfaa
refs/heads/master
2020-03-24T06:27:12.704000
2018-08-10T11:34:08
2018-08-10T11:34:08
142,528,739
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.visa.prj.dao; import java.util.List; import com.visa.prj.entity.Employee; import com.visa.prj.entity.Issue; public interface IssueDao { void addEmployee(Employee emp) throws DaoException; List<Employee> getEmployees() throws DaoException; void raiseIssue(Issue issue) throws DaoException; List<Issue> getUnresolvedIssues() throws DaoException; }
UTF-8
Java
365
java
IssueDao.java
Java
[]
null
[]
package com.visa.prj.dao; import java.util.List; import com.visa.prj.entity.Employee; import com.visa.prj.entity.Issue; public interface IssueDao { void addEmployee(Employee emp) throws DaoException; List<Employee> getEmployees() throws DaoException; void raiseIssue(Issue issue) throws DaoException; List<Issue> getUnresolvedIssues() throws DaoException; }
365
0.8
0.8
13
27.076923
20.611652
55
false
false
0
0
0
0
0
0
0.923077
false
false
4
bdf460cfcee8f62995ff7f0c82fb12c7697e0e10
29,566,554,916,653
8782061b1e1223488a090f9f3f3b8dfe489e054a
/storeMongoDB/projects/ABCD/apache_commons-cli/main/7.java
0251e0e533b59be5f61bd96f09c05d06b3e39b91
[]
no_license
ryosuke-ku/TCS_init
https://github.com/ryosuke-ku/TCS_init
3cb79a46aa217e62d8fff13d600f2a9583df986c
e1207d68bdc9d2f1eed63ef44a672b5a37b45633
refs/heads/master
2020-08-08T18:40:17.929000
2019-10-18T01:06:32
2019-10-18T01:06:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public boolean isRequired() { return required; }
UTF-8
Java
73
java
7.java
Java
[]
null
[]
public boolean isRequired() { return required; }
73
0.506849
0.506849
4
15.25
10.304732
27
false
false
0
0
0
0
0
0
0.25
false
false
4
737d09e3423302be9f5d287307de8a90a0ae59fd
1,073,741,848,465
6cf96295f4533367030f2900a4b9faa3e459c3b5
/src/main/java/com/Server/QuestionServer.java
467979e684b2218fb339e7ce4d8a3e93e35645af
[]
no_license
Diffblue-benchmarks/Proud-Sachinda-Segfault
https://github.com/Diffblue-benchmarks/Proud-Sachinda-Segfault
d0e3c439a7acdb02baecaf8866102bdf3bb9b88f
6b36b0ee5e32d97eb44020dd96c6ef844f76dd79
refs/heads/master
2020-05-26T11:15:46.194000
2019-05-23T10:22:15
2019-05-23T10:22:15
188,212,891
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Server; import com.Objects.LecturerItem; import com.Objects.QuestionItem; import javax.validation.constraints.NotNull; import java.sql.*; import java.util.ArrayList; public class QuestionServer { // connection variable private Connection connection; public QuestionServer(@NotNull Connection connection) { // initialise connection variable this.connection = connection; } // -------------------------------- GET METHODS (SELECT) public ArrayList<QuestionItem> getQuestionItems() { // question array ArrayList<QuestionItem> questions = new ArrayList<>(); try { // get database variables Statement statement = connection.createStatement(); // query String query = "SELECT DISTINCT * FROM public.question"; // execute statement ResultSet set = statement.executeQuery(query); while(set.next()) { // QuestionItem class variable QuestionItem question = new QuestionItem(); // set variables question.setUpQuestionItem(set); // add to array list questions.add(question); } } catch (SQLException e) { e.printStackTrace(); } return questions; } public QuestionItem getQuestionItemById(int questionId) { // create return question item QuestionItem item = new QuestionItem(); try { // get database variables Statement statement = connection.createStatement(); // query String query = "SELECT * FROM public.question WHERE question_id = " + questionId; // execute statement ResultSet set = statement.executeQuery(query); while(set.next()) { // set variables item.setUpQuestionItem(set); } } catch (SQLException e) { e.printStackTrace(); } return item; } // -------------------------------- POST METHODS (INSERT) public int postToQuestionTable(QuestionItem questionItem, LecturerItem lecturerItem, int course_id) { // return variable int questionId = 0; try { // insert into core table String query = "INSERT INTO public.question" + "(lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id, question_is_variant, question_variance)" + "VALUES" + "('" + lecturerItem.getLecturerId() + "', '" + questionItem.getQuestionType() + "', '" + questionItem.getQuestionBody() + "', '" + questionItem.getQuestionAns() + "', now(), " + questionItem.getQuestionMark() + ", " + questionItem.getQuestionDifficulty() + ", " + course_id + ", " + questionItem.getQuestionIsVariant() + ", " + questionItem.getQuestionVariance() + ")"; // statement Statement statement = connection.createStatement(); // execute statement questionId = statement.executeUpdate(query); // get question id query = "SELECT question_id FROM public.question ORDER BY question_id DESC LIMIT 1"; // execute statement ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { questionId = resultSet.getInt("question_id"); } if (questionId > 0) { // post to other question tables if (questionItem.getQuestionType().equals("written")) { // query for written table query = "INSERT INTO public.written_question" + "(question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id) " + "SELECT question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id FROM public.question " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } else if (questionItem.getQuestionType().equals("mcq")) { // query for mcq table query = "INSERT INTO public.mcq_question" + "(question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id)" + "SELECT question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id FROM public.question " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); // set mcq choices query = "UPDATE public.mcq_question " + "SET mcq_choices = " + questionItem.getQuestionMcqChoices() + " " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } else { // query for mcq table query = "INSERT INTO public.practical_question" + "(question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id)" + "SELECT question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id FROM public.question " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); // set mcq choices query = "UPDATE public.practical_question " + "SET sample_input = '" + questionItem.getQuestionPracticalSampleInput() + "', " + "sample_output = '" + questionItem.getQuestionPracticalSampleOutput() + "' " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } // set mcq choices query = "UPDATE public.question " + "SET question_is_variant = " + questionItem.getQuestionIsVariant() + ", " + "question_variance = " + questionItem.getQuestionVariance() + " " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } } catch (SQLException e) { e.printStackTrace(); } return questionId; } // -------------------------------- PUT METHODS (UPDATE) public boolean updateQuestionItem(QuestionItem item) { // return variable boolean success = false; try { // query String query = "UPDATE public.question" + " SET question_difficulty = ?, " + "question_mark = ?, " + "question_body = ?, " + "question_variance = ?, " + "question_is_variant = ?, " + "question_ans = ? " + " WHERE question_id = ?"; // statement PreparedStatement preparedStatement = connection.prepareStatement(query); // set strings preparedStatement.setInt(1, item.getQuestionDifficulty()); preparedStatement.setInt(2, item.getQuestionMark()); preparedStatement.setString(3, item.getQuestionBody()); preparedStatement.setInt(4, item.getQuestionVariance()); preparedStatement.setBoolean(5, item.getQuestionIsVariant()); preparedStatement.setString(6, item.getQuestionAns()); preparedStatement.setInt(7, item.getQuestionId()); // execute statement if (preparedStatement.executeUpdate() > 0) success = true; } catch (SQLException e) { e.printStackTrace(); success = false; } return success; } public boolean incrementQuestionItemVariance(int question_id) { // return variable boolean success = false; try { // query String query = "UPDATE public.question" + " SET question_variance = question_variance + 1 " + "WHERE question_id = " + question_id; // statement Statement statement = connection.createStatement(); // execute statement if (statement.executeUpdate(query) > 0) success = true; } catch (SQLException e) { e.printStackTrace(); success = false; } return success; } }
UTF-8
Java
9,575
java
QuestionServer.java
Java
[]
null
[]
package com.Server; import com.Objects.LecturerItem; import com.Objects.QuestionItem; import javax.validation.constraints.NotNull; import java.sql.*; import java.util.ArrayList; public class QuestionServer { // connection variable private Connection connection; public QuestionServer(@NotNull Connection connection) { // initialise connection variable this.connection = connection; } // -------------------------------- GET METHODS (SELECT) public ArrayList<QuestionItem> getQuestionItems() { // question array ArrayList<QuestionItem> questions = new ArrayList<>(); try { // get database variables Statement statement = connection.createStatement(); // query String query = "SELECT DISTINCT * FROM public.question"; // execute statement ResultSet set = statement.executeQuery(query); while(set.next()) { // QuestionItem class variable QuestionItem question = new QuestionItem(); // set variables question.setUpQuestionItem(set); // add to array list questions.add(question); } } catch (SQLException e) { e.printStackTrace(); } return questions; } public QuestionItem getQuestionItemById(int questionId) { // create return question item QuestionItem item = new QuestionItem(); try { // get database variables Statement statement = connection.createStatement(); // query String query = "SELECT * FROM public.question WHERE question_id = " + questionId; // execute statement ResultSet set = statement.executeQuery(query); while(set.next()) { // set variables item.setUpQuestionItem(set); } } catch (SQLException e) { e.printStackTrace(); } return item; } // -------------------------------- POST METHODS (INSERT) public int postToQuestionTable(QuestionItem questionItem, LecturerItem lecturerItem, int course_id) { // return variable int questionId = 0; try { // insert into core table String query = "INSERT INTO public.question" + "(lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id, question_is_variant, question_variance)" + "VALUES" + "('" + lecturerItem.getLecturerId() + "', '" + questionItem.getQuestionType() + "', '" + questionItem.getQuestionBody() + "', '" + questionItem.getQuestionAns() + "', now(), " + questionItem.getQuestionMark() + ", " + questionItem.getQuestionDifficulty() + ", " + course_id + ", " + questionItem.getQuestionIsVariant() + ", " + questionItem.getQuestionVariance() + ")"; // statement Statement statement = connection.createStatement(); // execute statement questionId = statement.executeUpdate(query); // get question id query = "SELECT question_id FROM public.question ORDER BY question_id DESC LIMIT 1"; // execute statement ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { questionId = resultSet.getInt("question_id"); } if (questionId > 0) { // post to other question tables if (questionItem.getQuestionType().equals("written")) { // query for written table query = "INSERT INTO public.written_question" + "(question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id) " + "SELECT question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id FROM public.question " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } else if (questionItem.getQuestionType().equals("mcq")) { // query for mcq table query = "INSERT INTO public.mcq_question" + "(question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id)" + "SELECT question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id FROM public.question " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); // set mcq choices query = "UPDATE public.mcq_question " + "SET mcq_choices = " + questionItem.getQuestionMcqChoices() + " " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } else { // query for mcq table query = "INSERT INTO public.practical_question" + "(question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id)" + "SELECT question_id, lecturer_id, question_type, question_body, question_ans, question_date, " + "question_mark, question_difficulty, course_id FROM public.question " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); // set mcq choices query = "UPDATE public.practical_question " + "SET sample_input = '" + questionItem.getQuestionPracticalSampleInput() + "', " + "sample_output = '" + questionItem.getQuestionPracticalSampleOutput() + "' " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } // set mcq choices query = "UPDATE public.question " + "SET question_is_variant = " + questionItem.getQuestionIsVariant() + ", " + "question_variance = " + questionItem.getQuestionVariance() + " " + "WHERE question_id = " + questionId; // execute statement statement.executeUpdate(query); } } catch (SQLException e) { e.printStackTrace(); } return questionId; } // -------------------------------- PUT METHODS (UPDATE) public boolean updateQuestionItem(QuestionItem item) { // return variable boolean success = false; try { // query String query = "UPDATE public.question" + " SET question_difficulty = ?, " + "question_mark = ?, " + "question_body = ?, " + "question_variance = ?, " + "question_is_variant = ?, " + "question_ans = ? " + " WHERE question_id = ?"; // statement PreparedStatement preparedStatement = connection.prepareStatement(query); // set strings preparedStatement.setInt(1, item.getQuestionDifficulty()); preparedStatement.setInt(2, item.getQuestionMark()); preparedStatement.setString(3, item.getQuestionBody()); preparedStatement.setInt(4, item.getQuestionVariance()); preparedStatement.setBoolean(5, item.getQuestionIsVariant()); preparedStatement.setString(6, item.getQuestionAns()); preparedStatement.setInt(7, item.getQuestionId()); // execute statement if (preparedStatement.executeUpdate() > 0) success = true; } catch (SQLException e) { e.printStackTrace(); success = false; } return success; } public boolean incrementQuestionItemVariance(int question_id) { // return variable boolean success = false; try { // query String query = "UPDATE public.question" + " SET question_variance = question_variance + 1 " + "WHERE question_id = " + question_id; // statement Statement statement = connection.createStatement(); // execute statement if (statement.executeUpdate(query) > 0) success = true; } catch (SQLException e) { e.printStackTrace(); success = false; } return success; } }
9,575
0.520418
0.51906
264
35.26894
32.135479
124
false
false
0
0
0
0
0
0
0.560606
false
false
4
baaa8d88829cb22091c7c05a51742c36082a3caa
17,824,114,288,935
3ca53c13d2953805c00406476ceda9684887a8ad
/src/com/iwxxm/taf/GeodeticCRSType.java
17843e542eb33317ce0f99ad21cddd8ed4c1c9ba
[]
no_license
yw2017051032/tac2iwxxm
https://github.com/yw2017051032/tac2iwxxm
ae93c12b08b7316cd59de032d4ae2e8082bc6c0b
5a08cb9ecd0833fd4435bf6db81a2b8126380ec1
refs/heads/master
2020-03-17T03:03:06.671000
2018-06-05T16:55:59
2018-06-05T17:06:03
133,217,637
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// // 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.8-b130911.1802 生成的 // 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // 在重新编译源模式时, 对此文件的所有修改都将丢失。 // 生成时间: 2018.04.04 时间 07:08:22 PM CST // package com.iwxxm.taf; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; /** * gml:GeodeticCRS is a coordinate reference system based on a geodetic datum. * * <p>GeodeticCRSType complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="GeodeticCRSType"> * &lt;complexContent> * &lt;extension base="{http://www.opengis.net/gml/3.2}AbstractCRSType"> * &lt;sequence> * &lt;choice> * &lt;element ref="{http://www.opengis.net/gml/3.2}ellipsoidalCS"/> * &lt;element ref="{http://www.opengis.net/gml/3.2}cartesianCS"/> * &lt;element ref="{http://www.opengis.net/gml/3.2}sphericalCS"/> * &lt;/choice> * &lt;element ref="{http://www.opengis.net/gml/3.2}geodeticDatum"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GeodeticCRSType", propOrder = { "ellipsoidalCS", "cartesianCS", "sphericalCS", "geodeticDatum" }) public class GeodeticCRSType extends AbstractCRSType { @XmlElementRef(name = "ellipsoidalCS", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class, required = false) protected JAXBElement<EllipsoidalCSPropertyType> ellipsoidalCS; @XmlElementRef(name = "cartesianCS", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class, required = false) protected JAXBElement<CartesianCSPropertyType> cartesianCS; @XmlElementRef(name = "sphericalCS", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class, required = false) protected JAXBElement<SphericalCSPropertyType> sphericalCS; @XmlElementRef(name = "geodeticDatum", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class) protected JAXBElement<GeodeticDatumPropertyType> geodeticDatum; /** * 获取ellipsoidalCS属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * */ public JAXBElement<EllipsoidalCSPropertyType> getEllipsoidalCS() { return ellipsoidalCS; } /** * 设置ellipsoidalCS属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * */ public void setEllipsoidalCS(JAXBElement<EllipsoidalCSPropertyType> value) { this.ellipsoidalCS = value; } /** * 获取cartesianCS属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * */ public JAXBElement<CartesianCSPropertyType> getCartesianCS() { return cartesianCS; } /** * 设置cartesianCS属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * */ public void setCartesianCS(JAXBElement<CartesianCSPropertyType> value) { this.cartesianCS = value; } /** * 获取sphericalCS属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * */ public JAXBElement<SphericalCSPropertyType> getSphericalCS() { return sphericalCS; } /** * 设置sphericalCS属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * */ public void setSphericalCS(JAXBElement<SphericalCSPropertyType> value) { this.sphericalCS = value; } /** * 获取geodeticDatum属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * */ public JAXBElement<GeodeticDatumPropertyType> getGeodeticDatum() { return geodeticDatum; } /** * 设置geodeticDatum属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * */ public void setGeodeticDatum(JAXBElement<GeodeticDatumPropertyType> value) { this.geodeticDatum = value; } }
GB18030
Java
5,835
java
GeodeticCRSType.java
Java
[]
null
[]
// // 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.8-b130911.1802 生成的 // 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // 在重新编译源模式时, 对此文件的所有修改都将丢失。 // 生成时间: 2018.04.04 时间 07:08:22 PM CST // package com.iwxxm.taf; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; /** * gml:GeodeticCRS is a coordinate reference system based on a geodetic datum. * * <p>GeodeticCRSType complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="GeodeticCRSType"> * &lt;complexContent> * &lt;extension base="{http://www.opengis.net/gml/3.2}AbstractCRSType"> * &lt;sequence> * &lt;choice> * &lt;element ref="{http://www.opengis.net/gml/3.2}ellipsoidalCS"/> * &lt;element ref="{http://www.opengis.net/gml/3.2}cartesianCS"/> * &lt;element ref="{http://www.opengis.net/gml/3.2}sphericalCS"/> * &lt;/choice> * &lt;element ref="{http://www.opengis.net/gml/3.2}geodeticDatum"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GeodeticCRSType", propOrder = { "ellipsoidalCS", "cartesianCS", "sphericalCS", "geodeticDatum" }) public class GeodeticCRSType extends AbstractCRSType { @XmlElementRef(name = "ellipsoidalCS", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class, required = false) protected JAXBElement<EllipsoidalCSPropertyType> ellipsoidalCS; @XmlElementRef(name = "cartesianCS", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class, required = false) protected JAXBElement<CartesianCSPropertyType> cartesianCS; @XmlElementRef(name = "sphericalCS", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class, required = false) protected JAXBElement<SphericalCSPropertyType> sphericalCS; @XmlElementRef(name = "geodeticDatum", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class) protected JAXBElement<GeodeticDatumPropertyType> geodeticDatum; /** * 获取ellipsoidalCS属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * */ public JAXBElement<EllipsoidalCSPropertyType> getEllipsoidalCS() { return ellipsoidalCS; } /** * 设置ellipsoidalCS属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link EllipsoidalCSPropertyType }{@code >} * */ public void setEllipsoidalCS(JAXBElement<EllipsoidalCSPropertyType> value) { this.ellipsoidalCS = value; } /** * 获取cartesianCS属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * */ public JAXBElement<CartesianCSPropertyType> getCartesianCS() { return cartesianCS; } /** * 设置cartesianCS属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link CartesianCSPropertyType }{@code >} * */ public void setCartesianCS(JAXBElement<CartesianCSPropertyType> value) { this.cartesianCS = value; } /** * 获取sphericalCS属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * */ public JAXBElement<SphericalCSPropertyType> getSphericalCS() { return sphericalCS; } /** * 设置sphericalCS属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link SphericalCSPropertyType }{@code >} * */ public void setSphericalCS(JAXBElement<SphericalCSPropertyType> value) { this.sphericalCS = value; } /** * 获取geodeticDatum属性的值。 * * @return * possible object is * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * */ public JAXBElement<GeodeticDatumPropertyType> getGeodeticDatum() { return geodeticDatum; } /** * 设置geodeticDatum属性的值。 * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * {@link JAXBElement }{@code <}{@link GeodeticDatumPropertyType }{@code >} * */ public void setGeodeticDatum(JAXBElement<GeodeticDatumPropertyType> value) { this.geodeticDatum = value; } }
5,835
0.605475
0.597423
168
31.267857
31.545597
132
false
false
0
0
0
0
0
0
0.285714
false
false
4
14b39b395a12d755d473c1b9f22285ceff0fb735
23,132,693,903,307
8dbd3fe15b9f161820aca9af404252bd58a8ac26
/src/test/java/com/learning/crackingcodinginterview/BSTSequences.java
7f9822c920f7102991b4d16892d7042561d74565
[]
no_license
sandeep2703/Learning
https://github.com/sandeep2703/Learning
18cba1d53c22bb587f8b52932ec5fedec6f64f83
e52a28926d1926e48c32513e68b805fbaa3c8ac9
refs/heads/master
2020-03-31T00:20:40.372000
2018-10-06T03:43:56
2018-10-06T03:43:56
151,735,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.learning.crackingcodinginterview; import java.util.ArrayList; import java.util.LinkedList; import com.objects.TreeNode; //4.9 public class BSTSequences { public static void main(String[] args) { // TODO Auto-generated method stub } public static ArrayList<LinkedList<Integer>> allSequences(TreeNode a) { ArrayList<LinkedList<Integer>> result = new ArrayList<LinkedList<Integer>>(); if (a==null) { result.add(new LinkedList<Integer>()); return result; } LinkedList<Integer> prefix = new LinkedList<Integer>(); prefix.add(a.val); ArrayList<LinkedList<Integer>> leftC = allSequences(a.left); ArrayList<LinkedList<Integer>> rightR = allSequences(a.right); for (LinkedList<Integer> first: leftC) { for (LinkedList<Integer> second: rightR) { ArrayList<LinkedList<Integer>> output = new ArrayList<LinkedList<Integer>>(); weaveLists(first, second, prefix, output); result.addAll(output); } } return result; } public static void weaveLists(LinkedList<Integer> first, LinkedList<Integer> second, LinkedList<Integer> prefix, ArrayList<LinkedList<Integer>> results) { //If first of second is 0 then add the other to prefix and add to result if (first.size() == 0 || second.size()==1) { LinkedList<Integer> output = (LinkedList<Integer>) prefix.clone(); output.addAll(first); output.addAll(second); results.add(output); return;//base case i missed } //take first element as prefix int temp = first.removeFirst(); prefix.addLast(temp); weaveLists(first, second, prefix, results); first.addFirst(temp); prefix.removeLast(); //take second element as prefix temp = second.removeFirst(); prefix.addLast(temp); weaveLists(first, second, prefix, results); second.addFirst(temp); prefix.removeLast(); } }
UTF-8
Java
1,812
java
BSTSequences.java
Java
[]
null
[]
package com.learning.crackingcodinginterview; import java.util.ArrayList; import java.util.LinkedList; import com.objects.TreeNode; //4.9 public class BSTSequences { public static void main(String[] args) { // TODO Auto-generated method stub } public static ArrayList<LinkedList<Integer>> allSequences(TreeNode a) { ArrayList<LinkedList<Integer>> result = new ArrayList<LinkedList<Integer>>(); if (a==null) { result.add(new LinkedList<Integer>()); return result; } LinkedList<Integer> prefix = new LinkedList<Integer>(); prefix.add(a.val); ArrayList<LinkedList<Integer>> leftC = allSequences(a.left); ArrayList<LinkedList<Integer>> rightR = allSequences(a.right); for (LinkedList<Integer> first: leftC) { for (LinkedList<Integer> second: rightR) { ArrayList<LinkedList<Integer>> output = new ArrayList<LinkedList<Integer>>(); weaveLists(first, second, prefix, output); result.addAll(output); } } return result; } public static void weaveLists(LinkedList<Integer> first, LinkedList<Integer> second, LinkedList<Integer> prefix, ArrayList<LinkedList<Integer>> results) { //If first of second is 0 then add the other to prefix and add to result if (first.size() == 0 || second.size()==1) { LinkedList<Integer> output = (LinkedList<Integer>) prefix.clone(); output.addAll(first); output.addAll(second); results.add(output); return;//base case i missed } //take first element as prefix int temp = first.removeFirst(); prefix.addLast(temp); weaveLists(first, second, prefix, results); first.addFirst(temp); prefix.removeLast(); //take second element as prefix temp = second.removeFirst(); prefix.addLast(temp); weaveLists(first, second, prefix, results); second.addFirst(temp); prefix.removeLast(); } }
1,812
0.713024
0.710265
62
28.225807
24.866365
113
false
false
0
0
0
0
0
0
2.419355
false
false
4