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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
524b3c3c2f23b6d66f927da5736f7d4e41c2a38d | 17,033,840,350,606 | 1409cc235c0e0e64da94b576d3b91401ffe28a21 | /library/src/com/gametravel/assetsbuilder/data/BaseAssetData.java | cc179b8379ac3337cae6b37735656da89fda9bf0 | [
"Apache-2.0"
]
| permissive | danielchow/AssetBuilder | https://github.com/danielchow/AssetBuilder | a0f4cdc064e8a54ca3d3ca80204eb0a24257657b | 59ebdbc03622f029e4287b6e9e0e58387635cc1a | refs/heads/master | 2016-09-05T19:03:52.154000 | 2014-06-01T17:26:30 | 2014-06-01T17:26:30 | 19,985,203 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gametravel.assetsbuilder.data;
import com.badlogic.gdx.utils.Array;
import com.gametravel.assetsbuilder.Options;
import com.gametravel.assetsbuilder.scan.AssetBundle;
import com.gametravel.assetsbuilder.util.Util;
/**
* Basic implementation of {@link com.gametravel.assetsbuilder.data.AssetData}.
* @author Hang Zhou Apr 1, 2014 4:18:05 PM
*/
public class BaseAssetData implements AssetData {
/** The full name of asset data, e.g. {@code "libgdx_boy_jump.png"}. */
protected String fullName;
/** The full name of asset data, e.g. {@code "libgdx_boy_jump"}. */
protected String simpleName;
/** Whether asset data is resolved. */
protected boolean resolved = false;
/** Whether has already tried resolving this asset data. */
protected boolean triedResolve = false;
protected boolean tagged = false;
/**
* The information about this asset unit, e.g. the reason of failed resolving or other info.
*/
protected String message;
/** Array of assets that depends on this asset. */
protected Array<AssetData> dependants = new Array<AssetData>(false, 1);
public BaseAssetData(String fullName, String simpleName) {
this.fullName = fullName;
this.simpleName = simpleName;
}
@Override
public boolean resolve(AssetBundle bundle, Options options) {
triedResolve = true;
return false;
}
@Override
public void tag(boolean tag, Options options) {
this.tagged = tag;
if (options.LogOption.DEBUG) Util.log((tag ? "Tag" : "Un") + " " + toString());
}
@Override
public boolean isTagged() {
return this.tagged;
}
@Override
public boolean isResolved() {
return resolved;
}
@Override
public boolean hasTriedResolve() {
return triedResolve;
}
/**
* Returns the information about this asset unit, e.g. the reason of failed resolving or other
* info.
* @return The message
*/
public String getMessage() {
return message;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("{ name:").append(fullName).append(", type:")
.append(getClass().getSimpleName()).append(", status:");
if (isResolved()) {
builder.append("RESOLVED }");
} else if (hasTriedResolve()) {
builder.append("FAILED, Message:").append(getMessage()).append(" }");
} else {
builder.append("PENDING }");
}
return builder.toString();
}
@Override
public String simpleName() {
return simpleName;
}
@Override
public String fullName() {
return fullName;
}
@Override
public Array<AssetData> getDependants() {
return dependants;
}
@Override
public void addDependant(AssetData dependant) {
dependants.add(dependant);
}
}
| UTF-8 | Java | 2,951 | java | BaseAssetData.java | Java | [
{
"context": "metravel.assetsbuilder.data.AssetData}.\n * @author Hang Zhou Apr 1, 2014 4:18:05 PM\n */\npublic class BaseAsset",
"end": 332,
"score": 0.9998060464859009,
"start": 323,
"tag": "NAME",
"value": "Hang Zhou"
}
]
| null | []
| package com.gametravel.assetsbuilder.data;
import com.badlogic.gdx.utils.Array;
import com.gametravel.assetsbuilder.Options;
import com.gametravel.assetsbuilder.scan.AssetBundle;
import com.gametravel.assetsbuilder.util.Util;
/**
* Basic implementation of {@link com.gametravel.assetsbuilder.data.AssetData}.
* @author <NAME> Apr 1, 2014 4:18:05 PM
*/
public class BaseAssetData implements AssetData {
/** The full name of asset data, e.g. {@code "libgdx_boy_jump.png"}. */
protected String fullName;
/** The full name of asset data, e.g. {@code "libgdx_boy_jump"}. */
protected String simpleName;
/** Whether asset data is resolved. */
protected boolean resolved = false;
/** Whether has already tried resolving this asset data. */
protected boolean triedResolve = false;
protected boolean tagged = false;
/**
* The information about this asset unit, e.g. the reason of failed resolving or other info.
*/
protected String message;
/** Array of assets that depends on this asset. */
protected Array<AssetData> dependants = new Array<AssetData>(false, 1);
public BaseAssetData(String fullName, String simpleName) {
this.fullName = fullName;
this.simpleName = simpleName;
}
@Override
public boolean resolve(AssetBundle bundle, Options options) {
triedResolve = true;
return false;
}
@Override
public void tag(boolean tag, Options options) {
this.tagged = tag;
if (options.LogOption.DEBUG) Util.log((tag ? "Tag" : "Un") + " " + toString());
}
@Override
public boolean isTagged() {
return this.tagged;
}
@Override
public boolean isResolved() {
return resolved;
}
@Override
public boolean hasTriedResolve() {
return triedResolve;
}
/**
* Returns the information about this asset unit, e.g. the reason of failed resolving or other
* info.
* @return The message
*/
public String getMessage() {
return message;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("{ name:").append(fullName).append(", type:")
.append(getClass().getSimpleName()).append(", status:");
if (isResolved()) {
builder.append("RESOLVED }");
} else if (hasTriedResolve()) {
builder.append("FAILED, Message:").append(getMessage()).append(" }");
} else {
builder.append("PENDING }");
}
return builder.toString();
}
@Override
public String simpleName() {
return simpleName;
}
@Override
public String fullName() {
return fullName;
}
@Override
public Array<AssetData> getDependants() {
return dependants;
}
@Override
public void addDependant(AssetData dependant) {
dependants.add(dependant);
}
}
| 2,948 | 0.628262 | 0.624534 | 110 | 25.827272 | 25.118576 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.390909 | false | false | 13 |
8e9ef8b5486736c3eb6808c5bf45afadfac935ac | 10,342,281,314,097 | efe11ddfe31abcd778e3141feb07af3f6d465c11 | /gdx-test/src/main/java/de/hochschuletrier/gdw/ss14/sandbox/ecs/systems/TestRenderSystem.java | a4fde432c11178899cdac34aa1b92707bc4e3f3c | []
| no_license | GameDevWeek/GDW-2014-SS | https://github.com/GameDevWeek/GDW-2014-SS | 16a9079dd0427301b01c65572f82d6e941197173 | 4818ed0b24d74f15da3abdec96522f605becf5bf | refs/heads/master | 2020-04-23T14:05:30.915000 | 2014-10-05T13:32:23 | 2014-10-05T13:32:23 | 41,483,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.hochschuletrier.gdw.ss14.sandbox.ecs.systems;
import com.badlogic.gdx.math.*;
import com.badlogic.gdx.utils.*;
import de.hochschuletrier.gdw.commons.gdx.utils.*;
import de.hochschuletrier.gdw.ss14.sandbox.ecs.*;
import de.hochschuletrier.gdw.ss14.sandbox.ecs.components.*;
/**
* Created by Dani on 29.09.2014.
*/
public class TestRenderSystem extends ECSystem
{
public TestRenderSystem(EntityManager entityManager)
{
super(entityManager, 10);
}
@Override
public void update(float delta)
{
}
@Override
public void render()
{
Array<Integer> entityArray = entityManager.getAllEntitiesWithComponents(TestRenderComponent.class, PhysicsComponent.class);
for (Integer entity : entityArray)
{
PhysicsComponent physicsComponent = entityManager.getComponent(entity, PhysicsComponent.class);
TestRenderComponent testRenderComponent = entityManager.getComponent(entity, TestRenderComponent.class);
Vector2 pos = physicsComponent.getPosition();
DrawUtil.batch.draw(testRenderComponent.texture, pos.x, pos.y);
}
}
}
| UTF-8 | Java | 1,195 | java | TestRenderSystem.java | Java | [
{
"context": "14.sandbox.ecs.components.*;\r\n\r\n/**\r\n * Created by Dani on 29.09.2014.\r\n */\r\npublic class TestRenderSyste",
"end": 317,
"score": 0.9980411529541016,
"start": 313,
"tag": "NAME",
"value": "Dani"
}
]
| null | []
| package de.hochschuletrier.gdw.ss14.sandbox.ecs.systems;
import com.badlogic.gdx.math.*;
import com.badlogic.gdx.utils.*;
import de.hochschuletrier.gdw.commons.gdx.utils.*;
import de.hochschuletrier.gdw.ss14.sandbox.ecs.*;
import de.hochschuletrier.gdw.ss14.sandbox.ecs.components.*;
/**
* Created by Dani on 29.09.2014.
*/
public class TestRenderSystem extends ECSystem
{
public TestRenderSystem(EntityManager entityManager)
{
super(entityManager, 10);
}
@Override
public void update(float delta)
{
}
@Override
public void render()
{
Array<Integer> entityArray = entityManager.getAllEntitiesWithComponents(TestRenderComponent.class, PhysicsComponent.class);
for (Integer entity : entityArray)
{
PhysicsComponent physicsComponent = entityManager.getComponent(entity, PhysicsComponent.class);
TestRenderComponent testRenderComponent = entityManager.getComponent(entity, TestRenderComponent.class);
Vector2 pos = physicsComponent.getPosition();
DrawUtil.batch.draw(testRenderComponent.texture, pos.x, pos.y);
}
}
}
| 1,195 | 0.686192 | 0.671967 | 40 | 27.875 | 33.595528 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 13 |
baa6641c40793b828ba55c3401a80608488fa635 | 10,342,281,314,895 | 17903b3ae811bfc639b11062577e4b8c345cae7b | /springbootws/src/main/java/com/example/ws/models/GetQuotationsRequest.java | 848230eb2395b975142987a326204a56de3bb89a | []
| no_license | borkox/hmrc-example | https://github.com/borkox/hmrc-example | 8a15391a0c8d1fa701f91914c7722a2c0a3bc271 | b2b62a28c03adbbd880b643ce7534086837856bf | refs/heads/master | 2020-03-31T13:28:43.289000 | 2018-10-11T21:09:56 | 2018-10-11T21:09:56 | 152,257,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.ws.models;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(namespace = "http://spring.io/guides/gs-producing-web-service", name = "getQuotationsRequest")
public class GetQuotationsRequest {
}
| UTF-8 | Java | 231 | java | GetQuotationsRequest.java | Java | []
| null | []
| package com.example.ws.models;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(namespace = "http://spring.io/guides/gs-producing-web-service", name = "getQuotationsRequest")
public class GetQuotationsRequest {
}
| 231 | 0.796537 | 0.796537 | 7 | 32 | 36.570869 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
9ff31a119f7b0a3988bf4e588cc5b79bdb3b79ae | 23,862,838,322,184 | 8ed00e7ba26066b250b56e42a6ba21f833ac175c | /src/main/java/com/road/yishi/log/analysor/AnalylizLogLocalReducer.java | b476319997a616b97f1d9afe430169cad99a0a1d | []
| no_license | pbting/Prism | https://github.com/pbting/Prism | 463236d8c91b6ca7b69ae90eac7ac6e6cd0e8a0e | cdab96107dcf128c3dd8d79fc21e45c70cde0f0f | refs/heads/master | 2021-01-12T23:33:17.196000 | 2016-10-06T01:58:42 | 2016-10-06T01:58:42 | 64,666,261 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.road.yishi.log.analysor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.road.yishi.log.Log;
import com.road.yishi.log.core.LogDetailInfo;
import com.road.yishi.log.core.LogMetaInfo;
import com.road.yishi.log.handler.Reducer;
import com.road.yishi.log.mgr.MessagePersiterMgr;
import com.road.yishi.log.mgr.TopicHandlerMappingMgr;
import com.road.yishi.log.servlet.service.ConsumerLogFactory;
import com.road.yishi.log.vo.LogKeyInfo;
public class AnalylizLogLocalReducer implements Reducer<LogMetaInfo, List<LogDetailInfo>> {
@Override
public void reduce(LogMetaInfo k, List<LogDetailInfo> v) {
try {
String topicName = TopicHandlerMappingMgr.getReducerTopicName(AnalylizLogLocalReducer.class.getName());
MessagePersiterMgr.persister(topicName, k.getKey(), v,(short) 0);
Map<LogKeyInfo,Integer> keyCountMap = ConsumerLogFactory.countMap.get(topicName);
if(keyCountMap == null){
keyCountMap = new HashMap<LogKeyInfo,Integer>();
ConsumerLogFactory.countMap.put(topicName, keyCountMap);
}
Integer count = keyCountMap.get(new LogKeyInfo(k.getKey()));
if(count == null){
count = 0 ;
}
keyCountMap.put(new LogKeyInfo(v.get(v.size()-1).getOccurDate(), k.getKey(), count+v.size()), count+v.size());
} catch (Exception e) {
Log.error("", e);
}
}
}
| UTF-8 | Java | 1,376 | java | AnalylizLogLocalReducer.java | Java | []
| null | []
| package com.road.yishi.log.analysor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.road.yishi.log.Log;
import com.road.yishi.log.core.LogDetailInfo;
import com.road.yishi.log.core.LogMetaInfo;
import com.road.yishi.log.handler.Reducer;
import com.road.yishi.log.mgr.MessagePersiterMgr;
import com.road.yishi.log.mgr.TopicHandlerMappingMgr;
import com.road.yishi.log.servlet.service.ConsumerLogFactory;
import com.road.yishi.log.vo.LogKeyInfo;
public class AnalylizLogLocalReducer implements Reducer<LogMetaInfo, List<LogDetailInfo>> {
@Override
public void reduce(LogMetaInfo k, List<LogDetailInfo> v) {
try {
String topicName = TopicHandlerMappingMgr.getReducerTopicName(AnalylizLogLocalReducer.class.getName());
MessagePersiterMgr.persister(topicName, k.getKey(), v,(short) 0);
Map<LogKeyInfo,Integer> keyCountMap = ConsumerLogFactory.countMap.get(topicName);
if(keyCountMap == null){
keyCountMap = new HashMap<LogKeyInfo,Integer>();
ConsumerLogFactory.countMap.put(topicName, keyCountMap);
}
Integer count = keyCountMap.get(new LogKeyInfo(k.getKey()));
if(count == null){
count = 0 ;
}
keyCountMap.put(new LogKeyInfo(v.get(v.size()-1).getOccurDate(), k.getKey(), count+v.size()), count+v.size());
} catch (Exception e) {
Log.error("", e);
}
}
}
| 1,376 | 0.731105 | 0.728924 | 37 | 35.18919 | 30.506392 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.27027 | false | false | 13 |
99fe3391acc02c3238d6f70e455e1e2974fff448 | 7,937,099,610,198 | a6ffb34388cd2b00d1bbce3ba761d247711fc291 | /src/basesDeDatos/DeleteData.java | d94f740c7d248cfe692ddb1efcbe9d4331a4765d | []
| no_license | Amaiur13/AmaiurJon | https://github.com/Amaiur13/AmaiurJon | b8d722acfc5136864127833247de1f089cd14828 | 15e67910a21c162600fef664d0a3752a179b9605 | refs/heads/master | 2020-08-08T18:31:33.078000 | 2020-01-14T15:45:48 | 2020-01-14T15:45:48 | 213,621,709 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package basesDeDatos;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Contiene el metodo de borrar tuplas
*
*/
public class DeleteData
{
/**
* Metodo generico para borrar
* @param tabla en que tabla quieres borrar tuplas
* @param nombreAtributo el nombre del atributo en que te fijas para borrar
* @param valorAtributo valor del atributo
* @param conn
*/
public static void delete(String tabla, String nombreAtributo, String valorAtributo, Connection conn)
{
String sql = "DELETE FROM " + tabla + " WHERE " + nombreAtributo + " = ?";
try
(
PreparedStatement pstmt = conn.prepareStatement(sql)
)
{
// set the corresponding param
pstmt.setString(1, valorAtributo);
// execute the delete statement
pstmt.executeUpdate();
}
catch (SQLException e)
{
System.out.println(e.getMessage() + "falla delete");
}
}
}
| UTF-8 | Java | 1,113 | java | DeleteData.java | Java | []
| null | []
| package basesDeDatos;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Contiene el metodo de borrar tuplas
*
*/
public class DeleteData
{
/**
* Metodo generico para borrar
* @param tabla en que tabla quieres borrar tuplas
* @param nombreAtributo el nombre del atributo en que te fijas para borrar
* @param valorAtributo valor del atributo
* @param conn
*/
public static void delete(String tabla, String nombreAtributo, String valorAtributo, Connection conn)
{
String sql = "DELETE FROM " + tabla + " WHERE " + nombreAtributo + " = ?";
try
(
PreparedStatement pstmt = conn.prepareStatement(sql)
)
{
// set the corresponding param
pstmt.setString(1, valorAtributo);
// execute the delete statement
pstmt.executeUpdate();
}
catch (SQLException e)
{
System.out.println(e.getMessage() + "falla delete");
}
}
}
| 1,113 | 0.60018 | 0.599281 | 43 | 24.88372 | 25.865671 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.302326 | false | false | 13 |
b815527a7749d263b8cc76a44cdaca62de3e3722 | 6,021,544,174,186 | 25329f27032f446d9cbef28045888be36956069f | /BinaryStoreAdapters/src/main/java/com/binarystore/adapter/map/TreeMapBinaryAdapter.java | ca492e6d724186024eefaed3d105b7a7476247a2 | []
| no_license | DmitriySazonov/BinaryStore | https://github.com/DmitriySazonov/BinaryStore | 18dae1d8fd0c956e6681c591b540e68423a1e705 | c695a2c732c88867d15d726c969508a349fac185 | refs/heads/main | 2023-05-29T15:39:30.270000 | 2021-06-13T13:55:57 | 2021-06-13T13:55:57 | 354,616,997 | 3 | 0 | null | false | 2021-06-13T13:55:58 | 2021-04-04T18:24:40 | 2021-06-12T17:14:19 | 2021-06-13T13:55:57 | 602 | 3 | 0 | 0 | Java | false | false | package com.binarystore.adapter.map;
import com.binarystore.adapter.BinaryAdapterProvider;
import com.binarystore.adapter.DefaultAdapters;
import com.binarystore.adapter.Key;
import com.binarystore.buffer.ByteBuffer;
import java.util.TreeMap;
import javax.annotation.Nonnull;
@SuppressWarnings("rawtypes")
public class TreeMapBinaryAdapter extends AbstractMapBinaryAdapter<TreeMap> {
public static final Factory factory = new Factory();
private static final Key<?> KEY = DefaultAdapters.TREE_MAP;
protected TreeMapBinaryAdapter(
@Nonnull BinaryAdapterProvider provider,
@Nonnull MapSettings settings
) {
super(provider, settings);
}
@Nonnull
@Override
@SuppressWarnings("SortedCollectionWithNonComparableKeys")
protected TreeMap<?, ?> createMap(int size) {
return new TreeMap<>();
}
@Nonnull
@Override
public Key<?> key() {
return KEY;
}
private static class Factory extends MapFactory<TreeMap, TreeMapBinaryAdapter> {
@Override
public Key<?> adapterKey() {
return TreeMapBinaryAdapter.KEY;
}
@Override
protected TreeMapBinaryAdapter create(
@Nonnull BinaryAdapterProvider provider,
@Nonnull MapSettings settings
) {
return new TreeMapBinaryAdapter(provider, settings);
}
}
}
| UTF-8 | Java | 1,411 | java | TreeMapBinaryAdapter.java | Java | []
| null | []
| package com.binarystore.adapter.map;
import com.binarystore.adapter.BinaryAdapterProvider;
import com.binarystore.adapter.DefaultAdapters;
import com.binarystore.adapter.Key;
import com.binarystore.buffer.ByteBuffer;
import java.util.TreeMap;
import javax.annotation.Nonnull;
@SuppressWarnings("rawtypes")
public class TreeMapBinaryAdapter extends AbstractMapBinaryAdapter<TreeMap> {
public static final Factory factory = new Factory();
private static final Key<?> KEY = DefaultAdapters.TREE_MAP;
protected TreeMapBinaryAdapter(
@Nonnull BinaryAdapterProvider provider,
@Nonnull MapSettings settings
) {
super(provider, settings);
}
@Nonnull
@Override
@SuppressWarnings("SortedCollectionWithNonComparableKeys")
protected TreeMap<?, ?> createMap(int size) {
return new TreeMap<>();
}
@Nonnull
@Override
public Key<?> key() {
return KEY;
}
private static class Factory extends MapFactory<TreeMap, TreeMapBinaryAdapter> {
@Override
public Key<?> adapterKey() {
return TreeMapBinaryAdapter.KEY;
}
@Override
protected TreeMapBinaryAdapter create(
@Nonnull BinaryAdapterProvider provider,
@Nonnull MapSettings settings
) {
return new TreeMapBinaryAdapter(provider, settings);
}
}
}
| 1,411 | 0.676825 | 0.676825 | 53 | 25.622641 | 23.068583 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.377358 | false | false | 13 |
b1b90adf3cf979387146c387b1e840b9b36458d8 | 35,691,178,233,826 | 88ec5772f3e7462fb243c6dcf03f29ffe12f9ede | /src/main/java/com/kharkiv/diploma/dao/OrganicRefererDao.java | 6196080786256bfaed37e1b730b078cf3da1b523 | []
| no_license | activecs/analytics | https://github.com/activecs/analytics | 86853b014d68c9675e014077a450c6afd2d8c3b9 | ac0ac2838162143a9fa55aa7ecc03b4ec9742579 | refs/heads/master | 2021-01-19T02:11:30.585000 | 2016-07-29T19:23:47 | 2016-07-29T19:23:47 | 32,212,037 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kharkiv.diploma.dao;
import java.util.List;
import com.kharkiv.diploma.dto.analytics.OrganicReferer;
public interface OrganicRefererDao {
List<OrganicReferer> getAll();
}
| UTF-8 | Java | 189 | java | OrganicRefererDao.java | Java | []
| null | []
| package com.kharkiv.diploma.dao;
import java.util.List;
import com.kharkiv.diploma.dto.analytics.OrganicReferer;
public interface OrganicRefererDao {
List<OrganicReferer> getAll();
}
| 189 | 0.793651 | 0.793651 | 11 | 16.181818 | 19.120756 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 13 |
f48410ec2a1ce37f194fbcd00f31c6c8ea34705d | 35,691,178,235,030 | 2e357a379b0c0352ab92aba0af99f09ffbcecd11 | /app/src/main/java/br/com/douglas/flat/view/fragments/PaymentDetailFragment.java | 598bb0f0fd536b54189c6888d38fff39e78977f9 | []
| no_license | douglas-queiroz/MyControlMobile | https://github.com/douglas-queiroz/MyControlMobile | a3412670ecdc285a788c0a93e23b11e0ded0a97b | f03b20cc586bf8aa700aaf91cc5b6df8f5e238a0 | refs/heads/master | 2021-01-10T12:19:33.550000 | 2015-01-30T12:34:13 | 2015-01-30T12:34:13 | 46,717,749 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.douglas.flat.view.fragments;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import br.com.douglas.flat.R;
import br.com.douglas.flat.helper.DateHelper;
import br.com.douglas.flat.helper.NumberHelper;
import br.com.douglas.flat.model.Payment;
import br.com.douglas.flat.service.PaymentService;
import br.com.douglas.flat.view.activity.PaymentActivity;
public class PaymentDetailFragment extends Fragment {
public static final String ARG_PAYMENT = "payment";
private Payment mPayment;
private PaymentService service;
private TextView txtClient;
private TextView txtDate;
private TextView txtValue;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPayment = (Payment) getArguments().getSerializable(ARG_PAYMENT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_payment_detail, container, false);
txtClient = (TextView) view.findViewById(R.id.txt_client);
txtDate = (TextView) view.findViewById(R.id.txt_date);
txtValue = (TextView) view.findViewById(R.id.txt_value);
service = new PaymentService(getActivity());
loadInformations();
return view;
}
private void loadInformations(){
txtClient.setText(mPayment.getClient().toString());
txtDate.setText(DateHelper.getStringBr(mPayment.getDate()));
txtValue.setText("R$ " + NumberHelper.parseString(mPayment.getValue()));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_client_detail, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_edit) {
Intent intent = new Intent(getActivity(), PaymentActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(PaymentActivity.ARG_PAYMENT, mPayment);
intent.putExtras(bundle);
startActivity(intent);
return true;
}else if(id == R.id.action_delete){
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
builder.setMessage("Deseja realemnte excluir o pagamento do cliente " + mPayment.getClient() + "?")
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
service.delete(mPayment);
getActivity().onBackPressed();
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
})
.setTitle("Atenção");
// Create the AlertDialog object and return it
builder.create().show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
mPayment = service.get(mPayment.getId());
loadInformations();
super.onResume();
}
}
| UTF-8 | Java | 4,142 | java | PaymentDetailFragment.java | Java | []
| null | []
| package br.com.douglas.flat.view.fragments;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import br.com.douglas.flat.R;
import br.com.douglas.flat.helper.DateHelper;
import br.com.douglas.flat.helper.NumberHelper;
import br.com.douglas.flat.model.Payment;
import br.com.douglas.flat.service.PaymentService;
import br.com.douglas.flat.view.activity.PaymentActivity;
public class PaymentDetailFragment extends Fragment {
public static final String ARG_PAYMENT = "payment";
private Payment mPayment;
private PaymentService service;
private TextView txtClient;
private TextView txtDate;
private TextView txtValue;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPayment = (Payment) getArguments().getSerializable(ARG_PAYMENT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_payment_detail, container, false);
txtClient = (TextView) view.findViewById(R.id.txt_client);
txtDate = (TextView) view.findViewById(R.id.txt_date);
txtValue = (TextView) view.findViewById(R.id.txt_value);
service = new PaymentService(getActivity());
loadInformations();
return view;
}
private void loadInformations(){
txtClient.setText(mPayment.getClient().toString());
txtDate.setText(DateHelper.getStringBr(mPayment.getDate()));
txtValue.setText("R$ " + NumberHelper.parseString(mPayment.getValue()));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_client_detail, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_edit) {
Intent intent = new Intent(getActivity(), PaymentActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(PaymentActivity.ARG_PAYMENT, mPayment);
intent.putExtras(bundle);
startActivity(intent);
return true;
}else if(id == R.id.action_delete){
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
builder.setMessage("Deseja realemnte excluir o pagamento do cliente " + mPayment.getClient() + "?")
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
service.delete(mPayment);
getActivity().onBackPressed();
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
})
.setTitle("Atenção");
// Create the AlertDialog object and return it
builder.create().show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
mPayment = service.get(mPayment.getId());
loadInformations();
super.onResume();
}
}
| 4,142 | 0.643961 | 0.64372 | 118 | 34.084747 | 26.926321 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584746 | false | false | 13 |
9018284c931b00a1054561a1b90d8a71da3ae3e3 | 23,072,564,374,296 | e686f435f7a024dd0f9b1ea373f4dda1cd921341 | /src/unitTests/HandValueTest.java | b10ffc1fda26ea55749d1c23a70da0a39f943ea2 | []
| no_license | joaoapaenas/poker | https://github.com/joaoapaenas/poker | fb229cb3bb8d6b4b38dc4bea19211b9398468452 | 0c24975e47ea470df07ca92fad3c21590e7e787b | refs/heads/master | 2020-06-01T17:57:13.703000 | 2015-06-12T13:13:03 | 2015-06-12T13:13:03 | 32,323,722 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package unitTests;
import junit.framework.TestCase;
import org.junit.Test;
import org.ozsoft.texasholdem.Card;
import org.ozsoft.texasholdem.Hand;
import org.ozsoft.texasholdem.HandValue;
import static org.junit.Assert.*;
/**
* Created by matheus on 6/6/15.
*/
public class HandValueTest extends TestCase {
@Test
public void testEquals() throws Exception {
Hand handA = new Hand();
Hand handB = new Hand();
Card card = new Card(0,0);
handA.addCard(card);
handB.addCard(card);
HandValue handValueA = new HandValue(handA);
HandValue handValueB = new HandValue(handB);
assertEquals(true, handValueA.equals(handValueB));
}
} | UTF-8 | Java | 704 | java | HandValueTest.java | Java | [
{
"context": "port static org.junit.Assert.*;\n\n/**\n * Created by matheus on 6/6/15.\n */\npublic class HandValueTest extends",
"end": 250,
"score": 0.999525785446167,
"start": 243,
"tag": "USERNAME",
"value": "matheus"
}
]
| null | []
| package unitTests;
import junit.framework.TestCase;
import org.junit.Test;
import org.ozsoft.texasholdem.Card;
import org.ozsoft.texasholdem.Hand;
import org.ozsoft.texasholdem.HandValue;
import static org.junit.Assert.*;
/**
* Created by matheus on 6/6/15.
*/
public class HandValueTest extends TestCase {
@Test
public void testEquals() throws Exception {
Hand handA = new Hand();
Hand handB = new Hand();
Card card = new Card(0,0);
handA.addCard(card);
handB.addCard(card);
HandValue handValueA = new HandValue(handA);
HandValue handValueB = new HandValue(handB);
assertEquals(true, handValueA.equals(handValueB));
}
} | 704 | 0.678977 | 0.670455 | 29 | 23.310345 | 18.699259 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586207 | false | false | 13 |
b6f60e721fafb70befe0ba6649e6cf55fd26534e | 32,195,074,854,221 | a815bd3fa523968cf88347dcce461b84e1a3d3f4 | /Android/history/Task_Android/code/Chuangyiyun/app/src/main/java/com/lht/cloudjob/fragment/FgDemandRequire.java | 3401960c6f4fd96d597ea13523c6e867b2eaf331 | []
| no_license | leobert-lan/My-Document | https://github.com/leobert-lan/My-Document | 7fa2563a865c3e8f4a0f368d14d3dceecc3edd05 | d1396c1b64b7dbe5c923874349fa6b9fbd2043ce | refs/heads/master | 2021-01-20T20:15:28.984000 | 2018-02-09T03:03:22 | 2018-02-09T03:03:22 | 60,241,501 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lht.cloudjob.fragment;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ScrollView;
import android.widget.TextView;
import com.lht.cloudjob.Event.AppEvent;
import com.lht.cloudjob.R;
import com.lht.cloudjob.activity.BaseActivity;
import com.lht.cloudjob.adapter.ListAdapter2;
import com.lht.cloudjob.adapter.viewprovider.FilesAttachmentProviderImpl;
import com.lht.cloudjob.adapter.viewprovider.ImagesAttachmentProviderImpl;
import com.lht.cloudjob.customview.ConflictListView;
import com.lht.cloudjob.customview.CustomDialog;
import com.lht.cloudjob.customview.CustomPopupWindow;
import com.lht.cloudjob.customview.CustomProgressView;
import com.lht.cloudjob.customview.RoundImageView;
import com.lht.cloudjob.interfaces.IVerifyHolder;
import com.lht.cloudjob.mvp.model.bean.DemandInfoResBean;
import com.lht.cloudjob.mvp.model.pojo.LoginInfo;
import com.lht.cloudjob.mvp.model.pojo.PreviewFileEntity;
import com.lht.cloudjob.mvp.presenter.DemandRequireFragmentPresenter;
import com.lht.cloudjob.mvp.viewinterface.IActivityAsyncProtected;
import com.lht.cloudjob.mvp.viewinterface.IDemandRequireFragment;
import com.lht.cloudjob.util.file.FileUtils;
import com.lht.cloudjob.util.file.PreviewUtils;
import com.lht.cloudjob.util.string.StringUtil;
import com.lht.cloudjob.util.time.TimeUtil;
import com.lht.customwidgetlib.list.HorizontalListView;
import com.lht.customwidgetlib.nestedscroll.AttachUtil;
import com.squareup.picasso.Picasso;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class FgDemandRequire extends BaseFragment implements IDemandRequireFragment, IVerifyHolder {
private static final String PAGENAME = "FgDemandRequire";
private DemandInfoResBean demandInfoResBean;
private TextView tvRequirements;
private TextView hintAttachment;
private TextView tvName;
private RoundImageView imgAvatar;
// private TextView tvContact;
private TextView tvRegisterTime;
private CheckBox cbFollow;
private ScrollView scrollView;
private DemandRequireFragmentPresenter presenter;
private IActivityAsyncProtected parent;
private HorizontalListView hlvImages;
private ConflictListView clvFiles;
private ListAdapter2<DemandInfoResBean.AttachmentExt> imageAdapter;
private ListAdapter2<DemandInfoResBean.AttachmentExt> fileAdapter;
public FgDemandRequire() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
@Override
protected String getPageName() {
return PAGENAME;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fg_demand_require, container, false);
initView(view);
initVariable();
initEvent();
return view;
}
protected void initView(View view) {
scrollView = (ScrollView) view.findViewById(R.id.fgdr_sv);
tvRequirements = (TextView) view.findViewById(R.id.fgdr_tv_requirement);
hintAttachment = (TextView) view.findViewById(R.id.hint_attachment);
imgAvatar = (RoundImageView) view.findViewById(R.id.fgdr_img_publisher_avatar);
tvName = (TextView) view.findViewById(R.id.fgdr_tv_publisher_name);
// tvContact = (TextView) view.findViewById(R.id.fgdr_tv_publisher_contact);
tvRegisterTime = (TextView) view.findViewById(R.id.fgdr_tv_publisher_registertime);
cbFollow = (CheckBox) view.findViewById(R.id.fgdr_btn_follow);
hlvImages = (HorizontalListView) view.findViewById(R.id.fgdr_attachments_imgs);
clvFiles = (ConflictListView) view.findViewById(R.id.fgdr_attachments_files);
}
protected void initVariable() {
parent = (IActivityAsyncProtected) getActivity();
presenter = new DemandRequireFragmentPresenter(this);
presenter.setLoginStatus(!StringUtil.isEmpty(mLoginInfo.getUsername()));
ImagesAttachmentProviderImpl imagesItemViewProvider =
new ImagesAttachmentProviderImpl(getActivity().getLayoutInflater(), imgItemCustomor);
imageAdapter =
new ListAdapter2<>(new ArrayList<DemandInfoResBean.AttachmentExt>(), imagesItemViewProvider);
FilesAttachmentProviderImpl filesItemViewProvider =
new FilesAttachmentProviderImpl(getActivity().getLayoutInflater(), fileItemCustomor);
fileAdapter =
new ListAdapter2<>(new ArrayList<DemandInfoResBean.AttachmentExt>(), filesItemViewProvider);
}
protected void initEvent() {
hlvImages.setAdapter(imageAdapter);
clvFiles.setAdapter(fileAdapter);
clvFiles.setDividerHeight(0);
cbFollow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!cbFollow.isChecked()) {
//if has followed ,click will change the state_check to false,and we should
// do unfollow
presenter.callUnFollowPublisher(mLoginInfo.getUsername(), getPublisher());
} else {
presenter.callFollowPublisher(mLoginInfo.getUsername(), getPublisher());
}
}
});
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean isTopArrived = AttachUtil.isScrollViewAttach(scrollView);
EventBus.getDefault().post(new AppEvent.NestedContentScrollEvent(isTopArrived));
return false;
}
});
}
private void initFollow() {
if (!StringUtil.isEmpty(mLoginInfo.getUsername())) {
if (mLoginInfo.getUsername().equals(getPublisher())) {
cbFollow.setVisibility(View.GONE);
} else {
cbFollow.setVisibility(View.VISIBLE);
}
} else {
cbFollow.setVisibility(View.VISIBLE);
}
}
public DemandInfoResBean getDemandInfoResBean() {
if (demandInfoResBean == null) {
demandInfoResBean = new DemandInfoResBean();
}
return demandInfoResBean;
}
public void setDemandInfoResBean(DemandInfoResBean demandInfoResBean) {
this.demandInfoResBean = demandInfoResBean;
if (isResumed()) {
updateView();
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
onPause();
} else {
onResume();
}
}
@Override
public void onResume() {
super.onResume();
updateView();
}
/**
* 更新视图内容
*/
private void updateView() {
DemandInfoResBean bean = getDemandInfoResBean();
tvRequirements.setText(bean.getDescription());
initFollow();
ArrayList<DemandInfoResBean.AttachmentExt> attachments = bean.getAttachment();
updateAttachments(attachments);
DemandInfoResBean.Publisher publisher = bean.getPublisher();
if (publisher == null) {
publisher = new DemandInfoResBean.Publisher();
}
Picasso.with(getActivity()).load(publisher.getAvatar()).diskCache(BaseActivity
.getLocalImageCache()).placeholder(R.drawable.v1010_drawable_avatar_default)
.error(R.drawable.v1010_drawable_avatar_default).fit().into(imgAvatar);
tvName.setText(publisher.getNickname());
// String _contact = new StringBuilder().append(getString(R.string.v1010_default_fgdemandrequire_contact)).append(publisher.getNickname()).toString();
// tvContact.setText(_contact);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
String _createTime = TimeUtil.getTime(bean.getCreate_time(), format);
tvRegisterTime.setText(_createTime);
DemandInfoResBean.Favored favored = bean.getFavored();
if (favored == null) {
favored = new DemandInfoResBean.Favored();
}
setPublisherFollowed(favored.isPublisher());
}
/**
* @param attachments
*/
private void updateAttachments(ArrayList<DemandInfoResBean.AttachmentExt> attachments) {
if (attachments != null) {
if (attachments.size() != 0) {
hintAttachment.setVisibility(View.VISIBLE);
ArrayList<DemandInfoResBean.AttachmentExt> images = PreviewUtils.filterImageTypedWithoutGif(attachments);
ArrayList<DemandInfoResBean.AttachmentExt> files = PreviewUtils.filterFileTyped(attachments);
if (images.size() != 0) {
imageAdapter.setLiData(images);
} else {
hlvImages.setVisibility(View.GONE);
}
if (files.size() != 0) {
fileAdapter.setLiData(files);
} else {
clvFiles.setVisibility(View.GONE);
}
// TODO: 2016/11/9 test
// fileAdapter.setLiData(files);
} else {
hintAttachment.setVisibility(View.GONE);
hlvImages.setVisibility(View.GONE);
clvFiles.setVisibility(View.GONE);
}
}
}
/**
* desc: 主线程回调登录成功
* 需要处理:成员对象的更新、界面的更新
*
* @param event 登录成功事件,包含信息
*/
@Override
@Subscribe
public void onEventMainThread(AppEvent.LoginSuccessEvent event) {
mLoginInfo.copy(event.getLoginInfo());
presenter.setLoginStatus(!StringUtil.isEmpty(mLoginInfo.getUsername()));
presenter.identifyTrigger(event.getTrigger());
}
/**
* desc: 未进行登录的事件订阅
*
* @param event 手动关闭登录页事件
*/
@Override
@Subscribe
public void onEventMainThread(AppEvent.LoginCancelEvent event) {
presenter.identifyCanceledTrigger(event.getTrigger());
}
@Override
public LoginInfo getLoginInfo() {
return mLoginInfo;
}
/**
* desc: 显示等待窗
*
* @param isProtectNeed 是否需要屏幕防击穿保护
*/
@Override
public void showWaitView(boolean isProtectNeed) {
parent.showWaitView(isProtectNeed);
}
/**
* desc: 取消等待窗
*/
@Override
public void cancelWaitView() {
parent.cancelWaitView();
}
@Override
public Resources getAppResource() {
return getResources();
}
@Override
public void showMsg(String msg) {
parent.showMsg(msg);
}
@Override
public void showErrorMsg(String msg) {
parent.showMsg(msg);
}
@Override
public String getPublisher() {
return getDemandInfoResBean().getUsername();
}
@Override
public void setPublisherFollowed(boolean isFollowed) {
cbFollow.setChecked(isFollowed);
if (!isFollowed) {
cbFollow.setText(R.string.v1010_default_demandinfo_text_follow);
} else {
cbFollow.setText(R.string.v1010_default_demandinfo_text_unfollow);
}
}
private CustomProgressView customProgressView;
@Override
public void showPreviewProgress(PreviewFileEntity entity) {
customProgressView = new CustomProgressView(parent.getActivity());
customProgressView.show();
customProgressView.setProgress(0, 100);
}
@Override
public void hidePreviewProgress() {
if (customProgressView == null) {
//todo log
return;
}
customProgressView.dismiss();
customProgressView = null;
}
@Override
public void UpdateProgress(PreviewFileEntity entity, long current, long total) {
if (customProgressView == null) {
// TODO: 2016/11/7 log
return;
}
if (!customProgressView.isShowing()) {
customProgressView.show();
}
customProgressView.setProgress(current, total);
}
@Override
public void showMobileDownloadAlert(CustomPopupWindow.OnPositiveClickListener onPositiveClickListener) {
CustomDialog dialog = new CustomDialog(parent.getActivity());
dialog.setContent(R.string.v1020_dialog_download_onmobile);
dialog.setNegativeButton(R.string.v1020_dialog_nbtn_onmobile);
dialog.setPositiveButton(R.string.v1020_dialog_pbtn_onmobile);
dialog.setPositiveClickListener(onPositiveClickListener);
dialog.show();
}
@Override
public void showLargeSizeDownloadAlert(long fileSize, CustomPopupWindow.OnPositiveClickListener onPositiveClickListener) {
CustomDialog dialog = new CustomDialog(parent.getActivity());
final String format = getString(R.string.v1020_dialog_preview_onmobile_toolarge);
dialog.setContent(String.format(Locale.ENGLISH, format, FileUtils.calcSize(fileSize)));
dialog.setNegativeButton(R.string.v1020_dialog_nbtn_onmobile);
dialog.setPositiveButton(R.string.v1020_dialog_pbtn_onmobile);
dialog.setPositiveClickListener(onPositiveClickListener);
dialog.show();
}
private ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt,
ImagesAttachmentProviderImpl.ViewHolder> imgItemCustomor =
new ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt, ImagesAttachmentProviderImpl.ViewHolder>() {
public void customize(final int position, DemandInfoResBean.AttachmentExt data, View convertView, ImagesAttachmentProviderImpl.ViewHolder viewHolder) {
Picasso.with(getActivity()).load(data.getUrl_thumbnail()).diskCache(BaseActivity
.getLocalImageCache()).placeholder(R.drawable.v1011_drawable_work_default)
.error(R.drawable.v1011_drawable_work_error).fit().into(viewHolder.ivImageAttachment);
viewHolder.ivImageAttachment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.callPreviewImage(imageAdapter.getAll(), position);
}
});
}
};
private ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt,
FilesAttachmentProviderImpl.ViewHolder> fileItemCustomor =
new ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt, FilesAttachmentProviderImpl.ViewHolder>() {
@Override
public void customize(final int position, final DemandInfoResBean.AttachmentExt data, View convertView, FilesAttachmentProviderImpl.ViewHolder viewHolder) {
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.callPreviewFile(getDemandId(), data);
}
});
}
};
private String getDemandId() {
if (demandInfoResBean == null) {
return null;
}
return demandInfoResBean.getTask_bn();
}
public void cancelPreview() {
if (presenter != null) {
presenter.doCancelDownload();
}
}
} | UTF-8 | Java | 16,283 | java | FgDemandRequire.java | Java | []
| null | []
| package com.lht.cloudjob.fragment;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ScrollView;
import android.widget.TextView;
import com.lht.cloudjob.Event.AppEvent;
import com.lht.cloudjob.R;
import com.lht.cloudjob.activity.BaseActivity;
import com.lht.cloudjob.adapter.ListAdapter2;
import com.lht.cloudjob.adapter.viewprovider.FilesAttachmentProviderImpl;
import com.lht.cloudjob.adapter.viewprovider.ImagesAttachmentProviderImpl;
import com.lht.cloudjob.customview.ConflictListView;
import com.lht.cloudjob.customview.CustomDialog;
import com.lht.cloudjob.customview.CustomPopupWindow;
import com.lht.cloudjob.customview.CustomProgressView;
import com.lht.cloudjob.customview.RoundImageView;
import com.lht.cloudjob.interfaces.IVerifyHolder;
import com.lht.cloudjob.mvp.model.bean.DemandInfoResBean;
import com.lht.cloudjob.mvp.model.pojo.LoginInfo;
import com.lht.cloudjob.mvp.model.pojo.PreviewFileEntity;
import com.lht.cloudjob.mvp.presenter.DemandRequireFragmentPresenter;
import com.lht.cloudjob.mvp.viewinterface.IActivityAsyncProtected;
import com.lht.cloudjob.mvp.viewinterface.IDemandRequireFragment;
import com.lht.cloudjob.util.file.FileUtils;
import com.lht.cloudjob.util.file.PreviewUtils;
import com.lht.cloudjob.util.string.StringUtil;
import com.lht.cloudjob.util.time.TimeUtil;
import com.lht.customwidgetlib.list.HorizontalListView;
import com.lht.customwidgetlib.nestedscroll.AttachUtil;
import com.squareup.picasso.Picasso;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class FgDemandRequire extends BaseFragment implements IDemandRequireFragment, IVerifyHolder {
private static final String PAGENAME = "FgDemandRequire";
private DemandInfoResBean demandInfoResBean;
private TextView tvRequirements;
private TextView hintAttachment;
private TextView tvName;
private RoundImageView imgAvatar;
// private TextView tvContact;
private TextView tvRegisterTime;
private CheckBox cbFollow;
private ScrollView scrollView;
private DemandRequireFragmentPresenter presenter;
private IActivityAsyncProtected parent;
private HorizontalListView hlvImages;
private ConflictListView clvFiles;
private ListAdapter2<DemandInfoResBean.AttachmentExt> imageAdapter;
private ListAdapter2<DemandInfoResBean.AttachmentExt> fileAdapter;
public FgDemandRequire() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
@Override
protected String getPageName() {
return PAGENAME;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fg_demand_require, container, false);
initView(view);
initVariable();
initEvent();
return view;
}
protected void initView(View view) {
scrollView = (ScrollView) view.findViewById(R.id.fgdr_sv);
tvRequirements = (TextView) view.findViewById(R.id.fgdr_tv_requirement);
hintAttachment = (TextView) view.findViewById(R.id.hint_attachment);
imgAvatar = (RoundImageView) view.findViewById(R.id.fgdr_img_publisher_avatar);
tvName = (TextView) view.findViewById(R.id.fgdr_tv_publisher_name);
// tvContact = (TextView) view.findViewById(R.id.fgdr_tv_publisher_contact);
tvRegisterTime = (TextView) view.findViewById(R.id.fgdr_tv_publisher_registertime);
cbFollow = (CheckBox) view.findViewById(R.id.fgdr_btn_follow);
hlvImages = (HorizontalListView) view.findViewById(R.id.fgdr_attachments_imgs);
clvFiles = (ConflictListView) view.findViewById(R.id.fgdr_attachments_files);
}
protected void initVariable() {
parent = (IActivityAsyncProtected) getActivity();
presenter = new DemandRequireFragmentPresenter(this);
presenter.setLoginStatus(!StringUtil.isEmpty(mLoginInfo.getUsername()));
ImagesAttachmentProviderImpl imagesItemViewProvider =
new ImagesAttachmentProviderImpl(getActivity().getLayoutInflater(), imgItemCustomor);
imageAdapter =
new ListAdapter2<>(new ArrayList<DemandInfoResBean.AttachmentExt>(), imagesItemViewProvider);
FilesAttachmentProviderImpl filesItemViewProvider =
new FilesAttachmentProviderImpl(getActivity().getLayoutInflater(), fileItemCustomor);
fileAdapter =
new ListAdapter2<>(new ArrayList<DemandInfoResBean.AttachmentExt>(), filesItemViewProvider);
}
protected void initEvent() {
hlvImages.setAdapter(imageAdapter);
clvFiles.setAdapter(fileAdapter);
clvFiles.setDividerHeight(0);
cbFollow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!cbFollow.isChecked()) {
//if has followed ,click will change the state_check to false,and we should
// do unfollow
presenter.callUnFollowPublisher(mLoginInfo.getUsername(), getPublisher());
} else {
presenter.callFollowPublisher(mLoginInfo.getUsername(), getPublisher());
}
}
});
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean isTopArrived = AttachUtil.isScrollViewAttach(scrollView);
EventBus.getDefault().post(new AppEvent.NestedContentScrollEvent(isTopArrived));
return false;
}
});
}
private void initFollow() {
if (!StringUtil.isEmpty(mLoginInfo.getUsername())) {
if (mLoginInfo.getUsername().equals(getPublisher())) {
cbFollow.setVisibility(View.GONE);
} else {
cbFollow.setVisibility(View.VISIBLE);
}
} else {
cbFollow.setVisibility(View.VISIBLE);
}
}
public DemandInfoResBean getDemandInfoResBean() {
if (demandInfoResBean == null) {
demandInfoResBean = new DemandInfoResBean();
}
return demandInfoResBean;
}
public void setDemandInfoResBean(DemandInfoResBean demandInfoResBean) {
this.demandInfoResBean = demandInfoResBean;
if (isResumed()) {
updateView();
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
onPause();
} else {
onResume();
}
}
@Override
public void onResume() {
super.onResume();
updateView();
}
/**
* 更新视图内容
*/
private void updateView() {
DemandInfoResBean bean = getDemandInfoResBean();
tvRequirements.setText(bean.getDescription());
initFollow();
ArrayList<DemandInfoResBean.AttachmentExt> attachments = bean.getAttachment();
updateAttachments(attachments);
DemandInfoResBean.Publisher publisher = bean.getPublisher();
if (publisher == null) {
publisher = new DemandInfoResBean.Publisher();
}
Picasso.with(getActivity()).load(publisher.getAvatar()).diskCache(BaseActivity
.getLocalImageCache()).placeholder(R.drawable.v1010_drawable_avatar_default)
.error(R.drawable.v1010_drawable_avatar_default).fit().into(imgAvatar);
tvName.setText(publisher.getNickname());
// String _contact = new StringBuilder().append(getString(R.string.v1010_default_fgdemandrequire_contact)).append(publisher.getNickname()).toString();
// tvContact.setText(_contact);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
String _createTime = TimeUtil.getTime(bean.getCreate_time(), format);
tvRegisterTime.setText(_createTime);
DemandInfoResBean.Favored favored = bean.getFavored();
if (favored == null) {
favored = new DemandInfoResBean.Favored();
}
setPublisherFollowed(favored.isPublisher());
}
/**
* @param attachments
*/
private void updateAttachments(ArrayList<DemandInfoResBean.AttachmentExt> attachments) {
if (attachments != null) {
if (attachments.size() != 0) {
hintAttachment.setVisibility(View.VISIBLE);
ArrayList<DemandInfoResBean.AttachmentExt> images = PreviewUtils.filterImageTypedWithoutGif(attachments);
ArrayList<DemandInfoResBean.AttachmentExt> files = PreviewUtils.filterFileTyped(attachments);
if (images.size() != 0) {
imageAdapter.setLiData(images);
} else {
hlvImages.setVisibility(View.GONE);
}
if (files.size() != 0) {
fileAdapter.setLiData(files);
} else {
clvFiles.setVisibility(View.GONE);
}
// TODO: 2016/11/9 test
// fileAdapter.setLiData(files);
} else {
hintAttachment.setVisibility(View.GONE);
hlvImages.setVisibility(View.GONE);
clvFiles.setVisibility(View.GONE);
}
}
}
/**
* desc: 主线程回调登录成功
* 需要处理:成员对象的更新、界面的更新
*
* @param event 登录成功事件,包含信息
*/
@Override
@Subscribe
public void onEventMainThread(AppEvent.LoginSuccessEvent event) {
mLoginInfo.copy(event.getLoginInfo());
presenter.setLoginStatus(!StringUtil.isEmpty(mLoginInfo.getUsername()));
presenter.identifyTrigger(event.getTrigger());
}
/**
* desc: 未进行登录的事件订阅
*
* @param event 手动关闭登录页事件
*/
@Override
@Subscribe
public void onEventMainThread(AppEvent.LoginCancelEvent event) {
presenter.identifyCanceledTrigger(event.getTrigger());
}
@Override
public LoginInfo getLoginInfo() {
return mLoginInfo;
}
/**
* desc: 显示等待窗
*
* @param isProtectNeed 是否需要屏幕防击穿保护
*/
@Override
public void showWaitView(boolean isProtectNeed) {
parent.showWaitView(isProtectNeed);
}
/**
* desc: 取消等待窗
*/
@Override
public void cancelWaitView() {
parent.cancelWaitView();
}
@Override
public Resources getAppResource() {
return getResources();
}
@Override
public void showMsg(String msg) {
parent.showMsg(msg);
}
@Override
public void showErrorMsg(String msg) {
parent.showMsg(msg);
}
@Override
public String getPublisher() {
return getDemandInfoResBean().getUsername();
}
@Override
public void setPublisherFollowed(boolean isFollowed) {
cbFollow.setChecked(isFollowed);
if (!isFollowed) {
cbFollow.setText(R.string.v1010_default_demandinfo_text_follow);
} else {
cbFollow.setText(R.string.v1010_default_demandinfo_text_unfollow);
}
}
private CustomProgressView customProgressView;
@Override
public void showPreviewProgress(PreviewFileEntity entity) {
customProgressView = new CustomProgressView(parent.getActivity());
customProgressView.show();
customProgressView.setProgress(0, 100);
}
@Override
public void hidePreviewProgress() {
if (customProgressView == null) {
//todo log
return;
}
customProgressView.dismiss();
customProgressView = null;
}
@Override
public void UpdateProgress(PreviewFileEntity entity, long current, long total) {
if (customProgressView == null) {
// TODO: 2016/11/7 log
return;
}
if (!customProgressView.isShowing()) {
customProgressView.show();
}
customProgressView.setProgress(current, total);
}
@Override
public void showMobileDownloadAlert(CustomPopupWindow.OnPositiveClickListener onPositiveClickListener) {
CustomDialog dialog = new CustomDialog(parent.getActivity());
dialog.setContent(R.string.v1020_dialog_download_onmobile);
dialog.setNegativeButton(R.string.v1020_dialog_nbtn_onmobile);
dialog.setPositiveButton(R.string.v1020_dialog_pbtn_onmobile);
dialog.setPositiveClickListener(onPositiveClickListener);
dialog.show();
}
@Override
public void showLargeSizeDownloadAlert(long fileSize, CustomPopupWindow.OnPositiveClickListener onPositiveClickListener) {
CustomDialog dialog = new CustomDialog(parent.getActivity());
final String format = getString(R.string.v1020_dialog_preview_onmobile_toolarge);
dialog.setContent(String.format(Locale.ENGLISH, format, FileUtils.calcSize(fileSize)));
dialog.setNegativeButton(R.string.v1020_dialog_nbtn_onmobile);
dialog.setPositiveButton(R.string.v1020_dialog_pbtn_onmobile);
dialog.setPositiveClickListener(onPositiveClickListener);
dialog.show();
}
private ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt,
ImagesAttachmentProviderImpl.ViewHolder> imgItemCustomor =
new ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt, ImagesAttachmentProviderImpl.ViewHolder>() {
public void customize(final int position, DemandInfoResBean.AttachmentExt data, View convertView, ImagesAttachmentProviderImpl.ViewHolder viewHolder) {
Picasso.with(getActivity()).load(data.getUrl_thumbnail()).diskCache(BaseActivity
.getLocalImageCache()).placeholder(R.drawable.v1011_drawable_work_default)
.error(R.drawable.v1011_drawable_work_error).fit().into(viewHolder.ivImageAttachment);
viewHolder.ivImageAttachment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.callPreviewImage(imageAdapter.getAll(), position);
}
});
}
};
private ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt,
FilesAttachmentProviderImpl.ViewHolder> fileItemCustomor =
new ListAdapter2.ICustomizeListItem2<DemandInfoResBean.AttachmentExt, FilesAttachmentProviderImpl.ViewHolder>() {
@Override
public void customize(final int position, final DemandInfoResBean.AttachmentExt data, View convertView, FilesAttachmentProviderImpl.ViewHolder viewHolder) {
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.callPreviewFile(getDemandId(), data);
}
});
}
};
private String getDemandId() {
if (demandInfoResBean == null) {
return null;
}
return demandInfoResBean.getTask_bn();
}
public void cancelPreview() {
if (presenter != null) {
presenter.doCancelDownload();
}
}
} | 16,283 | 0.658393 | 0.652932 | 462 | 33.883118 | 31.186275 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.467532 | false | false | 13 |
922f3ad2ce803394cf4e687cdffe9c15a0b4f86c | 10,771,778,005,507 | 57b6f59198af2c54976f2d596376df97a535aad1 | /src/main/java/com/ljy/sbtemplate/util/DateUtil.java | 184401e423bbe1a719cb5ae66284d340cf78c3cb | []
| no_license | Lokiyor/sb-template | https://github.com/Lokiyor/sb-template | ee3a64494c43c276c8f621184288e387bbb6674f | 899b98f5e939b261239aaa232070d73a78dfdc91 | refs/heads/master | 2022-11-30T10:23:09.433000 | 2020-02-17T13:05:53 | 2020-02-17T13:05:53 | 170,453,223 | 0 | 0 | null | false | 2022-11-16T11:38:49 | 2019-02-13T06:28:41 | 2020-02-17T13:07:40 | 2022-11-16T11:38:46 | 93 | 0 | 0 | 9 | Java | false | false | package com.ljy.sbtemplate.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
/**
* @author Lokiy
* @date 2018/6/7
* @description jre8日期帮助类
* 需要其他的方法自行添加
*/
public class DateUtil {
private static final Logger log = LogManager.getLogger();
/**
* 秒
*/
public static final long SECOND_MILLI = 1000;
/**
* 分
*/
public static final long MINUTE_MILLI = 60 * 1000;
/**
* 时
*/
public static final long HOUR_MILLI = 60 * 60 * 1000;
/**
* 天
*/
public static final long DAY_MILLI = 24 * 60 * 60 * 1000;
/**
* 东八区
*/
private static final String ZONE_8 = "+8";
/**
* 获取当前时间
* @return 当前时间
*/
public static LocalDateTime localDateTime(){
return LocalDateTime.now();
}
/**
* 当前时间 date 类型
* @return date类型
*/
public static Date date(){
return new Date();
}
public static Date localDateTime2Date(LocalDateTime localDateTime){
return Date.from(localDateTime
.atZone(ZoneId.systemDefault())
.toInstant());
}
public static LocalDateTime date2LocalDateTime(Date date){
return date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
// 01. java.util.Date --> java.time.LocalDateTime
public static LocalDateTime dateToLocalDateTime(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
// 02. java.util.Date --> java.time.LocalDate
public static LocalDate dateToLocalDate(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
return localDateTime.toLocalDate();
}
// 03. java.util.Date --> java.time.LocalTime
public static LocalTime dateToLocalTime(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
return localDateTime.toLocalTime();
}
// 04. java.time.LocalDateTime --> java.util.Date
public static Date LocalDateTimeToDate(LocalDateTime localDateTime) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return Date.from(instant);
}
// 05. java.time.LocalDate --> java.util.Date
public static Date LocalDateToDate(LocalDate localDate) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);
}
// 06. java.time.LocalTime --> java.util.Date
public static Date LocalTimeToDate(LocalDate localDate,LocalTime localTime) {
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return Date.from(instant);
}
public static int year(Date date){
return date.getYear() + 1900;
}
public static int month(Date date){
return date.getMonth() + 1;
}
public static int day(Date date){
return date.getDate();
}
/**
* 获取当前时间戳
* @return 时间戳
*/
public static long timeStamp(){
return Instant.now().getEpochSecond();
}
/**
* 获取相应时间的时间戳
* @param localDateTime 时间
* @return 毫秒级时间戳
*/
public static long timeStamp(LocalDateTime localDateTime){
return localDateTime.toInstant(ZoneOffset.of(ZONE_8)).toEpochMilli();
}
public static void main(String[] args) {
// System.out.println(timeStamp(LocalDateTime.now()));
LocalDate date = dateToLocalDate(new Date());
System.out.println(date);
LocalDate localDate = date.plusMonths(-1);
// System.out.println(localDate);
// LocalDate date1 = LocalDate.of(2018,10,12);
// int days = date1.until(date).getDays();
// System.out.println(days);
LocalDate of = LocalDate.of(localDate.getYear(), localDate.getMonth().getValue(), 15);
System.out.println(localDate.isBefore(LocalDate.of(localDate.getYear(),localDate.getMonth().getValue(),15)));
}
/**
* ijoke 2018-10-29
* 获取传入日期的下月1号
* @param date
* @return
*/
public static Date firstDayOfNextMonth(Date date) {
//获得入参的日期
Calendar cd = Calendar.getInstance();
cd.setTime(date);
//获取下个月第一天:
cd.add(Calendar.MONTH, 1);
//设置为1号,当前日期既为次月第一天
cd.set(Calendar.DAY_OF_MONTH,1);
return cd.getTime();
}
/**
* ijoke 2018-10-29
* 根据传入的日期和int数字,对月份做加减操作,正数为往后推算月份,负数往前推算月份
* 可跨年
* @param inDate 传入的日期
* @param num 需要增加的月数
* @return
*/
public static Date getMonthAdd(Date inDate,int num){
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(inDate);
rightNow.add(Calendar.MONTH,num);//日期加3个月
Date outDate=rightNow.getTime();
return outDate;
}
/**
* 判断是否是当月最后一天
* @param date
* @return
*/
public static boolean isLastDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH) == calendar
.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
| UTF-8 | Java | 6,064 | java | DateUtil.java | Java | [
{
"context": "l.Calendar;\nimport java.util.Date;\n\n/**\n * @author Lokiy\n * @date 2018/6/7\n * @description jre8日期帮助类\n * 需要",
"end": 210,
"score": 0.9992168545722961,
"start": 205,
"tag": "USERNAME",
"value": "Lokiy"
}
]
| null | []
| package com.ljy.sbtemplate.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
/**
* @author Lokiy
* @date 2018/6/7
* @description jre8日期帮助类
* 需要其他的方法自行添加
*/
public class DateUtil {
private static final Logger log = LogManager.getLogger();
/**
* 秒
*/
public static final long SECOND_MILLI = 1000;
/**
* 分
*/
public static final long MINUTE_MILLI = 60 * 1000;
/**
* 时
*/
public static final long HOUR_MILLI = 60 * 60 * 1000;
/**
* 天
*/
public static final long DAY_MILLI = 24 * 60 * 60 * 1000;
/**
* 东八区
*/
private static final String ZONE_8 = "+8";
/**
* 获取当前时间
* @return 当前时间
*/
public static LocalDateTime localDateTime(){
return LocalDateTime.now();
}
/**
* 当前时间 date 类型
* @return date类型
*/
public static Date date(){
return new Date();
}
public static Date localDateTime2Date(LocalDateTime localDateTime){
return Date.from(localDateTime
.atZone(ZoneId.systemDefault())
.toInstant());
}
public static LocalDateTime date2LocalDateTime(Date date){
return date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
// 01. java.util.Date --> java.time.LocalDateTime
public static LocalDateTime dateToLocalDateTime(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
// 02. java.util.Date --> java.time.LocalDate
public static LocalDate dateToLocalDate(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
return localDateTime.toLocalDate();
}
// 03. java.util.Date --> java.time.LocalTime
public static LocalTime dateToLocalTime(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
return localDateTime.toLocalTime();
}
// 04. java.time.LocalDateTime --> java.util.Date
public static Date LocalDateTimeToDate(LocalDateTime localDateTime) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return Date.from(instant);
}
// 05. java.time.LocalDate --> java.util.Date
public static Date LocalDateToDate(LocalDate localDate) {
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);
}
// 06. java.time.LocalTime --> java.util.Date
public static Date LocalTimeToDate(LocalDate localDate,LocalTime localTime) {
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return Date.from(instant);
}
public static int year(Date date){
return date.getYear() + 1900;
}
public static int month(Date date){
return date.getMonth() + 1;
}
public static int day(Date date){
return date.getDate();
}
/**
* 获取当前时间戳
* @return 时间戳
*/
public static long timeStamp(){
return Instant.now().getEpochSecond();
}
/**
* 获取相应时间的时间戳
* @param localDateTime 时间
* @return 毫秒级时间戳
*/
public static long timeStamp(LocalDateTime localDateTime){
return localDateTime.toInstant(ZoneOffset.of(ZONE_8)).toEpochMilli();
}
public static void main(String[] args) {
// System.out.println(timeStamp(LocalDateTime.now()));
LocalDate date = dateToLocalDate(new Date());
System.out.println(date);
LocalDate localDate = date.plusMonths(-1);
// System.out.println(localDate);
// LocalDate date1 = LocalDate.of(2018,10,12);
// int days = date1.until(date).getDays();
// System.out.println(days);
LocalDate of = LocalDate.of(localDate.getYear(), localDate.getMonth().getValue(), 15);
System.out.println(localDate.isBefore(LocalDate.of(localDate.getYear(),localDate.getMonth().getValue(),15)));
}
/**
* ijoke 2018-10-29
* 获取传入日期的下月1号
* @param date
* @return
*/
public static Date firstDayOfNextMonth(Date date) {
//获得入参的日期
Calendar cd = Calendar.getInstance();
cd.setTime(date);
//获取下个月第一天:
cd.add(Calendar.MONTH, 1);
//设置为1号,当前日期既为次月第一天
cd.set(Calendar.DAY_OF_MONTH,1);
return cd.getTime();
}
/**
* ijoke 2018-10-29
* 根据传入的日期和int数字,对月份做加减操作,正数为往后推算月份,负数往前推算月份
* 可跨年
* @param inDate 传入的日期
* @param num 需要增加的月数
* @return
*/
public static Date getMonthAdd(Date inDate,int num){
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(inDate);
rightNow.add(Calendar.MONTH,num);//日期加3个月
Date outDate=rightNow.getTime();
return outDate;
}
/**
* 判断是否是当月最后一天
* @param date
* @return
*/
public static boolean isLastDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH) == calendar
.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
| 6,064 | 0.616894 | 0.600245 | 212 | 25.915094 | 23.687078 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382075 | false | false | 13 |
397e146fa09aa00fe75d102a32eb53fd9ada18e7 | 30,794,915,534,159 | dde19b2a7639b3640dd1060034d9cfc7522fa8d5 | /src/main/java/interview/TestSync2.java | 5fc7afc220f7e09022c3373c6e5f420fc70350f3 | []
| no_license | dongfucai/dongpractice | https://github.com/dongfucai/dongpractice | 6578d4cc3fed2f6c908b60df3205262382405c56 | 1f69a899a3e35553901664042eced8ee3bf67933 | refs/heads/master | 2022-12-23T19:28:03.449000 | 2019-05-28T13:36:54 | 2019-05-28T13:36:54 | 146,291,555 | 0 | 0 | null | false | 2022-12-16T04:31:55 | 2018-08-27T12:01:40 | 2019-05-28T13:49:05 | 2022-12-16T04:31:53 | 180 | 0 | 0 | 5 | Java | false | false | package interview;
/**
* @Package Name : ${PACKAG_NAME}
* @Author : 1766318593@qq.com
* @Creation Date : 2018年11月06日上午12:08
* @Function : todo
*/
public class TestSync2 implements Runnable {
int b = 100;
synchronized void m1() throws InterruptedException {
b = 1000;
//Thread.sleep(500); //6
System.out.println("b=" + b);
}
synchronized void m2() throws InterruptedException {
//Thread.sleep(250); //5
b = 2000;
}
public static void main(String[] args) throws InterruptedException {
TestSync2 tt = new TestSync2();
Thread t = new Thread(tt); //1
t.start(); //2
tt.m2(); //3
System.out.println("main thread b=" + tt.b); //4
}
@Override
public void run() {
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
下面开始简单分析:
该题目涉及到2个线程(主线程main、子线程)、关键词涉及到synchronized、Thread.sleep。
synchronized关键词还是比较复杂的(可能有时候没有理解到位所以上面题目会有点误区),他的作用就是实现线程的同步(实现线程同步有很多方法,它只是一种,后续文章会说其他的,需要好好研究大神Doug Lea的一些实现),它的工作就是对需要同步的代码加锁,使得每一次只有一个线程可以进入同步块(其实是一种悲观策略)从而保证线程只记得安全性。
一般关键词synchronized的用法
指定加锁对象:对给定对象加锁,进入同步代码前需要活的给定对象的锁。
直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
直接作用于静态方法:相当于对当前类加锁,进入同步代码前要获得当前类的锁。
上面的代码,synchronized用法其实就 属于第二种情况。直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
可能存在的误区
由于对synchronized理解的不到位,由于很多时候,我们多线程都是操作一个synchronized的方法,当2个线程调用2个不同synchronized的方法的时候,认为是没有关系的,这种想法是存在误区的。直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
如果一个调用synchronized方法。另外一个调用普通方法是没有关系的,2个是不存在等待关系的。
这些对于后面的分析很有作用。
Thread.sleep
使当前线程(即调用该方法的线程)暂停执行一段时间,让其他线程有机会继续执行,**但它并不释放对象锁。也就是说如果有synchronized同步快,其他线程仍然不能访问共享数据。**注意该方法要捕捉异常,对于后面的分析很有作用。一些细节可以参考我的系统学习java高并发系列二。
作者:匠心零度
链接:https://juejin.im/post/59f9804851882554b836dd8b
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/ | UTF-8 | Java | 3,235 | java | TestSync2.java | Java | [
{
"context": "**\n * @Package Name : ${PACKAG_NAME}\n * @Author : 1766318593@qq.com\n * @Creation Date : 2018年11月06日上午12:08\n * @Functi",
"end": 88,
"score": 0.9998345971107483,
"start": 71,
"tag": "EMAIL",
"value": "1766318593@qq.com"
},
{
"context": "法要捕捉异常,对于后面的分析很有作用。一些细节可以参考我的系统学习java高并发系列二。\n\n 作者:匠心零度\n 链接:https://juejin.im/post/59f9804851882554b836dd",
"end": 1754,
"score": 0.9978823661804199,
"start": 1750,
"tag": "NAME",
"value": "匠心零度"
}
]
| null | []
| package interview;
/**
* @Package Name : ${PACKAG_NAME}
* @Author : <EMAIL>
* @Creation Date : 2018年11月06日上午12:08
* @Function : todo
*/
public class TestSync2 implements Runnable {
int b = 100;
synchronized void m1() throws InterruptedException {
b = 1000;
//Thread.sleep(500); //6
System.out.println("b=" + b);
}
synchronized void m2() throws InterruptedException {
//Thread.sleep(250); //5
b = 2000;
}
public static void main(String[] args) throws InterruptedException {
TestSync2 tt = new TestSync2();
Thread t = new Thread(tt); //1
t.start(); //2
tt.m2(); //3
System.out.println("main thread b=" + tt.b); //4
}
@Override
public void run() {
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
下面开始简单分析:
该题目涉及到2个线程(主线程main、子线程)、关键词涉及到synchronized、Thread.sleep。
synchronized关键词还是比较复杂的(可能有时候没有理解到位所以上面题目会有点误区),他的作用就是实现线程的同步(实现线程同步有很多方法,它只是一种,后续文章会说其他的,需要好好研究大神Doug Lea的一些实现),它的工作就是对需要同步的代码加锁,使得每一次只有一个线程可以进入同步块(其实是一种悲观策略)从而保证线程只记得安全性。
一般关键词synchronized的用法
指定加锁对象:对给定对象加锁,进入同步代码前需要活的给定对象的锁。
直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
直接作用于静态方法:相当于对当前类加锁,进入同步代码前要获得当前类的锁。
上面的代码,synchronized用法其实就 属于第二种情况。直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
可能存在的误区
由于对synchronized理解的不到位,由于很多时候,我们多线程都是操作一个synchronized的方法,当2个线程调用2个不同synchronized的方法的时候,认为是没有关系的,这种想法是存在误区的。直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
如果一个调用synchronized方法。另外一个调用普通方法是没有关系的,2个是不存在等待关系的。
这些对于后面的分析很有作用。
Thread.sleep
使当前线程(即调用该方法的线程)暂停执行一段时间,让其他线程有机会继续执行,**但它并不释放对象锁。也就是说如果有synchronized同步快,其他线程仍然不能访问共享数据。**注意该方法要捕捉异常,对于后面的分析很有作用。一些细节可以参考我的系统学习java高并发系列二。
作者:匠心零度
链接:https://juejin.im/post/59f9804851882554b836dd8b
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/ | 3,225 | 0.709434 | 0.669003 | 69 | 25.89855 | 33.296276 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.202899 | false | false | 13 |
4a1bf4c37017fa54201bacd03145851cca7de80d | 35,665,408,431,980 | fb1ead5ca99cd6a89efe4d416b2ec2217d68d054 | /Riddle Server/riddle_server/src/main/java/server/TCPServer.java | 7d9cf92d3033e1cf76f77a80d6c05e4555ab43be | []
| no_license | arosharodrigo/distributed-systems | https://github.com/arosharodrigo/distributed-systems | dc038d37f763b6f3a7641e1532a4d8b3322cd42f | 541b6f83c4779be5afd24d2136e94fa74123b516 | refs/heads/master | 2020-05-17T22:22:28.979000 | 2014-04-23T01:27:10 | 2014-04-23T01:27:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.java.server;
import main.java.domain.Message;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: arosha
* Date: 3/30/14
* Time: 9:13 AM
* To change this template use File | Settings | File Templates.
*/
public class TCPServer extends AbstractServer {
private static int SERVER_PORT = 7000;
private static String SEPARATOR = " ";
private static boolean READY_TO_STOP = true;
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
TCPServer tcpServer = new TCPServer();
ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(SERVER_PORT));
ssc.configureBlocking(false);
READY_TO_STOP = false;
while(!READY_TO_STOP) {
try {
System.out.println("Waiting for connections.....");
SocketChannel sc = ssc.accept();
if(sc == null) {
Thread.sleep(1000);
} else {
sc.read(receiveBuffer);
Message req = (Message)Message.deserialize(receiveBuffer.array());
SocketAddress remoteAddress = sc.getRemoteAddress();
System.out.println("Received: [" + req.getMessage() + "] from: [" + remoteAddress + "]");
receiveBuffer.clear();
Arrays.fill(receiveBuffer.array(), (byte) 0);
String res = tcpServer.executeCommand(req.getMessage().split(SEPARATOR));
tcpServer.sendToClient(sendBuffer, res, sc, remoteAddress);
}
} catch (Exception e) {
System.out.println("Error occurred while processing message: " + e.getMessage());
e.printStackTrace();
}
}
ssc.close();
}
private void sendToClient(ByteBuffer sendBuffer, String resp, SocketChannel sc, SocketAddress remoteAddress) throws IOException {
Message res = new Message(resp);
sendBuffer.put(Message.serialize(res));
sendBuffer.rewind();
sc.write(sendBuffer);
sendBuffer.clear();
Arrays.fill(sendBuffer.array(), (byte) 0);
}
@Override
public void close() throws Exception {
}
}
| UTF-8 | Java | 2,649 | java | TCPServer.java | Java | [
{
"context": "rays;\n\n/**\n * Created with IntelliJ IDEA.\n * User: arosha\n * Date: 3/30/14\n * Time: 9:13 AM\n * To change th",
"end": 345,
"score": 0.9992356300354004,
"start": 339,
"tag": "USERNAME",
"value": "arosha"
}
]
| null | []
| package main.java.server;
import main.java.domain.Message;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: arosha
* Date: 3/30/14
* Time: 9:13 AM
* To change this template use File | Settings | File Templates.
*/
public class TCPServer extends AbstractServer {
private static int SERVER_PORT = 7000;
private static String SEPARATOR = " ";
private static boolean READY_TO_STOP = true;
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
TCPServer tcpServer = new TCPServer();
ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(SERVER_PORT));
ssc.configureBlocking(false);
READY_TO_STOP = false;
while(!READY_TO_STOP) {
try {
System.out.println("Waiting for connections.....");
SocketChannel sc = ssc.accept();
if(sc == null) {
Thread.sleep(1000);
} else {
sc.read(receiveBuffer);
Message req = (Message)Message.deserialize(receiveBuffer.array());
SocketAddress remoteAddress = sc.getRemoteAddress();
System.out.println("Received: [" + req.getMessage() + "] from: [" + remoteAddress + "]");
receiveBuffer.clear();
Arrays.fill(receiveBuffer.array(), (byte) 0);
String res = tcpServer.executeCommand(req.getMessage().split(SEPARATOR));
tcpServer.sendToClient(sendBuffer, res, sc, remoteAddress);
}
} catch (Exception e) {
System.out.println("Error occurred while processing message: " + e.getMessage());
e.printStackTrace();
}
}
ssc.close();
}
private void sendToClient(ByteBuffer sendBuffer, String resp, SocketChannel sc, SocketAddress remoteAddress) throws IOException {
Message res = new Message(resp);
sendBuffer.put(Message.serialize(res));
sendBuffer.rewind();
sc.write(sendBuffer);
sendBuffer.clear();
Arrays.fill(sendBuffer.array(), (byte) 0);
}
@Override
public void close() throws Exception {
}
}
| 2,649 | 0.616082 | 0.606266 | 77 | 33.402596 | 29.643887 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.662338 | false | false | 13 |
0299ab174831d26f318f44f193c158a2b472440c | 9,869,834,871,799 | 03be40b86ec02d2d87d65960288a587647fe2341 | /src/main/java/is/bokun/dtos/PenaltyRuleDto.java | 93d97a2ee93237091eff4e796054e28f883d39dd | []
| no_license | xperious/bokun_api | https://github.com/xperious/bokun_api | a156db620096304c1889285476952a9a5cb40b12 | b58d964feb1ca3cdfd215acbf841a631d5bda85a | refs/heads/master | 2021-01-22T19:08:35.512000 | 2018-09-14T07:59:11 | 2018-09-14T07:59:11 | 85,165,182 | 0 | 0 | null | true | 2017-03-16T07:21:56 | 2017-03-16T07:21:56 | 2015-11-26T12:00:32 | 2015-11-25T14:57:43 | 735 | 0 | 0 | 0 | null | null | null | package is.bokun.dtos;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PenaltyRuleDto {
public int id;
public int cutoffHours;
public Long charge;
public String chargeType;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCutoffHours() {
return cutoffHours;
}
public void setCutoffHours(int cutoffHours) {
this.cutoffHours = cutoffHours;
}
public Long getCharge() {
return charge;
}
public void setCharge(Long charge) {
this.charge = charge;
}
public String getChargeType() {
return chargeType;
}
public void setChargeType(String chargeType) {
this.chargeType = chargeType;
}
}
| UTF-8 | Java | 847 | java | PenaltyRuleDto.java | Java | []
| null | []
| package is.bokun.dtos;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PenaltyRuleDto {
public int id;
public int cutoffHours;
public Long charge;
public String chargeType;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCutoffHours() {
return cutoffHours;
}
public void setCutoffHours(int cutoffHours) {
this.cutoffHours = cutoffHours;
}
public Long getCharge() {
return charge;
}
public void setCharge(Long charge) {
this.charge = charge;
}
public String getChargeType() {
return chargeType;
}
public void setChargeType(String chargeType) {
this.chargeType = chargeType;
}
}
| 847 | 0.635183 | 0.635183 | 44 | 18.25 | 16.816017 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 13 |
ebf8b70cb1ec3688c833d1d85a346afbfa0102b9 | 21,431,886,844,551 | dcfe2f397bad56e998df3239d8cdfb40b874fd1b | /app/src/main/java/app/taxi/newtaxi/My_taxi.java | e51d20e84b74be1d5b2e2cfe65c0774166e05923 | []
| no_license | Dolphin-PC/T.T | https://github.com/Dolphin-PC/T.T | d9af2f5c9d9dbf5d4a5d6c890c86da46503d0f65 | 80ffd9473bf4661d8b792de3d82be789e1f3c4f3 | refs/heads/master | 2023-03-10T19:23:22.268000 | 2021-02-25T09:15:57 | 2021-02-25T09:15:57 | 180,379,286 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.taxi.newtaxi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
// 나가기 버튼(방장은 나갈때, 다이얼로그 표시)
public class My_taxi extends AppCompatActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,GoogleMap.OnCameraIdleListener,GoogleMap.OnCameraMoveListener {
private DatabaseReference mDatabase;
private TextView INDEXtext,TIMEtext,PRICEtext,DISTANCEtext,PERSONtext;
private GoogleMap MAPview;
GoogleApiClient googleApiClient;
Marker marker;
private static int DEFAULT_ZOOM = 14; //0~21 level
int POINT=1000,MIDDLE_ZOOM = 14,Max;
private ListView LISTview,MYDIALOGlist;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private String userID,title,start,arrive,driver,taxinumber,phonenumber,ID,INDEX,TIME,DISTANCE,PAY;
private int person,PRICE;
long now = System.currentTimeMillis ();
Date date = new Date(now);
SimpleDateFormat sdfNow = new SimpleDateFormat("MM/DD");
String Time = sdfNow.format(date);
int MONTH = Integer.parseInt(Time.split("/")[0]);
int DAY = Integer.parseInt(Time.split("/")[1]);
private final int stuck = 10;
LatLng STARTlatlng,ARRIVElatlng,MIDDLElatlng;
AlertDialog.Builder PAYdialog, CHARGEdialog,OUTdialog,QUITdialog;
My_taxiAdapter adapter;
Double MIDDLE_latitude,MIDDLE_longitude;
Button INFObutton,OUTbutton,PAYbutton;
Dialog dialog;
Query MEMBERSquery;
QuitReceiver quitReceiver;
void init() {
SharedPreferences positionDATA = getSharedPreferences("positionDATA",MODE_PRIVATE);
final SharedPreferences.Editor editor = positionDATA.edit();
INFObutton = findViewById(R.id.INFObutton);
INDEXtext = findViewById(R.id.INDEXtext);
LISTview = findViewById(R.id.LISTview);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.MY_MAP);
mapFragment.getMapAsync(this);
dialog = new Dialog(this);
Intent intent = getIntent();
INDEX = intent.getExtras().getString("INDEX");
title = positionDATA.getString("TITLE","");
arrive = positionDATA.getString("ARRIVE","");
start = positionDATA.getString("START","");
person = Integer.valueOf(positionDATA.getString("PERSON","1"));
PRICE = Integer.valueOf(positionDATA.getString("PRICE","1000"));
userID = positionDATA.getString("USERNAME","");
ID = positionDATA.getString("ID","");
TIME = positionDATA.getString("TIME","");
DISTANCE = positionDATA.getString("DISTANCE","");
PAY = positionDATA.getString("PAY","");
Max = Integer.valueOf(positionDATA.getString("MAX","3"));
INDEXtext.setText(INDEX);
mDatabase = FirebaseDatabase.getInstance().getReference();
MEMBERSquery = mDatabase.child("post-members").orderByChild("userid").equalTo(ID);
String start_lati = positionDATA.getString("출발", "").split(",")[0];
String start_long = positionDATA.getString("출발", "").split(",")[1];
STARTlatlng = new LatLng(Double.valueOf(start_lati), Double.valueOf(start_long));
String arrive_lati = positionDATA.getString("도착", "").split(",")[0];
String arrive_long = positionDATA.getString("도착", "").split(",")[1];
ARRIVElatlng = new LatLng(Double.valueOf(arrive_lati), Double.valueOf(arrive_long));
MIDDLE_latitude = Math.abs(STARTlatlng.latitude - ARRIVElatlng.latitude) / 2.0;
MIDDLE_longitude = Math.abs(STARTlatlng.longitude - ARRIVElatlng.longitude) / 2.0;
if (STARTlatlng.latitude > ARRIVElatlng.latitude)
MIDDLE_latitude += ARRIVElatlng.latitude;
else
MIDDLE_latitude += STARTlatlng.latitude;
if (STARTlatlng.longitude > ARRIVElatlng.longitude)
MIDDLE_longitude += ARRIVElatlng.longitude;
else
MIDDLE_longitude += STARTlatlng.longitude;
MIDDLElatlng = new LatLng(MIDDLE_latitude, MIDDLE_longitude);
if (MIDDLE_latitude <= 0.0108 || MIDDLE_longitude <= 0.0108) { //출발지와 도착지가 중간지점에서부터 1.2km 이상이면,
MIDDLE_ZOOM = 14;
} else if (MIDDLE_latitude <= 0.0216 || MIDDLE_longitude <= 0.0216) {
MIDDLE_ZOOM = 13;
} else if (MIDDLE_latitude <= 0.0432 || MIDDLE_longitude <= 0.0432) {
MIDDLE_ZOOM = 12;
} else if (MIDDLE_latitude <= 0.0864 || MIDDLE_longitude <= 0.0864) {
MIDDLE_ZOOM = 11;
} else if (MIDDLE_latitude <= 0.1728 || MIDDLE_longitude <= 0.1728) {
MIDDLE_ZOOM = 10;
} else if (MIDDLE_latitude <= 0.3456 || MIDDLE_longitude <= 0.3456) {
MIDDLE_ZOOM = 9;
}
quitReceiver = new QuitReceiver();
}
void click(){
INFObutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.setContentView(R.layout.my_taxi_dialog);
dialog.show();
MYDIALOGlist = dialog.findViewById(R.id.MYDIALOGlist);
TIMEtext = dialog.findViewById(R.id.TIMEtext);
PRICEtext = dialog.findViewById(R.id.PRICEtext);
DISTANCEtext = dialog.findViewById(R.id.DISTANCEtext);
PERSONtext = dialog.findViewById(R.id.PERSONtext);
OUTbutton = dialog.findViewById(R.id.OUTbutton);
PAYbutton = dialog.findViewById(R.id.PAYbutton);
MEMBERSquery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data_Members data_members = snapshot.getValue(Data_Members.class);
if (data_members.getJOIN()) {
Log.e("JOIN", "왜");
PAYbutton.setText("채팅 창으로");
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
MYDIALOGlist.setAdapter(adapter);
TIMEtext.setText(TIME);
PRICEtext.setText(PAY + "원");
DISTANCEtext.setText(DISTANCE);
PERSONtext.setText(adapter.getCount() + "/" + Max);
OUTbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
OUTDIALOG();
OUTdialog.show();
}
});
PAYbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(PAYbutton.getText().toString().equals("결제하기")) {
dialog.dismiss();
PAYDIALOG(Integer.parseInt(PAY));
PAYdialog.show();
}else{
Intent intent1 = new Intent(getApplicationContext(),Post_Call.class);
intent1.putExtra("INDEX",INDEX);
dialog.dismiss();
startActivity(intent1);
}
}
});
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_taxi);
init();
click();
// Custom Adapter Instance 생성 및 ListView에 Adapter 지정
adapter = new My_taxiAdapter();
LISTview.setAdapter(adapter);
/*LISTview.addHeaderView();*/
Query query = mDatabase.child("post-members").orderByChild("index").equalTo(INDEX);
final Query query1 = mDatabase.child("post").orderByChild("index").equalTo(INDEX);
Log.e("index",INDEXtext.getText().toString());
query.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Data_Members data_members = dataSnapshot.getValue(Data_Members.class);
adapter.addItem(data_members.getPROFILEURL(),data_members.getUSER1(),data_members.getGENDER());
adapter.notifyDataSetChanged();
query1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot : dataSnapshot.getChildren()) {
Data_Post data_post = appleSnapshot.getValue(Data_Post.class);
Log.e("COUNT", adapter.getCount() + "");
if (adapter.getCount() == data_post.getMaxPerson()) {
POINT = data_post.getPay() / data_post.getMaxPerson();
PAYDIALOG(data_post.getPay() / data_post.getMaxPerson());
//TODO : 다른 방식으로 결제하기 알리기(Toast, Background Message)
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
Intent QUITintent = new Intent(getApplicationContext(),main.class);
QUITintent.putExtra("MESSAGE","방장이 퇴장하여 퇴장처리 되었습니다.");
QUIT_PROCESS_reference();
startActivity(QUITintent);
finish();
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
Log.e("MAX",Max+"");
Log.e("adapter",adapter.getCount()+"");
if(Max == adapter.getCount())
PAYdialog.show();
}
private void PAYDIALOG(final int Point) {
PAYdialog = new AlertDialog.Builder(this);
PAYdialog.setTitle("결제 확인");
PAYdialog.setMessage(Point + "P : 결제 하시겠습니까?\n(결제 후, 택시가 호출됩니다.)");
PAYdialog.setPositiveButton("결제", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, int which) {
final Query query = mDatabase.child("user").orderByChild("email").equalTo(ID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
String path = "/" + dataSnapshot.getKey() + "/" + snapshot.getKey();
Map<String,Object> POINTmap = new HashMap<String,Object>();
if(user.getPoint()-Point < 0){
CHARGEDIALOG(user.getPoint());
CHARGEdialog.show();
}
else {
POINTmap.put("point", user.getPoint() - Point);
mDatabase.child(path).updateChildren(POINTmap);
Query query1 = mDatabase.child("post-members").orderByChild("index").equalTo(INDEXtext.getText().toString().split(" ")[0]); //INDEX를 통해 JOIN을 바꾸면, 전체가 바뀜(ID를 통해 접근을 해서 해당 ID만 바꾸기)
query1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data_Members data_members = snapshot.getValue(Data_Members.class);
String path = "/" + dataSnapshot.getKey() + "/" + snapshot.getKey();
Map<String, Object> JOINmap = new HashMap<String, Object>();
JOINmap.put("join", true);
mDatabase.child(path).updateChildren(JOINmap);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
Intent intent = new Intent(getApplicationContext(),Post_Call.class);
intent.putExtra("INDEX",INDEX);
dialog.dismiss();
startActivity(intent);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
});
}
void CHARGEDIALOG(final int Point){
CHARGEdialog = new AlertDialog.Builder(this);
CHARGEdialog.setTitle("포인트 부족");
CHARGEdialog.setMessage("포인트가 부족합니다.\n충전하러 가시겠습니까?");
CHARGEdialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), Charge.class);
intent.putExtra("POINT",Point+"");
Log.e("POINT",Point+"");
startActivity(intent);
}
});
}
void OUTDIALOG(){
OUTdialog = new AlertDialog.Builder(this);
OUTdialog.setTitle("퇴장");
if(INDEXtext.getText().toString() == ID)
OUTdialog.setMessage("노선에서 나가시겠습니까?\n(팀원 전체 퇴장됩니다.)");
else
OUTdialog.setMessage("노선에서 나가시겠습니까?");
OUTdialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onDestroy();
}
});
OUTdialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
QUIT_PROCESS_reference();
QUIT_PROCESS_database();
Intent intent = new Intent(getApplicationContext(),main.class);
intent.putExtra("MESSAGE","");
startActivity(intent);
finish();
}
});
}
void QUITDIALOG(Context context){
QUITdialog = new AlertDialog.Builder(context);
QUITdialog.setTitle("퇴장");
QUITdialog.setMessage("방장님이 퇴장하여,\n전체퇴장 처리되었습니다.");
QUITdialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onDestroy();
}
});
}
@Override
public void onConnected(@Nullable Bundle bundle) { }
@Override
public void onConnectionSuspended(int i) { }
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { }
@Override
public void onCameraIdle() { }
@Override
public void onCameraMove() { }
@Override
public void onMapReady(GoogleMap googleMap) {
MAPview = googleMap;
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(MIDDLElatlng,MIDDLE_ZOOM));
marker = googleMap.addMarker(new MarkerOptions().position(STARTlatlng).title("출발 위치").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
marker = googleMap.addMarker(new MarkerOptions().position(ARRIVElatlng).title("도착 위치").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
void QUIT_PROCESS_reference() {
SharedPreferences positionDATA = getSharedPreferences("positionDATA", MODE_PRIVATE);
SharedPreferences.Editor editor = positionDATA.edit();
editor.remove("DISTANCE");
editor.remove("PERSON");
editor.remove("MAX");
editor.remove("도착지");
editor.remove("TIME");
editor.remove("도착");
editor.remove("출발");
editor.remove("출발지");
editor.remove("INDEX");
editor.apply();
}
void QUIT_PROCESS_database(){
final Query POSTquery = mDatabase.child("post").orderByChild("index").equalTo(INDEX);
final Query MEMBERSquery_1 = mDatabase.child("post-members").orderByChild("index").equalTo(ID); //방장이 나갔을때, post-members전체 삭제
final Query MEMBERSquery_2 = mDatabase.child("post-members").orderByChild("userid").equalTo(ID); //참가인원이 나갔을 때,
final Query MESSAGEquery_1 = mDatabase.child("post-message").orderByChild("index").equalTo(ID); //방장이 나갔을때, post-message전체 삭제
final Query MESSAGEquery_2 = mDatabase.child("post-message").orderByChild("id").equalTo(ID); //참가인원이 나갔을 때,
POSTquery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data_Post data_post = snapshot.getValue(Data_Post.class);
if (ID.equals(data_post.getIndex())){ //방장일 때, 방 전체 파기(post/post-members/post-message)
Log.d("post","방장일 때");
mDatabase.child("post").child(snapshot.getKey()).removeValue();
MEMBERSquery_1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-members").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
MESSAGEquery_1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-message").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
else{ //참가한 인원일경우, person-1, post-members 파기
Log.d("post","참가일 때");
String path = "/" + dataSnapshot.getKey() + "/" + snapshot.getKey();
Map<String,Object> taskMap = new HashMap<String,Object>();
taskMap.put("person",data_post.getPerson()-1);
mDatabase.child(path).updateChildren(taskMap);
MEMBERSquery_2.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-members").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
MESSAGEquery_2.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-message").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
@Override
public void onBackPressed() {
OUTDIALOG();
OUTdialog.show();
}
}
| UTF-8 | Java | 24,191 | java | My_taxi.java | Java | [
{
"context": "1000\"));\n userID = positionDATA.getString(\"USERNAME\",\"\");\n ID = positionDATA.getString(\"ID\",\"\"",
"end": 4205,
"score": 0.9979428648948669,
"start": 4197,
"tag": "USERNAME",
"value": "USERNAME"
}
]
| null | []
| package app.taxi.newtaxi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
// 나가기 버튼(방장은 나갈때, 다이얼로그 표시)
public class My_taxi extends AppCompatActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,GoogleMap.OnCameraIdleListener,GoogleMap.OnCameraMoveListener {
private DatabaseReference mDatabase;
private TextView INDEXtext,TIMEtext,PRICEtext,DISTANCEtext,PERSONtext;
private GoogleMap MAPview;
GoogleApiClient googleApiClient;
Marker marker;
private static int DEFAULT_ZOOM = 14; //0~21 level
int POINT=1000,MIDDLE_ZOOM = 14,Max;
private ListView LISTview,MYDIALOGlist;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private String userID,title,start,arrive,driver,taxinumber,phonenumber,ID,INDEX,TIME,DISTANCE,PAY;
private int person,PRICE;
long now = System.currentTimeMillis ();
Date date = new Date(now);
SimpleDateFormat sdfNow = new SimpleDateFormat("MM/DD");
String Time = sdfNow.format(date);
int MONTH = Integer.parseInt(Time.split("/")[0]);
int DAY = Integer.parseInt(Time.split("/")[1]);
private final int stuck = 10;
LatLng STARTlatlng,ARRIVElatlng,MIDDLElatlng;
AlertDialog.Builder PAYdialog, CHARGEdialog,OUTdialog,QUITdialog;
My_taxiAdapter adapter;
Double MIDDLE_latitude,MIDDLE_longitude;
Button INFObutton,OUTbutton,PAYbutton;
Dialog dialog;
Query MEMBERSquery;
QuitReceiver quitReceiver;
void init() {
SharedPreferences positionDATA = getSharedPreferences("positionDATA",MODE_PRIVATE);
final SharedPreferences.Editor editor = positionDATA.edit();
INFObutton = findViewById(R.id.INFObutton);
INDEXtext = findViewById(R.id.INDEXtext);
LISTview = findViewById(R.id.LISTview);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.MY_MAP);
mapFragment.getMapAsync(this);
dialog = new Dialog(this);
Intent intent = getIntent();
INDEX = intent.getExtras().getString("INDEX");
title = positionDATA.getString("TITLE","");
arrive = positionDATA.getString("ARRIVE","");
start = positionDATA.getString("START","");
person = Integer.valueOf(positionDATA.getString("PERSON","1"));
PRICE = Integer.valueOf(positionDATA.getString("PRICE","1000"));
userID = positionDATA.getString("USERNAME","");
ID = positionDATA.getString("ID","");
TIME = positionDATA.getString("TIME","");
DISTANCE = positionDATA.getString("DISTANCE","");
PAY = positionDATA.getString("PAY","");
Max = Integer.valueOf(positionDATA.getString("MAX","3"));
INDEXtext.setText(INDEX);
mDatabase = FirebaseDatabase.getInstance().getReference();
MEMBERSquery = mDatabase.child("post-members").orderByChild("userid").equalTo(ID);
String start_lati = positionDATA.getString("출발", "").split(",")[0];
String start_long = positionDATA.getString("출발", "").split(",")[1];
STARTlatlng = new LatLng(Double.valueOf(start_lati), Double.valueOf(start_long));
String arrive_lati = positionDATA.getString("도착", "").split(",")[0];
String arrive_long = positionDATA.getString("도착", "").split(",")[1];
ARRIVElatlng = new LatLng(Double.valueOf(arrive_lati), Double.valueOf(arrive_long));
MIDDLE_latitude = Math.abs(STARTlatlng.latitude - ARRIVElatlng.latitude) / 2.0;
MIDDLE_longitude = Math.abs(STARTlatlng.longitude - ARRIVElatlng.longitude) / 2.0;
if (STARTlatlng.latitude > ARRIVElatlng.latitude)
MIDDLE_latitude += ARRIVElatlng.latitude;
else
MIDDLE_latitude += STARTlatlng.latitude;
if (STARTlatlng.longitude > ARRIVElatlng.longitude)
MIDDLE_longitude += ARRIVElatlng.longitude;
else
MIDDLE_longitude += STARTlatlng.longitude;
MIDDLElatlng = new LatLng(MIDDLE_latitude, MIDDLE_longitude);
if (MIDDLE_latitude <= 0.0108 || MIDDLE_longitude <= 0.0108) { //출발지와 도착지가 중간지점에서부터 1.2km 이상이면,
MIDDLE_ZOOM = 14;
} else if (MIDDLE_latitude <= 0.0216 || MIDDLE_longitude <= 0.0216) {
MIDDLE_ZOOM = 13;
} else if (MIDDLE_latitude <= 0.0432 || MIDDLE_longitude <= 0.0432) {
MIDDLE_ZOOM = 12;
} else if (MIDDLE_latitude <= 0.0864 || MIDDLE_longitude <= 0.0864) {
MIDDLE_ZOOM = 11;
} else if (MIDDLE_latitude <= 0.1728 || MIDDLE_longitude <= 0.1728) {
MIDDLE_ZOOM = 10;
} else if (MIDDLE_latitude <= 0.3456 || MIDDLE_longitude <= 0.3456) {
MIDDLE_ZOOM = 9;
}
quitReceiver = new QuitReceiver();
}
void click(){
INFObutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.setContentView(R.layout.my_taxi_dialog);
dialog.show();
MYDIALOGlist = dialog.findViewById(R.id.MYDIALOGlist);
TIMEtext = dialog.findViewById(R.id.TIMEtext);
PRICEtext = dialog.findViewById(R.id.PRICEtext);
DISTANCEtext = dialog.findViewById(R.id.DISTANCEtext);
PERSONtext = dialog.findViewById(R.id.PERSONtext);
OUTbutton = dialog.findViewById(R.id.OUTbutton);
PAYbutton = dialog.findViewById(R.id.PAYbutton);
MEMBERSquery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data_Members data_members = snapshot.getValue(Data_Members.class);
if (data_members.getJOIN()) {
Log.e("JOIN", "왜");
PAYbutton.setText("채팅 창으로");
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
MYDIALOGlist.setAdapter(adapter);
TIMEtext.setText(TIME);
PRICEtext.setText(PAY + "원");
DISTANCEtext.setText(DISTANCE);
PERSONtext.setText(adapter.getCount() + "/" + Max);
OUTbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
OUTDIALOG();
OUTdialog.show();
}
});
PAYbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(PAYbutton.getText().toString().equals("결제하기")) {
dialog.dismiss();
PAYDIALOG(Integer.parseInt(PAY));
PAYdialog.show();
}else{
Intent intent1 = new Intent(getApplicationContext(),Post_Call.class);
intent1.putExtra("INDEX",INDEX);
dialog.dismiss();
startActivity(intent1);
}
}
});
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_taxi);
init();
click();
// Custom Adapter Instance 생성 및 ListView에 Adapter 지정
adapter = new My_taxiAdapter();
LISTview.setAdapter(adapter);
/*LISTview.addHeaderView();*/
Query query = mDatabase.child("post-members").orderByChild("index").equalTo(INDEX);
final Query query1 = mDatabase.child("post").orderByChild("index").equalTo(INDEX);
Log.e("index",INDEXtext.getText().toString());
query.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Data_Members data_members = dataSnapshot.getValue(Data_Members.class);
adapter.addItem(data_members.getPROFILEURL(),data_members.getUSER1(),data_members.getGENDER());
adapter.notifyDataSetChanged();
query1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot : dataSnapshot.getChildren()) {
Data_Post data_post = appleSnapshot.getValue(Data_Post.class);
Log.e("COUNT", adapter.getCount() + "");
if (adapter.getCount() == data_post.getMaxPerson()) {
POINT = data_post.getPay() / data_post.getMaxPerson();
PAYDIALOG(data_post.getPay() / data_post.getMaxPerson());
//TODO : 다른 방식으로 결제하기 알리기(Toast, Background Message)
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
Intent QUITintent = new Intent(getApplicationContext(),main.class);
QUITintent.putExtra("MESSAGE","방장이 퇴장하여 퇴장처리 되었습니다.");
QUIT_PROCESS_reference();
startActivity(QUITintent);
finish();
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
Log.e("MAX",Max+"");
Log.e("adapter",adapter.getCount()+"");
if(Max == adapter.getCount())
PAYdialog.show();
}
private void PAYDIALOG(final int Point) {
PAYdialog = new AlertDialog.Builder(this);
PAYdialog.setTitle("결제 확인");
PAYdialog.setMessage(Point + "P : 결제 하시겠습니까?\n(결제 후, 택시가 호출됩니다.)");
PAYdialog.setPositiveButton("결제", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, int which) {
final Query query = mDatabase.child("user").orderByChild("email").equalTo(ID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
String path = "/" + dataSnapshot.getKey() + "/" + snapshot.getKey();
Map<String,Object> POINTmap = new HashMap<String,Object>();
if(user.getPoint()-Point < 0){
CHARGEDIALOG(user.getPoint());
CHARGEdialog.show();
}
else {
POINTmap.put("point", user.getPoint() - Point);
mDatabase.child(path).updateChildren(POINTmap);
Query query1 = mDatabase.child("post-members").orderByChild("index").equalTo(INDEXtext.getText().toString().split(" ")[0]); //INDEX를 통해 JOIN을 바꾸면, 전체가 바뀜(ID를 통해 접근을 해서 해당 ID만 바꾸기)
query1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data_Members data_members = snapshot.getValue(Data_Members.class);
String path = "/" + dataSnapshot.getKey() + "/" + snapshot.getKey();
Map<String, Object> JOINmap = new HashMap<String, Object>();
JOINmap.put("join", true);
mDatabase.child(path).updateChildren(JOINmap);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
Intent intent = new Intent(getApplicationContext(),Post_Call.class);
intent.putExtra("INDEX",INDEX);
dialog.dismiss();
startActivity(intent);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
});
}
void CHARGEDIALOG(final int Point){
CHARGEdialog = new AlertDialog.Builder(this);
CHARGEdialog.setTitle("포인트 부족");
CHARGEdialog.setMessage("포인트가 부족합니다.\n충전하러 가시겠습니까?");
CHARGEdialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), Charge.class);
intent.putExtra("POINT",Point+"");
Log.e("POINT",Point+"");
startActivity(intent);
}
});
}
void OUTDIALOG(){
OUTdialog = new AlertDialog.Builder(this);
OUTdialog.setTitle("퇴장");
if(INDEXtext.getText().toString() == ID)
OUTdialog.setMessage("노선에서 나가시겠습니까?\n(팀원 전체 퇴장됩니다.)");
else
OUTdialog.setMessage("노선에서 나가시겠습니까?");
OUTdialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onDestroy();
}
});
OUTdialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
QUIT_PROCESS_reference();
QUIT_PROCESS_database();
Intent intent = new Intent(getApplicationContext(),main.class);
intent.putExtra("MESSAGE","");
startActivity(intent);
finish();
}
});
}
void QUITDIALOG(Context context){
QUITdialog = new AlertDialog.Builder(context);
QUITdialog.setTitle("퇴장");
QUITdialog.setMessage("방장님이 퇴장하여,\n전체퇴장 처리되었습니다.");
QUITdialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onDestroy();
}
});
}
@Override
public void onConnected(@Nullable Bundle bundle) { }
@Override
public void onConnectionSuspended(int i) { }
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { }
@Override
public void onCameraIdle() { }
@Override
public void onCameraMove() { }
@Override
public void onMapReady(GoogleMap googleMap) {
MAPview = googleMap;
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(MIDDLElatlng,MIDDLE_ZOOM));
marker = googleMap.addMarker(new MarkerOptions().position(STARTlatlng).title("출발 위치").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
marker = googleMap.addMarker(new MarkerOptions().position(ARRIVElatlng).title("도착 위치").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
void QUIT_PROCESS_reference() {
SharedPreferences positionDATA = getSharedPreferences("positionDATA", MODE_PRIVATE);
SharedPreferences.Editor editor = positionDATA.edit();
editor.remove("DISTANCE");
editor.remove("PERSON");
editor.remove("MAX");
editor.remove("도착지");
editor.remove("TIME");
editor.remove("도착");
editor.remove("출발");
editor.remove("출발지");
editor.remove("INDEX");
editor.apply();
}
void QUIT_PROCESS_database(){
final Query POSTquery = mDatabase.child("post").orderByChild("index").equalTo(INDEX);
final Query MEMBERSquery_1 = mDatabase.child("post-members").orderByChild("index").equalTo(ID); //방장이 나갔을때, post-members전체 삭제
final Query MEMBERSquery_2 = mDatabase.child("post-members").orderByChild("userid").equalTo(ID); //참가인원이 나갔을 때,
final Query MESSAGEquery_1 = mDatabase.child("post-message").orderByChild("index").equalTo(ID); //방장이 나갔을때, post-message전체 삭제
final Query MESSAGEquery_2 = mDatabase.child("post-message").orderByChild("id").equalTo(ID); //참가인원이 나갔을 때,
POSTquery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data_Post data_post = snapshot.getValue(Data_Post.class);
if (ID.equals(data_post.getIndex())){ //방장일 때, 방 전체 파기(post/post-members/post-message)
Log.d("post","방장일 때");
mDatabase.child("post").child(snapshot.getKey()).removeValue();
MEMBERSquery_1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-members").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
MESSAGEquery_1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-message").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
else{ //참가한 인원일경우, person-1, post-members 파기
Log.d("post","참가일 때");
String path = "/" + dataSnapshot.getKey() + "/" + snapshot.getKey();
Map<String,Object> taskMap = new HashMap<String,Object>();
taskMap.put("person",data_post.getPerson()-1);
mDatabase.child(path).updateChildren(taskMap);
MEMBERSquery_2.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-members").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
MESSAGEquery_2.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
mDatabase.child("post-message").child(snapshot1.getKey()).removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
@Override
public void onBackPressed() {
OUTDIALOG();
OUTdialog.show();
}
}
| 24,191 | 0.565336 | 0.559818 | 474 | 48.710972 | 32.596024 | 219 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.801688 | false | false | 13 |
aaf196a71f93bfa2493731a021b4d17a4726c72c | 17,154,099,383,490 | f617c23ccb8791c723d1bce78eec58da3b5c22fe | /src/main/java/com/alhous/emam/samamarketing/beans/MessageController.java | f52e2d5aa071e9ec53385ee2f60a02a24d1e6ee3 | []
| no_license | silahi/SamaMarketing | https://github.com/silahi/SamaMarketing | 663b8da6aeba302ae4c3d8af78591a88bfabd844 | 07787d9b1aa0973ecb5b8239a4306f10c0e32af7 | refs/heads/main | 2023-02-15T22:43:16.435000 | 2020-12-29T16:39:52 | 2020-12-29T16:39:52 | 325,333,646 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alhous.emam.samamarketing.beans;
import com.alhous.emam.samamarketing.ejb.ClientFacade;
import com.alhous.emam.samamarketing.ejb.MessageFacade;
import com.alhous.emam.samamarketing.entites.Client;
import com.alhous.emam.samamarketing.entites.Message;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
/**
*
* @author silah
*/
@Named(value = "message")
@ViewScoped
public class MessageController implements Serializable {
private Message msg = new Message();
private List<Client> clients = new ArrayList();
private Client client = new Client();
private List<ClientFormat> contacts = new ArrayList();
private ClientFormat contact = new ClientFormat();
private List<ClientFormat> selectedContacts = new ArrayList();
private boolean tous;
private boolean quelques;
private boolean renderContact;
@Inject
ClientFacade cf;
@Inject
MessageFacade mf;
boolean exist = false;
@PostConstruct
public void init() {
cf.findAll().stream().forEach(c -> {
ClientFormat cfm = new ClientFormat(c);
contacts.add(cfm);
});
}
public void addClient(ClientFormat clf) {
selectedContacts.stream().filter(c -> c.getId() == clf.getId()).findFirst().ifPresent(c1 -> {
selectedContacts.remove(c1);
exist = true;
});
if (exist == false) {
selectedContacts.add(clf);
}
}
public void sendMessage(){
}
public void selectAll() {
quelques = false;
renderContact = false;
}
public void selectSome() {
tous = false;
renderContact = true;
}
public Message getMsg() {
return msg;
}
public void setMsg(Message msg) {
this.msg = msg;
}
public void send() {
msg.setDateEnvoi(new Date());
msg.setHeure(new Date());
}
public MessageController() {
}
public List<Client> getClients() {
return clients;
}
public void setClients(List<Client> clients) {
this.clients = clients;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<ClientFormat> getContacts() {
return contacts;
}
public void setContacts(List<ClientFormat> contacts) {
this.contacts = contacts;
}
public ClientFormat getContact() {
return contact;
}
public void setContact(ClientFormat contact) {
this.contact = contact;
}
public boolean isRenderContact() {
return renderContact;
}
public void setRenderContact(boolean renderContact) {
this.renderContact = renderContact;
}
public boolean isTous() {
return tous;
}
public void setTous(boolean tous) {
this.tous = tous;
}
public boolean isQuelques() {
return quelques;
}
public void setQuelques(boolean quelques) {
this.quelques = quelques;
}
public List<ClientFormat> getSelectedContacts() {
return selectedContacts;
}
public void setSelectedContacts(List<ClientFormat> selectedContacts) {
this.selectedContacts = selectedContacts;
}
}
| UTF-8 | Java | 3,509 | java | MessageController.java | Java | [
{
"context": "ed;\nimport javax.inject.Inject;\n\n/**\n *\n * @author silah\n */\n@Named(value = \"message\")\n@ViewScoped\npublic ",
"end": 521,
"score": 0.8801409006118774,
"start": 516,
"tag": "USERNAME",
"value": "silah"
}
]
| null | []
| package com.alhous.emam.samamarketing.beans;
import com.alhous.emam.samamarketing.ejb.ClientFacade;
import com.alhous.emam.samamarketing.ejb.MessageFacade;
import com.alhous.emam.samamarketing.entites.Client;
import com.alhous.emam.samamarketing.entites.Message;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
/**
*
* @author silah
*/
@Named(value = "message")
@ViewScoped
public class MessageController implements Serializable {
private Message msg = new Message();
private List<Client> clients = new ArrayList();
private Client client = new Client();
private List<ClientFormat> contacts = new ArrayList();
private ClientFormat contact = new ClientFormat();
private List<ClientFormat> selectedContacts = new ArrayList();
private boolean tous;
private boolean quelques;
private boolean renderContact;
@Inject
ClientFacade cf;
@Inject
MessageFacade mf;
boolean exist = false;
@PostConstruct
public void init() {
cf.findAll().stream().forEach(c -> {
ClientFormat cfm = new ClientFormat(c);
contacts.add(cfm);
});
}
public void addClient(ClientFormat clf) {
selectedContacts.stream().filter(c -> c.getId() == clf.getId()).findFirst().ifPresent(c1 -> {
selectedContacts.remove(c1);
exist = true;
});
if (exist == false) {
selectedContacts.add(clf);
}
}
public void sendMessage(){
}
public void selectAll() {
quelques = false;
renderContact = false;
}
public void selectSome() {
tous = false;
renderContact = true;
}
public Message getMsg() {
return msg;
}
public void setMsg(Message msg) {
this.msg = msg;
}
public void send() {
msg.setDateEnvoi(new Date());
msg.setHeure(new Date());
}
public MessageController() {
}
public List<Client> getClients() {
return clients;
}
public void setClients(List<Client> clients) {
this.clients = clients;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<ClientFormat> getContacts() {
return contacts;
}
public void setContacts(List<ClientFormat> contacts) {
this.contacts = contacts;
}
public ClientFormat getContact() {
return contact;
}
public void setContact(ClientFormat contact) {
this.contact = contact;
}
public boolean isRenderContact() {
return renderContact;
}
public void setRenderContact(boolean renderContact) {
this.renderContact = renderContact;
}
public boolean isTous() {
return tous;
}
public void setTous(boolean tous) {
this.tous = tous;
}
public boolean isQuelques() {
return quelques;
}
public void setQuelques(boolean quelques) {
this.quelques = quelques;
}
public List<ClientFormat> getSelectedContacts() {
return selectedContacts;
}
public void setSelectedContacts(List<ClientFormat> selectedContacts) {
this.selectedContacts = selectedContacts;
}
}
| 3,509 | 0.627244 | 0.626674 | 158 | 21.20886 | 19.65785 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35443 | false | false | 13 |
c5d5bed83ede1e15291bc68197d07065510a1b8f | 10,230,612,135,554 | 2cd72b96f2957afabf937a860ff0676c758db11c | /Java/Inter/src/Controller/Tela_Cadastro_Controller.java | 58ffb54f397ac6e86c5903b2ce10ef8f68e4a4b4 | []
| no_license | Baronzinho/inter | https://github.com/Baronzinho/inter | c74e6b4317dff4cabf7d87a499abeaf30af609eb | a339b67164a7275a90fba79c297c38d087db0181 | refs/heads/master | 2022-12-27T10:51:56.130000 | 2020-09-29T17:31:34 | 2020-09-29T17:31:34 | 284,312,503 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Controller;
import DAO.EnderecoDAO;
import Model.Endereco;
import Model.Usuario;
import Model.Mascara;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.swing.JOptionPane;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javax.imageio.ImageIO;
public class Tela_Cadastro_Controller implements Initializable {
@FXML
private TextField txtNomeUser;
@FXML
private Mascara txtCpfUser;
@FXML
private TextField txtIdadeUser;
@FXML
private Mascara txtTelefoneUser;
@FXML
private TextField txtPrecoAula;
@FXML
private TextField txtNumeroEndereco;
@FXML
private TextField txtRuaEndereco;
@FXML
private TextField txtBairroEndereco;
@FXML
private TextField txtCidadeEndereco;
@FXML
private Mascara txtCepEndereco;
@FXML
private TextField txtComplementoEndereco;
@FXML
private TextField txtSenhaUser;
@FXML
private TextField txtConfirmSenhaUser;
@FXML
private RadioButton rbAluno;
@FXML
private RadioButton rbProfessor;
@FXML
private Button btnCancelar;
@FXML
private Button btnCadastrar;
@FXML
private Button btnSelecionar;
@FXML
private Text txtImagem;
String path;
String absolutPath;
@Override
public void initialize(URL url, ResourceBundle rb) {
txtCpfUser.setMask("NNN.NNN.NNN-NN");
txtTelefoneUser.setMask("NN NNNN-NNNN?N");
txtCepEndereco.setMask("NNNNN-NNN");
}
@FXML
private void CancelarCadastro(ActionEvent event) throws IOException {
Stage stageAtual = (Stage) btnCancelar.getScene().getWindow();
stageAtual.close();
}
@FXML
private void SelecionaImagem(ActionEvent event) throws IOException {
try {
FileChooser fl = new FileChooser();
fl.getExtensionFilters().add(new FileChooser.ExtensionFilter("Imagens", "*.jpg", " *.png", "*.jpeg"));
File file = fl.showOpenDialog(new Stage());
txtImagem.setText(file.getAbsolutePath());
absolutPath = file.getAbsolutePath();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Nenhuma Imagem Selecionada", "Aviso", JOptionPane.WARNING_MESSAGE);
}
}
@FXML
private void CadastrarUser(ActionEvent event) throws IOException {
try {
Usuario newUser = new Usuario();
Endereco newEndereco = new Endereco();
DAO.UsuarioDAO userDao = new DAO.UsuarioDAO();
EnderecoDAO endeDAO = new EnderecoDAO();
if (txtCpfUser.getText().isEmpty() || txtTelefoneUser.getText().isEmpty() || txtIdadeUser.getText().isEmpty() || txtNomeUser.getText().isEmpty() || txtBairroEndereco.getText().isEmpty()
|| txtCidadeEndereco.getText().isEmpty() || txtComplementoEndereco.getText().isEmpty() || txtRuaEndereco.getText().isEmpty() || txtNumeroEndereco.getText().isEmpty()
|| txtCepEndereco.getText().isEmpty() || txtConfirmSenhaUser.getText().isEmpty() || txtSenhaUser.getText().isEmpty() || txtImagem.getText().equals("Imagem do Perfil")) {
JOptionPane.showMessageDialog(null, "Preencha todos os campos!");
} else {
if (txtSenhaUser.getText().equals(txtConfirmSenhaUser.getText())) {
newUser.setSenha(txtSenhaUser.getText());
newUser.setCpf(txtCpfUser.getText());
newUser.setContato(txtTelefoneUser.getText());
newUser.setIdade(Integer.parseInt(txtIdadeUser.getText()));
newUser.setNome(txtNomeUser.getText());
newEndereco.setBairro(txtBairroEndereco.getText());
newEndereco.setCidade(txtCidadeEndereco.getText());
newEndereco.setComplemento(txtComplementoEndereco.getText());
newEndereco.setRua(txtRuaEndereco.getText());
newEndereco.setNumero(txtNumeroEndereco.getText());
newEndereco.setCep(txtCepEndereco.getText());
endeDAO.inserirEndereco(newEndereco);
path = txtNomeUser.getText() + ".jpg";
newUser.setImgUser("/ImgsUsers/" + path);
File imgPath = new File(absolutPath);
BufferedImage bImage = ImageIO.read(imgPath);
ImageIO.write(bImage, "jpg", new File("C:\\Users\\Gabriel\\Desktop\\GITHUB\\inter\\Java\\Inter\\src\\ImgsUsers\\" + path));
} else {
JOptionPane.showMessageDialog(null, "As senhas não coincidem!");
}
if (rbAluno.isSelected() == true) {
newUser.setCargo("Aluno");
userDao.inserirUsuario(newUser);
JOptionPane.showMessageDialog(null, "Novo Usuario Cadastrado!");
} else if (rbProfessor.isSelected() == true) {
newUser.setCargo("Professor");
userDao.inserirUsuario(newUser);
JOptionPane.showMessageDialog(null, "Novo Usuario Cadastrado!");
} else {
JOptionPane.showMessageDialog(null, "Selecione um tipo de usuario!");
}
}
} catch (Exception ex) {
Logger.getLogger(Tela_Cadastro_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
Stage stageAtual = (Stage) btnCancelar.getScene().getWindow();
stageAtual.close();
}
@FXML
private void sair(ActionEvent event) {
System.exit(0);
}
}
| UTF-8 | Java | 6,237 | java | Tela_Cadastro_Controller.java | Java | [
{
"context": "ImageIO.write(bImage, \"jpg\", new File(\"C:\\\\Users\\\\Gabriel\\\\Desktop\\\\GITHUB\\\\inter\\\\Java\\\\Inter\\\\src\\\\ImgsUs",
"end": 5067,
"score": 0.9988885521888733,
"start": 5060,
"tag": "NAME",
"value": "Gabriel"
}
]
| null | []
| package Controller;
import DAO.EnderecoDAO;
import Model.Endereco;
import Model.Usuario;
import Model.Mascara;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.swing.JOptionPane;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javax.imageio.ImageIO;
public class Tela_Cadastro_Controller implements Initializable {
@FXML
private TextField txtNomeUser;
@FXML
private Mascara txtCpfUser;
@FXML
private TextField txtIdadeUser;
@FXML
private Mascara txtTelefoneUser;
@FXML
private TextField txtPrecoAula;
@FXML
private TextField txtNumeroEndereco;
@FXML
private TextField txtRuaEndereco;
@FXML
private TextField txtBairroEndereco;
@FXML
private TextField txtCidadeEndereco;
@FXML
private Mascara txtCepEndereco;
@FXML
private TextField txtComplementoEndereco;
@FXML
private TextField txtSenhaUser;
@FXML
private TextField txtConfirmSenhaUser;
@FXML
private RadioButton rbAluno;
@FXML
private RadioButton rbProfessor;
@FXML
private Button btnCancelar;
@FXML
private Button btnCadastrar;
@FXML
private Button btnSelecionar;
@FXML
private Text txtImagem;
String path;
String absolutPath;
@Override
public void initialize(URL url, ResourceBundle rb) {
txtCpfUser.setMask("NNN.NNN.NNN-NN");
txtTelefoneUser.setMask("NN NNNN-NNNN?N");
txtCepEndereco.setMask("NNNNN-NNN");
}
@FXML
private void CancelarCadastro(ActionEvent event) throws IOException {
Stage stageAtual = (Stage) btnCancelar.getScene().getWindow();
stageAtual.close();
}
@FXML
private void SelecionaImagem(ActionEvent event) throws IOException {
try {
FileChooser fl = new FileChooser();
fl.getExtensionFilters().add(new FileChooser.ExtensionFilter("Imagens", "*.jpg", " *.png", "*.jpeg"));
File file = fl.showOpenDialog(new Stage());
txtImagem.setText(file.getAbsolutePath());
absolutPath = file.getAbsolutePath();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Nenhuma Imagem Selecionada", "Aviso", JOptionPane.WARNING_MESSAGE);
}
}
@FXML
private void CadastrarUser(ActionEvent event) throws IOException {
try {
Usuario newUser = new Usuario();
Endereco newEndereco = new Endereco();
DAO.UsuarioDAO userDao = new DAO.UsuarioDAO();
EnderecoDAO endeDAO = new EnderecoDAO();
if (txtCpfUser.getText().isEmpty() || txtTelefoneUser.getText().isEmpty() || txtIdadeUser.getText().isEmpty() || txtNomeUser.getText().isEmpty() || txtBairroEndereco.getText().isEmpty()
|| txtCidadeEndereco.getText().isEmpty() || txtComplementoEndereco.getText().isEmpty() || txtRuaEndereco.getText().isEmpty() || txtNumeroEndereco.getText().isEmpty()
|| txtCepEndereco.getText().isEmpty() || txtConfirmSenhaUser.getText().isEmpty() || txtSenhaUser.getText().isEmpty() || txtImagem.getText().equals("Imagem do Perfil")) {
JOptionPane.showMessageDialog(null, "Preencha todos os campos!");
} else {
if (txtSenhaUser.getText().equals(txtConfirmSenhaUser.getText())) {
newUser.setSenha(txtSenhaUser.getText());
newUser.setCpf(txtCpfUser.getText());
newUser.setContato(txtTelefoneUser.getText());
newUser.setIdade(Integer.parseInt(txtIdadeUser.getText()));
newUser.setNome(txtNomeUser.getText());
newEndereco.setBairro(txtBairroEndereco.getText());
newEndereco.setCidade(txtCidadeEndereco.getText());
newEndereco.setComplemento(txtComplementoEndereco.getText());
newEndereco.setRua(txtRuaEndereco.getText());
newEndereco.setNumero(txtNumeroEndereco.getText());
newEndereco.setCep(txtCepEndereco.getText());
endeDAO.inserirEndereco(newEndereco);
path = txtNomeUser.getText() + ".jpg";
newUser.setImgUser("/ImgsUsers/" + path);
File imgPath = new File(absolutPath);
BufferedImage bImage = ImageIO.read(imgPath);
ImageIO.write(bImage, "jpg", new File("C:\\Users\\Gabriel\\Desktop\\GITHUB\\inter\\Java\\Inter\\src\\ImgsUsers\\" + path));
} else {
JOptionPane.showMessageDialog(null, "As senhas não coincidem!");
}
if (rbAluno.isSelected() == true) {
newUser.setCargo("Aluno");
userDao.inserirUsuario(newUser);
JOptionPane.showMessageDialog(null, "Novo Usuario Cadastrado!");
} else if (rbProfessor.isSelected() == true) {
newUser.setCargo("Professor");
userDao.inserirUsuario(newUser);
JOptionPane.showMessageDialog(null, "Novo Usuario Cadastrado!");
} else {
JOptionPane.showMessageDialog(null, "Selecione um tipo de usuario!");
}
}
} catch (Exception ex) {
Logger.getLogger(Tela_Cadastro_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
Stage stageAtual = (Stage) btnCancelar.getScene().getWindow();
stageAtual.close();
}
@FXML
private void sair(ActionEvent event) {
System.exit(0);
}
}
| 6,237 | 0.62957 | 0.62941 | 165 | 36.793938 | 33.942822 | 197 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.806061 | false | false | 13 |
de54a49c213e3c3ebb455d57ac78eba843ecb20b | 1,279,900,314,828 | 8217538d8621b35ec0fe66cf832ece7153323549 | /MY LEARNINGS & NOTES/PersonIndSkillRatingBasedOnDesignPattern/src/com/PISR/impl/IndustorySkillRatingImpl.java | bf0513a928d7f39f6af2a79bbe83f64624e35785 | []
| no_license | gautamp33/Notes | https://github.com/gautamp33/Notes | 8682a5d3b1685a5c1351825fe20a15257e80d293 | e4c3bf405dd46f6042800fc48ba98bba047192a0 | refs/heads/master | 2022-12-28T05:11:52.529000 | 2019-11-06T13:43:15 | 2019-11-06T13:43:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.PISR.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.PISR.Util.Utility;
import com.PISR.interfacce.IndustoryTypeSkillRatingInterfacce;
import com.PISR.model.IndustoryTypeSkillsRating;
import com.PISR.model.Person;
public class IndustorySkillRatingImpl implements IndustoryTypeSkillRatingInterfacce {
public void getNameIdPhoneBySkills(List<String> listOfLines) throws IOException{
/* List<String> listOfReturnedLines= Utility.getContentOfInputFileFromFilePath("C:\\users\\neha\\Desktop\\PersonSkillSample.txt");
for(int i=0;i<listOfReturnedLines.size();i++){
String line=listOfReturnedLines.get(i);
String[] splitedLine=line.split(",");
String name=splitedLine[0];
String adharId=splitedLine[1];
Person person =new Person();
System.out.println("byskills "+person.getName());
person.setAdharId(adharId);
*/
}
public void getNameIdPhoneBySkills(String skill) throws IOException {
// TODO Auto-generated method stub
List<String> listOfReturnedLines= Utility.getContentOfInputFileFromFilePath("C:\\users\\neha\\Desktop\\PersonSkillSample.txt");
List<Person> listOfPerson=Utility.getListOfPerson(listOfReturnedLines);
Person person ;
//System.out.println("listOfPerson "+listOfPerson);
for (int i = 0; i < listOfPerson.size(); i++) {
person =listOfPerson.get(i);
// System.out.println("person "+person);
// List<IndustoryTypeSkillsRating> listofIndskillsRating= listOfIndustoryTypeSkillsRatingPerPerson.get(i);
//System.out.println("getname 99 "+person.getName());
System.out.println("Name:-"+person.getName());
System.out.println("Adhar Id:-"+person.getAdharId());
System.out.println("Phone no:-"+person.getPhoneNo());
//System.out.println("jj"+ person.getListOfIndustoryTypeSkillsRatingPerPerson());
//System.out.println("$%$ "+listOfIndSkillRate.size());
/* for (int j = 0; j < listOfIndSkillRate.size(); j++) {
// IndustoryTypeSkillsRating industoryTypeSkillsRating=person.this.getListOfIndustoryTypeSkillsRatingPerPerson.get(j);
// System.out.println("i m here");
}*/
// System.out.println("*************************************");
List<IndustoryTypeSkillsRating> listOfIndSkillRate =person.getListOfIndustoryTypeSkillsRatingPerPerson();
System.out.println(listOfIndSkillRate.get(i).getSkills().length());
System.out.println(listOfIndSkillRate.size());
for (int j = 0; j < listOfIndSkillRate.size(); j++) {
IndustoryTypeSkillsRating industoryTypeSkillsRating =listOfIndSkillRate.get(j);
//System.out.println(listOfIndSkillRate.get(0));
System.out.println(industoryTypeSkillsRating.getIndustoryType());
System.out.println(industoryTypeSkillsRating.getSkills());
System.out.println(industoryTypeSkillsRating.getRating());
}
}
}
}
| UTF-8 | Java | 2,964 | java | IndustorySkillRatingImpl.java | Java | []
| null | []
| package com.PISR.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.PISR.Util.Utility;
import com.PISR.interfacce.IndustoryTypeSkillRatingInterfacce;
import com.PISR.model.IndustoryTypeSkillsRating;
import com.PISR.model.Person;
public class IndustorySkillRatingImpl implements IndustoryTypeSkillRatingInterfacce {
public void getNameIdPhoneBySkills(List<String> listOfLines) throws IOException{
/* List<String> listOfReturnedLines= Utility.getContentOfInputFileFromFilePath("C:\\users\\neha\\Desktop\\PersonSkillSample.txt");
for(int i=0;i<listOfReturnedLines.size();i++){
String line=listOfReturnedLines.get(i);
String[] splitedLine=line.split(",");
String name=splitedLine[0];
String adharId=splitedLine[1];
Person person =new Person();
System.out.println("byskills "+person.getName());
person.setAdharId(adharId);
*/
}
public void getNameIdPhoneBySkills(String skill) throws IOException {
// TODO Auto-generated method stub
List<String> listOfReturnedLines= Utility.getContentOfInputFileFromFilePath("C:\\users\\neha\\Desktop\\PersonSkillSample.txt");
List<Person> listOfPerson=Utility.getListOfPerson(listOfReturnedLines);
Person person ;
//System.out.println("listOfPerson "+listOfPerson);
for (int i = 0; i < listOfPerson.size(); i++) {
person =listOfPerson.get(i);
// System.out.println("person "+person);
// List<IndustoryTypeSkillsRating> listofIndskillsRating= listOfIndustoryTypeSkillsRatingPerPerson.get(i);
//System.out.println("getname 99 "+person.getName());
System.out.println("Name:-"+person.getName());
System.out.println("Adhar Id:-"+person.getAdharId());
System.out.println("Phone no:-"+person.getPhoneNo());
//System.out.println("jj"+ person.getListOfIndustoryTypeSkillsRatingPerPerson());
//System.out.println("$%$ "+listOfIndSkillRate.size());
/* for (int j = 0; j < listOfIndSkillRate.size(); j++) {
// IndustoryTypeSkillsRating industoryTypeSkillsRating=person.this.getListOfIndustoryTypeSkillsRatingPerPerson.get(j);
// System.out.println("i m here");
}*/
// System.out.println("*************************************");
List<IndustoryTypeSkillsRating> listOfIndSkillRate =person.getListOfIndustoryTypeSkillsRatingPerPerson();
System.out.println(listOfIndSkillRate.get(i).getSkills().length());
System.out.println(listOfIndSkillRate.size());
for (int j = 0; j < listOfIndSkillRate.size(); j++) {
IndustoryTypeSkillsRating industoryTypeSkillsRating =listOfIndSkillRate.get(j);
//System.out.println(listOfIndSkillRate.get(0));
System.out.println(industoryTypeSkillsRating.getIndustoryType());
System.out.println(industoryTypeSkillsRating.getSkills());
System.out.println(industoryTypeSkillsRating.getRating());
}
}
}
}
| 2,964 | 0.716599 | 0.713563 | 96 | 29.875 | 33.439388 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.104167 | false | false | 13 |
0fa60bfb921910bec9550703bebea6d6643ad130 | 33,887,291,987,982 | 7134a50e2a8c356b2cbd2739070bd84ffe6d7f9a | /app/src/main/java/com/robsonp/agenda/view/schedule/AgendamentoScheduleEvent.java | 5a4dcd855f89c00b5cd2775c43a9f4b5a1126925 | []
| no_license | luiz158/agenda | https://github.com/luiz158/agenda | 015464d0a4b9fb4f99409b62c94aae9530d0bfe6 | 3aca436a1d7c397b93f324d0cf1bb39896bb837d | refs/heads/master | 2021-01-22T09:58:14.278000 | 2013-04-05T19:26:25 | 2013-04-05T19:26:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.robsonp.agenda.view.schedule;
import com.robsonp.agenda.domain.Agendamento;
import org.primefaces.model.DefaultScheduleEvent;
public class AgendamentoScheduleEvent extends DefaultScheduleEvent {
private Agendamento agendamento;
public AgendamentoScheduleEvent(Agendamento agendamento) {
this.agendamento = agendamento;
setStartDate(agendamento.getInicio());
setEndDate(agendamento.getTermino());
setTitle(agendamento.getObjetivo() + " em " + agendamento.getProjeto());
}
public Agendamento getAgendamento() {
return agendamento;
}
}
| UTF-8 | Java | 619 | java | AgendamentoScheduleEvent.java | Java | []
| null | []
| package com.robsonp.agenda.view.schedule;
import com.robsonp.agenda.domain.Agendamento;
import org.primefaces.model.DefaultScheduleEvent;
public class AgendamentoScheduleEvent extends DefaultScheduleEvent {
private Agendamento agendamento;
public AgendamentoScheduleEvent(Agendamento agendamento) {
this.agendamento = agendamento;
setStartDate(agendamento.getInicio());
setEndDate(agendamento.getTermino());
setTitle(agendamento.getObjetivo() + " em " + agendamento.getProjeto());
}
public Agendamento getAgendamento() {
return agendamento;
}
}
| 619 | 0.728594 | 0.728594 | 21 | 28.476191 | 25.257944 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 13 |
75315d50153386b67e1d6cf3fde91dd697e37727 | 28,518,582,847,590 | 6bf84729b43079e58b3b4d187fa25da12a68d3dd | /MostPopularWSClient/src/demoappclient/SimpleTestClient.java | dbfbb1ed51ede3bbdc5a822de2a7944a936c89b0 | []
| no_license | ccstartfish101/MostPopularGameMode | https://github.com/ccstartfish101/MostPopularGameMode | 4a3686b97f532dd50f1f435e1b745a9a122e6f88 | e4febe1e72bf48d61913d249917e7ca69240e54d | refs/heads/master | 2021-05-27T00:51:22.632000 | 2014-01-29T02:53:15 | 2014-01-29T02:53:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package demoappclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
public class SimpleTestClient {
private static final String DEMOAPP_URL = "http://localhost:8888/mostpopularws";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
correctnessTest();
stressTest();
}
public static void stressTest()
{
int numberOfRequests = 100;
int round = 5;
double requestsPerSecond = 0;
for (int i=0; i < round; i++){
requestsPerSecond =
(double)numberOfRequests/dispatchRequests(numberOfRequests);
numberOfRequests *=2;
}
System.out.println("Average number of requests per second : " + requestsPerSecond);
}
public static double dispatchRequests(int numberofRequests){
ArrayList<Thread> threads = new ArrayList<Thread>();
String[] gameModes = {"Single", "Multi", "Dual", "Group"};
Random rn = new Random();
long startTime = System.currentTimeMillis();
for (int i = 0; i < numberofRequests; i++) {
char[] c = {(char)(rn.nextInt(26) + 'A'), (char)(rn.nextInt(26) + 'A')};
String countryCode = String.valueOf(c);
Runnable task = new GameModeQueryRequest(countryCode, gameModes[rn.nextInt(4)]);
Thread worker = new Thread(task);
// We can set the name of the thread
worker.setName("Thread - " + String.valueOf(i));
// Start the thread, never call method run() direct
worker.start();
// Remember the thread for later usage
threads.add(worker);
}
for (int i = 0; i < numberofRequests; i++){
try {
threads.get(i).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Handling "+ numberofRequests +" requests at one time costs :" + (double)totalTime/1000.0 + "seconds");
return (double)totalTime/1000.0;
}
public static void correctnessTest()
{
try {
assert("MostPopular : Single".equals( fetchMostPopular("US","Single")));
assert("MostPopular : Single".equals( fetchMostPopular("US","Single")));
assert("MostPopular : Single".equals( fetchMostPopular("US","Multi")));
assert("MostPopular : Multi".equals( fetchMostPopular("US","Multi")));
assert("MostPopular : Dual".equals( fetchMostPopular("UK","Dual")));
assert("MostPopular : Single".equals( fetchMostPopular("UK","Single")));
assert("MostPopular : Multi".equals( fetchMostPopular("FR","Multi")));
assert(fetchMostPopular("JP", null) == null);
assert("MostPopular : Single".equals( fetchMostPopular("JP","Single")));
System.out.println("Test done");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String fetchMostPopular(String Country, String GameMode) throws Exception {
URL url = new URL(DEMOAPP_URL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Cookie", "Country=US;GameMode=Single");
conn.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String respString = null;
try {
respString = in.readLine();
} catch (Throwable t){
in.close();
}
in.close();
return respString;
}
}
| UTF-8 | Java | 3,698 | java | SimpleTestClient.java | Java | []
| null | []
| package demoappclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
public class SimpleTestClient {
private static final String DEMOAPP_URL = "http://localhost:8888/mostpopularws";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
correctnessTest();
stressTest();
}
public static void stressTest()
{
int numberOfRequests = 100;
int round = 5;
double requestsPerSecond = 0;
for (int i=0; i < round; i++){
requestsPerSecond =
(double)numberOfRequests/dispatchRequests(numberOfRequests);
numberOfRequests *=2;
}
System.out.println("Average number of requests per second : " + requestsPerSecond);
}
public static double dispatchRequests(int numberofRequests){
ArrayList<Thread> threads = new ArrayList<Thread>();
String[] gameModes = {"Single", "Multi", "Dual", "Group"};
Random rn = new Random();
long startTime = System.currentTimeMillis();
for (int i = 0; i < numberofRequests; i++) {
char[] c = {(char)(rn.nextInt(26) + 'A'), (char)(rn.nextInt(26) + 'A')};
String countryCode = String.valueOf(c);
Runnable task = new GameModeQueryRequest(countryCode, gameModes[rn.nextInt(4)]);
Thread worker = new Thread(task);
// We can set the name of the thread
worker.setName("Thread - " + String.valueOf(i));
// Start the thread, never call method run() direct
worker.start();
// Remember the thread for later usage
threads.add(worker);
}
for (int i = 0; i < numberofRequests; i++){
try {
threads.get(i).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Handling "+ numberofRequests +" requests at one time costs :" + (double)totalTime/1000.0 + "seconds");
return (double)totalTime/1000.0;
}
public static void correctnessTest()
{
try {
assert("MostPopular : Single".equals( fetchMostPopular("US","Single")));
assert("MostPopular : Single".equals( fetchMostPopular("US","Single")));
assert("MostPopular : Single".equals( fetchMostPopular("US","Multi")));
assert("MostPopular : Multi".equals( fetchMostPopular("US","Multi")));
assert("MostPopular : Dual".equals( fetchMostPopular("UK","Dual")));
assert("MostPopular : Single".equals( fetchMostPopular("UK","Single")));
assert("MostPopular : Multi".equals( fetchMostPopular("FR","Multi")));
assert(fetchMostPopular("JP", null) == null);
assert("MostPopular : Single".equals( fetchMostPopular("JP","Single")));
System.out.println("Test done");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String fetchMostPopular(String Country, String GameMode) throws Exception {
URL url = new URL(DEMOAPP_URL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Cookie", "Country=US;GameMode=Single");
conn.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String respString = null;
try {
respString = in.readLine();
} catch (Throwable t){
in.close();
}
in.close();
return respString;
}
}
| 3,698 | 0.639535 | 0.631963 | 103 | 34.902912 | 26.395983 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.029126 | false | false | 13 |
8bdc463a364b9846c6e503fa9825cbc181f22cbf | 14,018,773,298,777 | 13be5fbda63a4838d2f9cbcf11ab94b6b40cc3ef | /server/src/main/java/com/workoffice/controller/UsersController.java | 717dbe831dde0478d077b88a28d07670daf48d10 | []
| no_license | pawfa/work-office-app | https://github.com/pawfa/work-office-app | 717b19944192ec23723df5a1b66b2bd2dffa345b | 7bb50f71414fee558b89c0c0304d6048a75b8efb | refs/heads/master | 2023-01-24T19:03:29.783000 | 2018-06-05T17:45:43 | 2018-06-05T17:45:43 | 109,609,606 | 2 | 2 | null | false | 2022-12-29T08:05:35 | 2017-11-05T19:34:19 | 2018-06-05T17:45:51 | 2022-12-29T08:05:33 | 7,564 | 1 | 1 | 12 | TypeScript | false | false | package com.workoffice.controller;
import com.workoffice.entity.Emp;
import com.workoffice.entity.User;
import com.workoffice.entity.Person;
import com.workoffice.service.Exceptions.UserExistsException;
import com.workoffice.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
@CrossOrigin
@RestController
public class UsersController {
private UserService userService;
private final Log logger = LogFactory.getLog(getClass());
@ExceptionHandler({ UserExistsException.class })
public ResponseEntity<Object> handleAccessDeniedException(Exception ex) {
return new ResponseEntity<>(
ex.getMessage(), new HttpHeaders(), HttpStatus.FORBIDDEN);
}
@Autowired
public UsersController(UserService userService) {
this.userService = userService;
}
@GetMapping("/all")
public Iterable<User> getAllEmployees() {
return userService.findAll();
}
@PostMapping("/add/person")
public ResponseEntity addUser(@RequestBody Person person) throws UserExistsException {
logger.info(person.getEmail());
userService.save(person);
return new ResponseEntity(HttpStatus.OK);
}
@PostMapping("/add/emp")
public ResponseEntity addEmployee(@RequestBody Emp emp) throws UserExistsException {
logger.info(emp.getEmail());
userService.save(emp);
return new ResponseEntity(HttpStatus.OK);
}
@GetMapping("/profile")
public User getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
logger.info(currentPrincipalName);
return userService.findByEmail(authentication.getName());
}
}
| UTF-8 | Java | 2,246 | java | UsersController.java | Java | []
| null | []
| package com.workoffice.controller;
import com.workoffice.entity.Emp;
import com.workoffice.entity.User;
import com.workoffice.entity.Person;
import com.workoffice.service.Exceptions.UserExistsException;
import com.workoffice.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
@CrossOrigin
@RestController
public class UsersController {
private UserService userService;
private final Log logger = LogFactory.getLog(getClass());
@ExceptionHandler({ UserExistsException.class })
public ResponseEntity<Object> handleAccessDeniedException(Exception ex) {
return new ResponseEntity<>(
ex.getMessage(), new HttpHeaders(), HttpStatus.FORBIDDEN);
}
@Autowired
public UsersController(UserService userService) {
this.userService = userService;
}
@GetMapping("/all")
public Iterable<User> getAllEmployees() {
return userService.findAll();
}
@PostMapping("/add/person")
public ResponseEntity addUser(@RequestBody Person person) throws UserExistsException {
logger.info(person.getEmail());
userService.save(person);
return new ResponseEntity(HttpStatus.OK);
}
@PostMapping("/add/emp")
public ResponseEntity addEmployee(@RequestBody Emp emp) throws UserExistsException {
logger.info(emp.getEmail());
userService.save(emp);
return new ResponseEntity(HttpStatus.OK);
}
@GetMapping("/profile")
public User getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
logger.info(currentPrincipalName);
return userService.findByEmail(authentication.getName());
}
}
| 2,246 | 0.748442 | 0.748442 | 66 | 33.030304 | 25.629629 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
872f3c2526af2c9987b95fc46a41cecd072d4fd0 | 5,231,270,220,697 | a372ca8a41f00327bc94a3d35db01e2a4c1d1625 | /src/main/java/uk/kukino/sgo/sgf/Header.java | 32f4ee32a9ae925e66bb47aecc2af6cd113c34ff | []
| no_license | kuking/SympatheticGo | https://github.com/kuking/SympatheticGo | bc61d846aac53e1eaa1e450bdfd8a8a2c43a16a3 | 7758c6534b8d576cffd1f783278d604055f6064d | refs/heads/master | 2020-08-22T00:11:59.425000 | 2020-06-03T15:51:52 | 2020-06-03T15:51:52 | 216,278,342 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.kukino.sgo.sgf;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
public class Header
{
public Charset charset; //CA
public byte fileFormat; //FF
public GameType gameType; //GM
public CharSequence application; //AP
public byte variationsFormat; //ST
public byte size; //SZ
public CharSequence name; //GN
public CharSequence comment; //C
public CharSequence blackName; //PB
public CharSequence whiteName; //WP
public LocalDateTime dateTime; //DT
public int timeLimitSecs; //TM
public Rule rules; //RU
public byte handicap; //HA
public float komi; //KM
public Rank blackRank; //BR
public Rank whiteRank; //WR
public CharSequence place; //PC
public Result result; //RE
public Species blackSpecies; //BS
public Species whiteSpecies; //WS
public void reset()
{
charset = StandardCharsets.UTF_8;
fileFormat = -1;
gameType = null;
application = null;
variationsFormat = 0;
size = -1;
name = null;
comment = null;
blackName = null;
whiteName = null;
dateTime = null;
timeLimitSecs = 0;
handicap = 0;
rules = null;
komi = Float.NaN;
blackRank = null;
whiteRank = null;
place = null;
result = null;
blackSpecies = null;
whiteSpecies = null;
}
public Header clone()
{
final Header clone = new Header();
clone.charset = charset;
clone.fileFormat = fileFormat;
clone.gameType = gameType;
clone.application = application;
clone.variationsFormat = variationsFormat;
clone.size = size;
clone.name = name;
clone.comment = comment;
clone.blackName = blackName;
clone.whiteName = whiteName;
clone.dateTime = dateTime;
clone.timeLimitSecs = timeLimitSecs;
clone.handicap = handicap;
clone.rules = rules;
clone.komi = komi;
clone.blackRank = blackRank == null ? null : blackRank.clone();
clone.whiteRank = whiteRank == null ? null : whiteRank.clone();
clone.place = place;
clone.result = result == null ? null : result.clone();
clone.blackSpecies = blackSpecies;
clone.whiteSpecies = whiteSpecies;
return clone;
}
public boolean isEmpty()
{
return charset == StandardCharsets.UTF_8 &&
fileFormat == -1 &&
gameType == null &&
application == null &&
variationsFormat == 0 &&
size == -1 &&
name == null &&
comment == null &&
blackName == null &&
whiteName == null &&
dateTime == null &&
timeLimitSecs == 0 &&
rules == null &&
handicap == 0 &&
Float.isNaN(komi) &&
blackRank == null &&
whiteRank == null &&
place == null &&
result == null &&
blackSpecies == null &&
whiteSpecies == null;
}
}
| UTF-8 | Java | 3,161 | java | Header.java | Java | []
| null | []
| package uk.kukino.sgo.sgf;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
public class Header
{
public Charset charset; //CA
public byte fileFormat; //FF
public GameType gameType; //GM
public CharSequence application; //AP
public byte variationsFormat; //ST
public byte size; //SZ
public CharSequence name; //GN
public CharSequence comment; //C
public CharSequence blackName; //PB
public CharSequence whiteName; //WP
public LocalDateTime dateTime; //DT
public int timeLimitSecs; //TM
public Rule rules; //RU
public byte handicap; //HA
public float komi; //KM
public Rank blackRank; //BR
public Rank whiteRank; //WR
public CharSequence place; //PC
public Result result; //RE
public Species blackSpecies; //BS
public Species whiteSpecies; //WS
public void reset()
{
charset = StandardCharsets.UTF_8;
fileFormat = -1;
gameType = null;
application = null;
variationsFormat = 0;
size = -1;
name = null;
comment = null;
blackName = null;
whiteName = null;
dateTime = null;
timeLimitSecs = 0;
handicap = 0;
rules = null;
komi = Float.NaN;
blackRank = null;
whiteRank = null;
place = null;
result = null;
blackSpecies = null;
whiteSpecies = null;
}
public Header clone()
{
final Header clone = new Header();
clone.charset = charset;
clone.fileFormat = fileFormat;
clone.gameType = gameType;
clone.application = application;
clone.variationsFormat = variationsFormat;
clone.size = size;
clone.name = name;
clone.comment = comment;
clone.blackName = blackName;
clone.whiteName = whiteName;
clone.dateTime = dateTime;
clone.timeLimitSecs = timeLimitSecs;
clone.handicap = handicap;
clone.rules = rules;
clone.komi = komi;
clone.blackRank = blackRank == null ? null : blackRank.clone();
clone.whiteRank = whiteRank == null ? null : whiteRank.clone();
clone.place = place;
clone.result = result == null ? null : result.clone();
clone.blackSpecies = blackSpecies;
clone.whiteSpecies = whiteSpecies;
return clone;
}
public boolean isEmpty()
{
return charset == StandardCharsets.UTF_8 &&
fileFormat == -1 &&
gameType == null &&
application == null &&
variationsFormat == 0 &&
size == -1 &&
name == null &&
comment == null &&
blackName == null &&
whiteName == null &&
dateTime == null &&
timeLimitSecs == 0 &&
rules == null &&
handicap == 0 &&
Float.isNaN(komi) &&
blackRank == null &&
whiteRank == null &&
place == null &&
result == null &&
blackSpecies == null &&
whiteSpecies == null;
}
}
| 3,161 | 0.560898 | 0.557102 | 108 | 28.268518 | 13.251559 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.648148 | false | false | 15 |
20aadf96f2b438b8ba76bd4862dbcc990154b738 | 12,635,793,851,183 | 6f672fb72caedccb841ee23f53e32aceeaf1895e | /nbc_source/src/com/phunware/nbc/sochi/content/ParcelableUtils.java | 98957ca26e0782b168993ab9d39114ce84a7ce4a | []
| no_license | cha63506/CompSecurity | https://github.com/cha63506/CompSecurity | 5c69743f660b9899146ed3cf21eceabe3d5f4280 | eee7e74f4088b9c02dd711c061fc04fb1e4e2654 | refs/heads/master | 2018-03-23T04:15:18.480000 | 2015-12-19T01:29:58 | 2015-12-19T01:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.phunware.nbc.sochi.content;
import android.os.Parcel;
import android.os.Parcelable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ParcelableUtils
{
public ParcelableUtils()
{
}
public static boolean readBoolean(Parcel parcel)
{
return parcel.readByte() == 1;
}
public static Date readDate(Parcel parcel)
{
if (parcel.readByte() == 1)
{
return new Date(parcel.readLong());
} else
{
return null;
}
}
public static Enum readEnum(Parcel parcel, Class class1)
{
parcel = parcel.readString();
if ("".equals(parcel))
{
return null;
} else
{
return Enum.valueOf(class1, parcel);
}
}
public static Map readIntStringMap(Parcel parcel)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
HashMap hashmap = new HashMap();
_L4:
return hashmap;
_L2:
HashMap hashmap1 = new HashMap();
int i = 0;
do
{
hashmap = hashmap1;
if (i >= j)
{
continue;
}
hashmap1.put(Integer.valueOf(parcel.readInt()), parcel.readString());
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static List readPKPassFieldList(Parcel parcel)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
Object obj = null;
_L4:
return ((List) (obj));
_L2:
ArrayList arraylist = new ArrayList();
int i = 0;
do
{
obj = arraylist;
if (i >= j)
{
continue;
}
arraylist.add(parcel.readParcelable(null));
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static Parcelable readParcelable(Parcel parcel)
{
Parcelable parcelable = null;
if (parcel.readByte() == 1)
{
parcelable = parcel.readParcelable(null);
}
return parcelable;
}
public static Map readParcelableMap(Parcel parcel, ClassLoader classloader)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
HashMap hashmap = new HashMap();
_L4:
return hashmap;
_L2:
HashMap hashmap1 = new HashMap();
int i = 0;
do
{
hashmap = hashmap1;
if (i >= j)
{
continue;
}
hashmap1.put(parcel.readString(), parcel.readParcelable(classloader));
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static String readString(Parcel parcel)
{
if (parcel.readByte() == 1)
{
return parcel.readString();
} else
{
return null;
}
}
public static Map readStringMap(Parcel parcel)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
Object obj = null;
_L4:
return ((Map) (obj));
_L2:
HashMap hashmap = new HashMap();
int i = 0;
do
{
obj = hashmap;
if (i >= j)
{
continue;
}
hashmap.put(parcel.readString(), parcel.readString());
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static URL readURL(Parcel parcel)
{
try
{
parcel = new URL(parcel.readString());
}
// Misplaced declaration of an exception variable
catch (Parcel parcel)
{
parcel.printStackTrace();
return null;
}
return parcel;
}
public static void write(Parcel parcel, Parcelable parcelable, int i)
{
int j;
if (parcelable == null)
{
j = 0;
} else
{
j = 1;
}
parcel.writeByte((byte)j);
if (parcelable != null)
{
parcel.writeParcelable(parcelable, i);
}
}
public static void write(Parcel parcel, Enum enum)
{
if (enum == null)
{
parcel.writeString("");
return;
} else
{
parcel.writeString(enum.name());
return;
}
}
public static void write(Parcel parcel, String s)
{
int i;
if (s == null)
{
i = 0;
} else
{
i = 1;
}
parcel.writeByte((byte)i);
if (s != null)
{
parcel.writeString(s);
}
}
public static void write(Parcel parcel, URL url)
{
parcel.writeString(url.toExternalForm());
}
public static void write(Parcel parcel, Date date)
{
int i;
if (date == null)
{
i = 0;
} else
{
i = 1;
}
parcel.writeByte((byte)i);
if (date != null)
{
parcel.writeLong(date.getTime());
}
}
public static void write(Parcel parcel, List list, int i)
{
if (list == null)
{
parcel.writeInt(-1);
} else
{
parcel.writeInt(list.size());
list = list.iterator();
while (list.hasNext())
{
parcel.writeParcelable((Parcelable)list.next(), i);
}
}
}
public static void write(Parcel parcel, Map map, int i)
{
if (map == null)
{
parcel.writeInt(-1);
} else
{
parcel.writeInt(map.keySet().size());
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
String s = (String)iterator.next();
parcel.writeString(s);
parcel.writeParcelable((Parcelable)map.get(s), i);
}
}
}
public static void write(Parcel parcel, boolean flag)
{
int i;
if (flag)
{
i = 1;
} else
{
i = 0;
}
parcel.writeByte((byte)i);
}
public static void writeIntStringMap(Parcel parcel, Map map)
{
if (map == null)
{
parcel.writeInt(-1);
} else
{
parcel.writeInt(map.keySet().size());
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
Integer integer = (Integer)iterator.next();
parcel.writeInt(integer.intValue());
parcel.writeString((String)map.get(integer));
}
}
}
}
| UTF-8 | Java | 7,274 | java | ParcelableUtils.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9996638894081116,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
]
| null | []
| // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.phunware.nbc.sochi.content;
import android.os.Parcel;
import android.os.Parcelable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ParcelableUtils
{
public ParcelableUtils()
{
}
public static boolean readBoolean(Parcel parcel)
{
return parcel.readByte() == 1;
}
public static Date readDate(Parcel parcel)
{
if (parcel.readByte() == 1)
{
return new Date(parcel.readLong());
} else
{
return null;
}
}
public static Enum readEnum(Parcel parcel, Class class1)
{
parcel = parcel.readString();
if ("".equals(parcel))
{
return null;
} else
{
return Enum.valueOf(class1, parcel);
}
}
public static Map readIntStringMap(Parcel parcel)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
HashMap hashmap = new HashMap();
_L4:
return hashmap;
_L2:
HashMap hashmap1 = new HashMap();
int i = 0;
do
{
hashmap = hashmap1;
if (i >= j)
{
continue;
}
hashmap1.put(Integer.valueOf(parcel.readInt()), parcel.readString());
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static List readPKPassFieldList(Parcel parcel)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
Object obj = null;
_L4:
return ((List) (obj));
_L2:
ArrayList arraylist = new ArrayList();
int i = 0;
do
{
obj = arraylist;
if (i >= j)
{
continue;
}
arraylist.add(parcel.readParcelable(null));
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static Parcelable readParcelable(Parcel parcel)
{
Parcelable parcelable = null;
if (parcel.readByte() == 1)
{
parcelable = parcel.readParcelable(null);
}
return parcelable;
}
public static Map readParcelableMap(Parcel parcel, ClassLoader classloader)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
HashMap hashmap = new HashMap();
_L4:
return hashmap;
_L2:
HashMap hashmap1 = new HashMap();
int i = 0;
do
{
hashmap = hashmap1;
if (i >= j)
{
continue;
}
hashmap1.put(parcel.readString(), parcel.readParcelable(classloader));
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static String readString(Parcel parcel)
{
if (parcel.readByte() == 1)
{
return parcel.readString();
} else
{
return null;
}
}
public static Map readStringMap(Parcel parcel)
{
int j = parcel.readInt();
if (j != -1) goto _L2; else goto _L1
_L1:
Object obj = null;
_L4:
return ((Map) (obj));
_L2:
HashMap hashmap = new HashMap();
int i = 0;
do
{
obj = hashmap;
if (i >= j)
{
continue;
}
hashmap.put(parcel.readString(), parcel.readString());
i++;
} while (true);
if (true) goto _L4; else goto _L3
_L3:
}
public static URL readURL(Parcel parcel)
{
try
{
parcel = new URL(parcel.readString());
}
// Misplaced declaration of an exception variable
catch (Parcel parcel)
{
parcel.printStackTrace();
return null;
}
return parcel;
}
public static void write(Parcel parcel, Parcelable parcelable, int i)
{
int j;
if (parcelable == null)
{
j = 0;
} else
{
j = 1;
}
parcel.writeByte((byte)j);
if (parcelable != null)
{
parcel.writeParcelable(parcelable, i);
}
}
public static void write(Parcel parcel, Enum enum)
{
if (enum == null)
{
parcel.writeString("");
return;
} else
{
parcel.writeString(enum.name());
return;
}
}
public static void write(Parcel parcel, String s)
{
int i;
if (s == null)
{
i = 0;
} else
{
i = 1;
}
parcel.writeByte((byte)i);
if (s != null)
{
parcel.writeString(s);
}
}
public static void write(Parcel parcel, URL url)
{
parcel.writeString(url.toExternalForm());
}
public static void write(Parcel parcel, Date date)
{
int i;
if (date == null)
{
i = 0;
} else
{
i = 1;
}
parcel.writeByte((byte)i);
if (date != null)
{
parcel.writeLong(date.getTime());
}
}
public static void write(Parcel parcel, List list, int i)
{
if (list == null)
{
parcel.writeInt(-1);
} else
{
parcel.writeInt(list.size());
list = list.iterator();
while (list.hasNext())
{
parcel.writeParcelable((Parcelable)list.next(), i);
}
}
}
public static void write(Parcel parcel, Map map, int i)
{
if (map == null)
{
parcel.writeInt(-1);
} else
{
parcel.writeInt(map.keySet().size());
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
String s = (String)iterator.next();
parcel.writeString(s);
parcel.writeParcelable((Parcelable)map.get(s), i);
}
}
}
public static void write(Parcel parcel, boolean flag)
{
int i;
if (flag)
{
i = 1;
} else
{
i = 0;
}
parcel.writeByte((byte)i);
}
public static void writeIntStringMap(Parcel parcel, Map map)
{
if (map == null)
{
parcel.writeInt(-1);
} else
{
parcel.writeInt(map.keySet().size());
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
Integer integer = (Integer)iterator.next();
parcel.writeInt(integer.intValue());
parcel.writeString((String)map.get(integer));
}
}
}
}
| 7,264 | 0.477591 | 0.467968 | 323 | 21.520124 | 18.394257 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 15 |
57620ff2191f6c930757be559c0291ce1290a42b | 26,096,221,357,548 | a00fe03c645e335c1d63b8d90f85e32b6eac3b61 | /src/main/java/com/example/repository/CategoryRepository.java | a878e32031aae5ff6bec560bbc6ea837b8a248b4 | []
| no_license | nhhung0000/BookShop | https://github.com/nhhung0000/BookShop | 50875914b1b1a5a578b7a346be856f57b148f5dc | 442477c08287a9b65653a4ff2edaf57c06a40afb | refs/heads/master | 2023-08-28T04:32:49.917000 | 2021-11-06T02:42:49 | 2021-11-06T02:42:49 | 424,983,684 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.entity.Category;
public interface CategoryRepository extends CrudRepository<Category, String> {
public Category findByName(String name);
}
| UTF-8 | Java | 254 | java | CategoryRepository.java | Java | []
| null | []
| package com.example.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.entity.Category;
public interface CategoryRepository extends CrudRepository<Category, String> {
public Category findByName(String name);
}
| 254 | 0.830709 | 0.830709 | 10 | 24.4 | 27.133743 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 15 |
288a4da0826abc64254899a81d9602865223d276 | 31,860,067,440,319 | 8e7614692bc230815aedb6db1cee13b030ac0bfd | /farAwaySFE/mine/cn/itcast/mobile/Ydsdwyxjlb.java | 598fd47cfc35e72e82ac1db1f1d9309c15a13392 | []
| no_license | bandy101/my_git_respository | https://github.com/bandy101/my_git_respository | 11e1a81ac370b5bbeb6b4d6de2ba08094389b46e | bb598c7606de1492c5ccbf0a338e8914d25d405c | refs/heads/master | 2020-06-01T00:09:48.735000 | 2019-04-16T10:29:09 | 2019-04-16T10:29:09 | 190,551,899 | 0 | 0 | null | true | 2019-06-06T09:13:52 | 2019-06-06T09:13:52 | 2019-04-16T10:31:06 | 2019-04-16T10:31:04 | 401,790 | 0 | 0 | 0 | null | false | false |
package cn.itcast.mobile;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>ydsdwyxjlb complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="ydsdwyxjlb">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cbbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="cdpd" type="{http://www.w3.org/2001/XMLSchema}double"/>
* <element name="ddjd" type="{http://www.w3.org/2001/XMLSchema}double"/>
* <element name="ddwd" type="{http://www.w3.org/2001/XMLSchema}double"/>
* <element name="fxlx" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="jzbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="jzjcbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="jzrzbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="zzdz" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ydsdwyxjlb", propOrder = {
"cbbh",
"cdpd",
"ddjd",
"ddwd",
"fxlx",
"jzbh",
"jzjcbh",
"jzrzbh",
"zzdz"
})
public class Ydsdwyxjlb {
protected String cbbh;
protected double cdpd;
protected double ddjd;
protected double ddwd;
protected String fxlx;
protected String jzbh;
protected String jzjcbh;
protected String jzrzbh;
protected String zzdz;
/**
* 获取cbbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getCbbh() {
return cbbh;
}
/**
* 设置cbbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCbbh(String value) {
this.cbbh = value;
}
/**
* 获取cdpd属性的值。
*
*/
public double getCdpd() {
return cdpd;
}
/**
* 设置cdpd属性的值。
*
*/
public void setCdpd(double value) {
this.cdpd = value;
}
/**
* 获取ddjd属性的值。
*
*/
public double getDdjd() {
return ddjd;
}
/**
* 设置ddjd属性的值。
*
*/
public void setDdjd(double value) {
this.ddjd = value;
}
/**
* 获取ddwd属性的值。
*
*/
public double getDdwd() {
return ddwd;
}
/**
* 设置ddwd属性的值。
*
*/
public void setDdwd(double value) {
this.ddwd = value;
}
/**
* 获取fxlx属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getFxlx() {
return fxlx;
}
/**
* 设置fxlx属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFxlx(String value) {
this.fxlx = value;
}
/**
* 获取jzbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getJzbh() {
return jzbh;
}
/**
* 设置jzbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setJzbh(String value) {
this.jzbh = value;
}
/**
* 获取jzjcbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getJzjcbh() {
return jzjcbh;
}
/**
* 设置jzjcbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setJzjcbh(String value) {
this.jzjcbh = value;
}
/**
* 获取jzrzbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getJzrzbh() {
return jzrzbh;
}
/**
* 设置jzrzbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setJzrzbh(String value) {
this.jzrzbh = value;
}
/**
* 获取zzdz属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getZzdz() {
return zzdz;
}
/**
* 设置zzdz属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setZzdz(String value) {
this.zzdz = value;
}
}
| GB18030 | Java | 5,176 | java | Ydsdwyxjlb.java | Java | []
| null | []
|
package cn.itcast.mobile;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>ydsdwyxjlb complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="ydsdwyxjlb">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cbbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="cdpd" type="{http://www.w3.org/2001/XMLSchema}double"/>
* <element name="ddjd" type="{http://www.w3.org/2001/XMLSchema}double"/>
* <element name="ddwd" type="{http://www.w3.org/2001/XMLSchema}double"/>
* <element name="fxlx" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="jzbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="jzjcbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="jzrzbh" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="zzdz" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ydsdwyxjlb", propOrder = {
"cbbh",
"cdpd",
"ddjd",
"ddwd",
"fxlx",
"jzbh",
"jzjcbh",
"jzrzbh",
"zzdz"
})
public class Ydsdwyxjlb {
protected String cbbh;
protected double cdpd;
protected double ddjd;
protected double ddwd;
protected String fxlx;
protected String jzbh;
protected String jzjcbh;
protected String jzrzbh;
protected String zzdz;
/**
* 获取cbbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getCbbh() {
return cbbh;
}
/**
* 设置cbbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCbbh(String value) {
this.cbbh = value;
}
/**
* 获取cdpd属性的值。
*
*/
public double getCdpd() {
return cdpd;
}
/**
* 设置cdpd属性的值。
*
*/
public void setCdpd(double value) {
this.cdpd = value;
}
/**
* 获取ddjd属性的值。
*
*/
public double getDdjd() {
return ddjd;
}
/**
* 设置ddjd属性的值。
*
*/
public void setDdjd(double value) {
this.ddjd = value;
}
/**
* 获取ddwd属性的值。
*
*/
public double getDdwd() {
return ddwd;
}
/**
* 设置ddwd属性的值。
*
*/
public void setDdwd(double value) {
this.ddwd = value;
}
/**
* 获取fxlx属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getFxlx() {
return fxlx;
}
/**
* 设置fxlx属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFxlx(String value) {
this.fxlx = value;
}
/**
* 获取jzbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getJzbh() {
return jzbh;
}
/**
* 设置jzbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setJzbh(String value) {
this.jzbh = value;
}
/**
* 获取jzjcbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getJzjcbh() {
return jzjcbh;
}
/**
* 设置jzjcbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setJzjcbh(String value) {
this.jzjcbh = value;
}
/**
* 获取jzrzbh属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getJzrzbh() {
return jzrzbh;
}
/**
* 设置jzrzbh属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setJzrzbh(String value) {
this.jzrzbh = value;
}
/**
* 获取zzdz属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getZzdz() {
return zzdz;
}
/**
* 设置zzdz属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setZzdz(String value) {
this.zzdz = value;
}
}
| 5,176 | 0.49508 | 0.4836 | 251 | 18.430279 | 18.765648 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227092 | false | false | 15 |
912b774b2c70976aca1d63f38af63e8a029b2e2a | 31,860,067,442,258 | 10bf813dbe1211d44519aa02643732fd0abd3bf9 | /src/main/java/de/redsix/pdfcompare/InThreadExecutorService.java | f22c9d19e02b9fca56bab077f75abce3ed86231a | [
"Apache-2.0"
]
| permissive | red6/pdfcompare | https://github.com/red6/pdfcompare | dd8fb1ea1a1d3c8d8b0ca1454344952bac6c25c1 | 49104922356b518047cabaed0d36681bf570b173 | refs/heads/master | 2023-09-04T07:56:48.503000 | 2023-08-23T09:51:10 | 2023-08-23T09:51:10 | 74,676,206 | 185 | 70 | Apache-2.0 | false | 2023-08-23T09:12:39 | 2016-11-24T13:34:39 | 2023-08-22T04:58:14 | 2023-08-23T09:11:39 | 945 | 184 | 59 | 6 | Java | false | false | package de.redsix.pdfcompare;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
public class InThreadExecutorService implements ExecutorService {
private boolean shutdown = false;
@Override
public void shutdown() {
shutdown = true;
}
@Override
public List<Runnable> shutdownNow() {
shutdown = true;
return Collections.emptyList();
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
return shutdown;
}
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
return true;
}
@Override
public <T> Future<T> submit(final Callable<T> task) {
try {
return new ImmediateFuture<>(task.call());
} catch (Exception e) {
return new ImmediateFuture<>(e);
}
}
@Override
public <T> Future<T> submit(final Runnable task, final T result) {
try {
task.run();
} catch (Exception e) {
return new ImmediateFuture<>(e);
}
return new ImmediateFuture<>(result);
}
@Override
public Future<?> submit(final Runnable task) {
return submit(task, null);
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks) throws InterruptedException {
List<Future<T>> result = new ArrayList<>();
for (Callable<T> task : tasks) {
result.add(submit(task));
}
return result;
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
throws InterruptedException {
return invokeAll(tasks);
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return invokeAny(tasks);
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return invokeAny(tasks);
}
@Override
public void execute(final Runnable command) {
command.run();
}
/*package for Testing*/ static class ImmediateFuture<T> implements Future<T> {
private final T result;
private final Exception exception;
public ImmediateFuture(final T result) {
this.result = result;
this.exception = null;
}
public ImmediateFuture(final Exception exeption) {
this.result = null;
this.exception = exeption;
}
@Override
public boolean cancel(final boolean mayInterruptIfRunning) {
return true;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public T get() throws InterruptedException, ExecutionException {
if (result != null) {
return result;
} else {
throw new ExecutionException(exception);
}
}
@Override
public T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
}
}
| UTF-8 | Java | 3,633 | java | InThreadExecutorService.java | Java | []
| null | []
| package de.redsix.pdfcompare;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
public class InThreadExecutorService implements ExecutorService {
private boolean shutdown = false;
@Override
public void shutdown() {
shutdown = true;
}
@Override
public List<Runnable> shutdownNow() {
shutdown = true;
return Collections.emptyList();
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
return shutdown;
}
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
return true;
}
@Override
public <T> Future<T> submit(final Callable<T> task) {
try {
return new ImmediateFuture<>(task.call());
} catch (Exception e) {
return new ImmediateFuture<>(e);
}
}
@Override
public <T> Future<T> submit(final Runnable task, final T result) {
try {
task.run();
} catch (Exception e) {
return new ImmediateFuture<>(e);
}
return new ImmediateFuture<>(result);
}
@Override
public Future<?> submit(final Runnable task) {
return submit(task, null);
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks) throws InterruptedException {
List<Future<T>> result = new ArrayList<>();
for (Callable<T> task : tasks) {
result.add(submit(task));
}
return result;
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
throws InterruptedException {
return invokeAll(tasks);
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return invokeAny(tasks);
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return invokeAny(tasks);
}
@Override
public void execute(final Runnable command) {
command.run();
}
/*package for Testing*/ static class ImmediateFuture<T> implements Future<T> {
private final T result;
private final Exception exception;
public ImmediateFuture(final T result) {
this.result = result;
this.exception = null;
}
public ImmediateFuture(final Exception exeption) {
this.result = null;
this.exception = exeption;
}
@Override
public boolean cancel(final boolean mayInterruptIfRunning) {
return true;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public T get() throws InterruptedException, ExecutionException {
if (result != null) {
return result;
} else {
throw new ExecutionException(exception);
}
}
@Override
public T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
}
}
| 3,633 | 0.602257 | 0.602257 | 138 | 25.326086 | 27.594938 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.376812 | false | false | 15 |
e95ffda5b54ffb59647d6f652b35005bc0f502e9 | 13,529,147,024,340 | 511ffb2da05394411566df0fa4931c6e3cd5484d | /src/model/DataAccsessObject.java | bd66048646197d479204da52d959c8ce29eb4327 | []
| no_license | hoangsonhv/JavaFX2 | https://github.com/hoangsonhv/JavaFX2 | d32313729fb11218160def36ed68be8a90b7a648 | 661574d24c48d30a830fcb3e3d40f020a8f06b40 | refs/heads/master | 2023-03-29T03:51:31.200000 | 2021-04-08T05:31:03 | 2021-04-08T05:31:03 | 354,763,284 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
import java.util.ArrayList;
public interface DataAccsessObject<T> {
ArrayList<T> getList();
boolean create(T t);
boolean update(T t);
boolean delete(T t);
}
| UTF-8 | Java | 190 | java | DataAccsessObject.java | Java | []
| null | []
| package model;
import java.util.ArrayList;
public interface DataAccsessObject<T> {
ArrayList<T> getList();
boolean create(T t);
boolean update(T t);
boolean delete(T t);
}
| 190 | 0.684211 | 0.684211 | 10 | 18 | 12.899612 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 15 |
e1df6aaee8770bc67c0c8fbec887e97caee339c7 | 6,708,738,962,700 | b6325a2d05bba3a30d80ce5f76ff75618f47ceb9 | /src/Nov2_2019/Exercise.java | a6939ccc299a4aea4652639dfafc5186ac62096b | []
| no_license | uday246/Season19-II | https://github.com/uday246/Season19-II | eeb717ab19367650ce980bec557075d07f837501 | 3ea358685a860b8b453c27229b03d5d6e3360cbf | refs/heads/master | 2020-08-15T06:53:29.142000 | 2020-04-11T05:54:02 | 2020-04-11T05:54:02 | 215,295,443 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Nov2_2019;
public class Exercise {
public static void stringTake(String input) {
char[]x= input.toCharArray();
int[]y= new int[x.length];
int[]z= new int[x.length];
for(int i=0; i<x.length; i++) {
switch(x[i])
{
case 65:
case 66:
case 67: y[i]=2;
break;
case 68:
case 69:
case 70: y[i]=3;
break;
case 71:
case 72:
case 73: y[i]=4;
break;
case 74:
case 75:
case 76: y[i]=5;
break;
case 77: y[i]=6;
case 78:
case 79: y[i]=6;
break;
case 80:
case 81:
case 82: y[i]=7;
break;
case 83:
case 84:
case 85: y[i]=8;
break;
case 86:
case 87:
case 88: y[i]=9;
break;
case 89:
case 90:
case 91: y[i]=0;
break;
default: y[i]=y[i];
}
}
}
public static void main(String[] args)
{
Exercise a= new Exercise();
stringTake("1800METHODS");
String z="1800METHODS";
a.stringTake(z); //There is an error here that I am unaware of how to fix
// here you have 1 issue
//1 z is not declared in this method because of that your getting the issue
}
} | UTF-8 | Java | 1,579 | java | Exercise.java | Java | []
| null | []
| package Nov2_2019;
public class Exercise {
public static void stringTake(String input) {
char[]x= input.toCharArray();
int[]y= new int[x.length];
int[]z= new int[x.length];
for(int i=0; i<x.length; i++) {
switch(x[i])
{
case 65:
case 66:
case 67: y[i]=2;
break;
case 68:
case 69:
case 70: y[i]=3;
break;
case 71:
case 72:
case 73: y[i]=4;
break;
case 74:
case 75:
case 76: y[i]=5;
break;
case 77: y[i]=6;
case 78:
case 79: y[i]=6;
break;
case 80:
case 81:
case 82: y[i]=7;
break;
case 83:
case 84:
case 85: y[i]=8;
break;
case 86:
case 87:
case 88: y[i]=9;
break;
case 89:
case 90:
case 91: y[i]=0;
break;
default: y[i]=y[i];
}
}
}
public static void main(String[] args)
{
Exercise a= new Exercise();
stringTake("1800METHODS");
String z="1800METHODS";
a.stringTake(z); //There is an error here that I am unaware of how to fix
// here you have 1 issue
//1 z is not declared in this method because of that your getting the issue
}
} | 1,579 | 0.391387 | 0.340722 | 60 | 24.35 | 14.172538 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.45 | false | false | 15 |
07fc70aef4c45bfb657b3a9cd7704a86327528e3 | 12,283,606,509,097 | 159d932dc274355d7b5274edc646ea2b9c07cd7b | /app/src/main/java/in/kay/flixtube/UI/HomeUI/Fragments/Watchlist.java | 8d71ac3410c2ac8f74959c14bcbb33ad5b684925 | [
"MIT"
]
| permissive | jay2413/Flixtube | https://github.com/jay2413/Flixtube | d1cf0c3737702089a6748cc93de5b8f8382114f5 | a3d9439f281f8926730fcb522fbb700fe37c7f88 | refs/heads/master | 2022-12-29T21:28:45.880000 | 2020-10-22T04:11:18 | 2020-10-22T04:11:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package in.kay.flixtube.UI.HomeUI.Fragments;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.sdsmdg.tastytoast.TastyToast;
import in.kay.flixtube.Adapter.WatchlistAdapter;
import in.kay.flixtube.Model.MovieModel;
import in.kay.flixtube.Model.WatchlistModel;
import in.kay.flixtube.R;
public class Watchlist extends Fragment {
View view;
Dialog dialog;
RecyclerView recyclerView;
WatchlistAdapter adapter;
Context mcontext;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.view = view;
dialog = new Dialog(mcontext);
recyclerView=view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(mcontext, LinearLayoutManager.VERTICAL, false));
ShowPopUp();
}
private void ShowPopUp() {
Button movie,series;
dialog.setContentView(R.layout.pop_up);
movie=dialog.findViewById(R.id.btn_movie);
series=dialog.findViewById(R.id.btn_series);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
dialog.setCanceledOnTouchOutside(false);
series.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
DoWork("Webseries");
}
});
movie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
DoWork("Movies");
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
TastyToast.makeText(getActivity(), "Please choose a value to continue..", TastyToast.LENGTH_SHORT,TastyToast.INFO);
return true;
}
return false;
}
});
}
private void DoWork(String string) {
FirebaseRecyclerOptions<WatchlistModel> options = new FirebaseRecyclerOptions.Builder<WatchlistModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("User").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Watchlist").child(string), WatchlistModel.class)
.build();
adapter=new WatchlistAdapter(options,mcontext);
recyclerView.setAdapter(adapter);
adapter.startListening();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_watchlist, container, false);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mcontext=context;
}
} | UTF-8 | Java | 3,911 | java | Watchlist.java | Java | []
| null | []
| package in.kay.flixtube.UI.HomeUI.Fragments;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.sdsmdg.tastytoast.TastyToast;
import in.kay.flixtube.Adapter.WatchlistAdapter;
import in.kay.flixtube.Model.MovieModel;
import in.kay.flixtube.Model.WatchlistModel;
import in.kay.flixtube.R;
public class Watchlist extends Fragment {
View view;
Dialog dialog;
RecyclerView recyclerView;
WatchlistAdapter adapter;
Context mcontext;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.view = view;
dialog = new Dialog(mcontext);
recyclerView=view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(mcontext, LinearLayoutManager.VERTICAL, false));
ShowPopUp();
}
private void ShowPopUp() {
Button movie,series;
dialog.setContentView(R.layout.pop_up);
movie=dialog.findViewById(R.id.btn_movie);
series=dialog.findViewById(R.id.btn_series);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
dialog.setCanceledOnTouchOutside(false);
series.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
DoWork("Webseries");
}
});
movie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
DoWork("Movies");
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
TastyToast.makeText(getActivity(), "Please choose a value to continue..", TastyToast.LENGTH_SHORT,TastyToast.INFO);
return true;
}
return false;
}
});
}
private void DoWork(String string) {
FirebaseRecyclerOptions<WatchlistModel> options = new FirebaseRecyclerOptions.Builder<WatchlistModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("User").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Watchlist").child(string), WatchlistModel.class)
.build();
adapter=new WatchlistAdapter(options,mcontext);
recyclerView.setAdapter(adapter);
adapter.startListening();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_watchlist, container, false);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mcontext=context;
}
} | 3,911 | 0.687804 | 0.687804 | 106 | 35.905659 | 29.932165 | 201 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.745283 | false | false | 15 |
b4c94b6cfa234f48ddc46ae11a391663a2d51ab7 | 103,079,256,161 | c3f770f97e50e87165a06610b030ce0c493153ac | /app/src/main/java/com/gwell/view/gwellview/MainActivity.java | 3b112ff984e2dfb5d8ca27e3f0ff4f0bbc61e6c4 | []
| no_license | dxsdyhm/BoundSelectView | https://github.com/dxsdyhm/BoundSelectView | 363009f4a07d7384ec514cc025036734c75843f5 | e3329b323acf51d087171703abcd6bb7bbb87467 | refs/heads/master | 2021-01-20T07:34:51.028000 | 2017-05-05T03:27:09 | 2017-05-05T03:27:09 | 90,014,202 | 0 | 0 | null | true | 2017-05-02T09:17:30 | 2017-05-02T09:17:30 | 2017-04-17T13:15:32 | 2017-04-20T09:55:09 | 125 | 0 | 0 | 0 | null | null | null | package com.gwell.view.gwellview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.gwell.view.gwellviewlibrary.BoundSelectView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
BoundSelectView myBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBtn = (BoundSelectView)findViewById(R.id.mybtn);
BoundSelectView.ItemOnClickListener itemOnClickListener =new BoundSelectView.ItemOnClickListener() {
@Override
public void onItemClick(int i, View v) {
Toast.makeText(MainActivity.this, "itemOnClickListeners "+i, Toast.LENGTH_SHORT).show();
}
};
ArrayList<String> names = new ArrayList();
names.add("超清");
names.add("高清");
names.add("标清");
myBtn.setBoundButton(itemOnClickListener,names,"标清");
}
public void change(View view) {
myBtn.hide();
}
}
| UTF-8 | Java | 1,152 | java | MainActivity.java | Java | []
| null | []
| package com.gwell.view.gwellview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.gwell.view.gwellviewlibrary.BoundSelectView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
BoundSelectView myBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBtn = (BoundSelectView)findViewById(R.id.mybtn);
BoundSelectView.ItemOnClickListener itemOnClickListener =new BoundSelectView.ItemOnClickListener() {
@Override
public void onItemClick(int i, View v) {
Toast.makeText(MainActivity.this, "itemOnClickListeners "+i, Toast.LENGTH_SHORT).show();
}
};
ArrayList<String> names = new ArrayList();
names.add("超清");
names.add("高清");
names.add("标清");
myBtn.setBoundButton(itemOnClickListener,names,"标清");
}
public void change(View view) {
myBtn.hide();
}
}
| 1,152 | 0.677817 | 0.676937 | 40 | 27.4 | 26.944202 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 15 |
7006f530135dfe305c95ab965bf455f96f98af00 | 7,559,142,485,592 | 23e05769f775ed7ae782871de3792e8881159849 | /InClassPractice/feb4/src/ClassName.java | 84d0c0063b047f960adabbb900cbd32bfbd5d1ea | []
| no_license | pkoenig077/JavaBootcamp | https://github.com/pkoenig077/JavaBootcamp | 1baf20756506a9153a4e38e1818ec8829e9da568 | 711cdec4e4a910d0c9acfe3d1e8d4a6fc6c69415 | refs/heads/master | 2021-01-10T06:15:33.107000 | 2016-03-10T14:13:04 | 2016-03-10T14:13:04 | 51,162,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.time.*;
import java.util.Scanner;
public class ClassName {
public static void main(String[] args) {
Employee[] empList = new Employee[1000];
//empList[0].setFullName("Hello");
for (int i=0;i<empList.length;i++){
empList[i]= new Employee();
}
// Scanner sc= new Scanner(System.in);
//
// Employee e1 = new Employee();
//
//
//
// String name = sc.nextLine();
//
//
// e1.setFullName(name);
// e1.setCompanyName("Company Name");
// e1.setSalary(100000.0f);
// e1.setSSN("111-11-1111");
// e1.setHireDate(null);
//
}
}
| UTF-8 | Java | 583 | java | ClassName.java | Java | [
{
"context": "= new Employee[1000];\n\t\t//empList[0].setFullName(\"Hello\");\n\t\t\n\t\tfor (int i=0;i<empList.length;i++){\n\t\t\tem",
"end": 194,
"score": 0.5860724449157715,
"start": 189,
"tag": "NAME",
"value": "Hello"
}
]
| null | []
|
import java.time.*;
import java.util.Scanner;
public class ClassName {
public static void main(String[] args) {
Employee[] empList = new Employee[1000];
//empList[0].setFullName("Hello");
for (int i=0;i<empList.length;i++){
empList[i]= new Employee();
}
// Scanner sc= new Scanner(System.in);
//
// Employee e1 = new Employee();
//
//
//
// String name = sc.nextLine();
//
//
// e1.setFullName(name);
// e1.setCompanyName("Company Name");
// e1.setSalary(100000.0f);
// e1.setSSN("111-11-1111");
// e1.setHireDate(null);
//
}
}
| 583 | 0.593482 | 0.545455 | 33 | 16.636364 | 15.117355 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.121212 | false | false | 15 |
27151b58ea1c779d6c5776c97117b1b53bf7bb1f | 22,196,391,028,848 | ec63a4afef125759fae77b7dc39a775f1154d361 | /src/main/java/com/kurukurupapa/pffsimu/domain/fitness/WeaponFitness.java | c6dcf95cebd81eb57ddc4e7b253832031810f227 | [
"MIT"
]
| permissive | kurukurupapa/pff-simulator | https://github.com/kurukurupapa/pff-simulator | ed9fa5c20e4e497e7683b5808b10a272f3e30b94 | 087e631eaae13afd61eddf71efe67d11d0f2dac4 | refs/heads/master | 2021-01-02T09:38:45.712000 | 2015-11-22T14:27:49 | 2015-11-22T14:27:49 | 37,526,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kurukurupapa.pffsimu.domain.fitness;
import org.apache.commons.lang3.Validate;
import com.kurukurupapa.pffsimu.domain.memoria.Memoria;
/**
* 武器適応度クラス
*/
public class WeaponFitness extends ItemFitness {
/**
* 適応度を計算します。
*
* @param memoria
* 武器装備前のメモリア
*/
public void calc(Memoria memoria) {
// 当該武器を装備するため、メモリアは武器未装備であること。
Validate.validState(memoria.getRemainWeaponSlot() >= 1);
// 武器装備後のメモリア
mMemoria = memoria.clone();
mMemoria.setWeapon(mItem);
// 当該武器の適応度
FitnessCalculator fitnessCalculator = createFitnessCalculator();
calcDifference(fitnessCalculator, memoria, mMemoria);
}
}
| UTF-8 | Java | 793 | java | WeaponFitness.java | Java | []
| null | []
| package com.kurukurupapa.pffsimu.domain.fitness;
import org.apache.commons.lang3.Validate;
import com.kurukurupapa.pffsimu.domain.memoria.Memoria;
/**
* 武器適応度クラス
*/
public class WeaponFitness extends ItemFitness {
/**
* 適応度を計算します。
*
* @param memoria
* 武器装備前のメモリア
*/
public void calc(Memoria memoria) {
// 当該武器を装備するため、メモリアは武器未装備であること。
Validate.validState(memoria.getRemainWeaponSlot() >= 1);
// 武器装備後のメモリア
mMemoria = memoria.clone();
mMemoria.setWeapon(mItem);
// 当該武器の適応度
FitnessCalculator fitnessCalculator = createFitnessCalculator();
calcDifference(fitnessCalculator, memoria, mMemoria);
}
}
| 793 | 0.725581 | 0.722481 | 31 | 19.806452 | 20.975285 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.096774 | false | false | 15 |
ff8f862d2395fef2c0b1d26aec60e0f6c2bb23fa | 11,149,735,161,816 | b911b148ccce82940f3d9ba00297ce980d352394 | /LogAnalyzer/src/main/java/tv/joyplus/backend/appinfo/beans/AppLogAnalyzeInfo.java | 34476e84cdcf24154e6b99c02150a0c99c8f31cd | []
| no_license | wsyandy/bigdata | https://github.com/wsyandy/bigdata | 61b2833d5af6330a7ee59d223102c7c0c5332c76 | e192ec7f3743994580ddd8c02eec0ffcc7b8b624 | refs/heads/master | 2021-01-18T20:52:53.698000 | 2014-09-26T01:53:42 | 2014-09-26T01:53:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tv.joyplus.backend.appinfo.beans;
import java.sql.Timestamp;
public class AppLogAnalyzeInfo {
public final static byte STATUS_UNPROCESSE = 0x00; //未处理
public final static byte STATUS_PROCESSED = 0x01; //已处理
public final static byte STATUS_UNKNOW = 0x02; //未知错误
public final static byte STATUS_FAIL = 0x03; //处理失败
public final static byte STATUS_PROCESSING = 0x04;//
public final static byte STATUS_LOCK = 0x02; //处理中
public final static byte STATUS_EXIST = 0x04; //已存在
private long id;
private String path;
private int status;
private Timestamp create_time;
private String businessId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Timestamp getCreate_time() {
return create_time;
}
public void setCreate_time(Timestamp create_time) {
this.create_time = create_time;
}
public String getBusinessId() {
return businessId;
}
public void setBusinessId(String businessId) {
this.businessId = businessId;
}
public static String TableName() {
return "ap_app_log_analyze_info";
}
}
| UTF-8 | Java | 1,529 | java | AppLogAnalyzeInfo.java | Java | []
| null | []
| package tv.joyplus.backend.appinfo.beans;
import java.sql.Timestamp;
public class AppLogAnalyzeInfo {
public final static byte STATUS_UNPROCESSE = 0x00; //未处理
public final static byte STATUS_PROCESSED = 0x01; //已处理
public final static byte STATUS_UNKNOW = 0x02; //未知错误
public final static byte STATUS_FAIL = 0x03; //处理失败
public final static byte STATUS_PROCESSING = 0x04;//
public final static byte STATUS_LOCK = 0x02; //处理中
public final static byte STATUS_EXIST = 0x04; //已存在
private long id;
private String path;
private int status;
private Timestamp create_time;
private String businessId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Timestamp getCreate_time() {
return create_time;
}
public void setCreate_time(Timestamp create_time) {
this.create_time = create_time;
}
public String getBusinessId() {
return businessId;
}
public void setBusinessId(String businessId) {
this.businessId = businessId;
}
public static String TableName() {
return "ap_app_log_analyze_info";
}
}
| 1,529 | 0.621222 | 0.607119 | 62 | 23.016129 | 20.328346 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.403226 | false | false | 15 |
5afb99c4708654a373324ea1f13a3f413b7b7478 | 23,235,773,115,695 | 329307375d5308bed2311c178b5c245233ac6ff1 | /src/com/tencent/mm/booter/notification/c.java | 53dee4007120684e85d5eb5e3172acf4f8ba34b3 | []
| no_license | ZoneMo/com.tencent.mm | https://github.com/ZoneMo/com.tencent.mm | 6529ac4c31b14efa84c2877824fa3a1f72185c20 | dc4f28aadc4afc27be8b099e08a7a06cee1960fe | refs/heads/master | 2021-01-18T12:12:12.843000 | 2015-07-05T03:21:46 | 2015-07-05T03:21:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.mm.booter.notification;
import android.annotation.TargetApi;
import android.app.Notification;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import com.tencent.mm.booter.notification.a.h;
import com.tencent.mm.booter.notification.queue.NotificationQueue;
import com.tencent.mm.booter.notification.queue.NotificationQueue.ParcelNotificationQueue;
import com.tencent.mm.g.g;
import com.tencent.mm.sdk.platformtools.aa;
import com.tencent.mm.sdk.platformtools.t;
import com.tencent.mm.ui.LauncherUI;
import java.lang.reflect.Field;
import java.util.Iterator;
public final class c
{
private static boolean bdA = true;
private static boolean bdB = false;
private static int bdC = -1;
private static int bdD = -1;
private static boolean bdE = true;
private static String bdF = "samsung";
public static boolean bdG = true;
public static boolean bdH = false;
private static int bdI = -1;
private static boolean bdz = true;
public static int a(Notification paramNotification, h paramh)
{
if ((paramNotification == null) || (!bdz)) {
return 0;
}
int i;
if (paramh == null) {
i = 0;
}
try
{
paramh = Class.forName("android.app.MiuiNotification").newInstance();
Field localField = paramh.getClass().getDeclaredField("messageCount");
localField.setAccessible(true);
localField.set(paramh, Integer.valueOf(i));
paramNotification.getClass().getField("extraNotification").set(paramNotification, paramh);
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "miuiNotification: %d", new Object[] { Integer.valueOf(i) });
return i;
}
catch (NoSuchFieldException paramNotification)
{
for (;;)
{
bdz = false;
return i;
int j = bes;
paramh = nLbdX;
if (bdW == null) {
paramh.restore();
}
paramh = bdW.iterator();
for (i = 0; paramh.hasNext(); i = nextbdQ + i) {}
i = j - i;
}
}
catch (IllegalArgumentException paramNotification)
{
bdz = false;
return i;
}
catch (IllegalAccessException paramNotification)
{
bdz = false;
return i;
}
catch (ClassNotFoundException paramNotification)
{
bdz = false;
return i;
}
catch (InstantiationException paramNotification)
{
bdz = false;
return i;
}
catch (Exception paramNotification)
{
bdz = false;
}
return i;
}
public static void bB(int paramInt)
{
bE(paramInt);
bD(paramInt);
bC(paramInt);
}
public static void bC(int paramInt)
{
boolean bool = true;
if (bdB)
{
bool = bdA;
if (bool) {
break label48;
}
}
label48:
while (bdC == paramInt)
{
return;
bdB = true;
if (!Build.BRAND.equals("vivo"))
{
bdA = false;
bool = false;
break;
}
bdA = true;
break;
}
try
{
Intent localIntent = new Intent("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
localIntent.putExtra("packageName", aa.getPackageName());
localIntent.putExtra("className", LauncherUI.class.getName());
localIntent.putExtra("notificationNum", paramInt);
aa.getContext().sendBroadcast(localIntent);
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "vivo badge: %d", new Object[] { Integer.valueOf(paramInt) });
return;
}
catch (Exception localException)
{
bdA = false;
}
}
@TargetApi(11)
public static void bD(int paramInt)
{
boolean bool = true;
if (bdE)
{
if (Build.VERSION.SDK_INT >= 11) {
break label21;
}
bdE = false;
}
label21:
while (bdD == paramInt) {
return;
}
for (;;)
{
try
{
Bundle localBundle = new Bundle();
localBundle.putString("package", aa.getPackageName());
localBundle.putString("class", LauncherUI.class.getName());
localBundle.putInt("badgenumber", paramInt);
if (aa.getContext().getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle) != null)
{
bdE = bool;
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "huawei badge: %d, %b", new Object[] { Integer.valueOf(paramInt), Boolean.valueOf(bdE) });
return;
}
}
catch (Exception localException)
{
t.printErrStackTrace("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", localException, "no huawei badge", new Object[0]);
bdE = false;
return;
}
bool = false;
}
}
public static void bE(int paramInt)
{
if (aa.getContext() == null) {}
Context localContext;
int i;
do
{
do
{
return;
} while (!nJ());
localContext = aa.getContext();
i = paramInt;
if (paramInt == -1) {
i = g.pV();
}
} while ((localContext == null) || (!nJ()) || (bdI == i));
bdI = i;
Intent localIntent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
localIntent.putExtra("badge_count", i);
localIntent.putExtra("badge_count_package_name", aa.getPackageName());
localIntent.putExtra("badge_count_class_name", LauncherUI.class.getName());
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "samsungNotification: %d, %s", new Object[] { Integer.valueOf(i), Build.BRAND });
localContext.sendBroadcast(localIntent);
}
private static boolean nJ()
{
if (bdH) {
return bdG;
}
bdH = true;
if (!Build.BRAND.equals(bdF))
{
bdG = false;
return false;
}
bdG = true;
return true;
}
}
/* Location:
* Qualified Name: com.tencent.mm.booter.notification.c
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 6,097 | java | c.java | Java | []
| null | []
| package com.tencent.mm.booter.notification;
import android.annotation.TargetApi;
import android.app.Notification;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import com.tencent.mm.booter.notification.a.h;
import com.tencent.mm.booter.notification.queue.NotificationQueue;
import com.tencent.mm.booter.notification.queue.NotificationQueue.ParcelNotificationQueue;
import com.tencent.mm.g.g;
import com.tencent.mm.sdk.platformtools.aa;
import com.tencent.mm.sdk.platformtools.t;
import com.tencent.mm.ui.LauncherUI;
import java.lang.reflect.Field;
import java.util.Iterator;
public final class c
{
private static boolean bdA = true;
private static boolean bdB = false;
private static int bdC = -1;
private static int bdD = -1;
private static boolean bdE = true;
private static String bdF = "samsung";
public static boolean bdG = true;
public static boolean bdH = false;
private static int bdI = -1;
private static boolean bdz = true;
public static int a(Notification paramNotification, h paramh)
{
if ((paramNotification == null) || (!bdz)) {
return 0;
}
int i;
if (paramh == null) {
i = 0;
}
try
{
paramh = Class.forName("android.app.MiuiNotification").newInstance();
Field localField = paramh.getClass().getDeclaredField("messageCount");
localField.setAccessible(true);
localField.set(paramh, Integer.valueOf(i));
paramNotification.getClass().getField("extraNotification").set(paramNotification, paramh);
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "miuiNotification: %d", new Object[] { Integer.valueOf(i) });
return i;
}
catch (NoSuchFieldException paramNotification)
{
for (;;)
{
bdz = false;
return i;
int j = bes;
paramh = nLbdX;
if (bdW == null) {
paramh.restore();
}
paramh = bdW.iterator();
for (i = 0; paramh.hasNext(); i = nextbdQ + i) {}
i = j - i;
}
}
catch (IllegalArgumentException paramNotification)
{
bdz = false;
return i;
}
catch (IllegalAccessException paramNotification)
{
bdz = false;
return i;
}
catch (ClassNotFoundException paramNotification)
{
bdz = false;
return i;
}
catch (InstantiationException paramNotification)
{
bdz = false;
return i;
}
catch (Exception paramNotification)
{
bdz = false;
}
return i;
}
public static void bB(int paramInt)
{
bE(paramInt);
bD(paramInt);
bC(paramInt);
}
public static void bC(int paramInt)
{
boolean bool = true;
if (bdB)
{
bool = bdA;
if (bool) {
break label48;
}
}
label48:
while (bdC == paramInt)
{
return;
bdB = true;
if (!Build.BRAND.equals("vivo"))
{
bdA = false;
bool = false;
break;
}
bdA = true;
break;
}
try
{
Intent localIntent = new Intent("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
localIntent.putExtra("packageName", aa.getPackageName());
localIntent.putExtra("className", LauncherUI.class.getName());
localIntent.putExtra("notificationNum", paramInt);
aa.getContext().sendBroadcast(localIntent);
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "vivo badge: %d", new Object[] { Integer.valueOf(paramInt) });
return;
}
catch (Exception localException)
{
bdA = false;
}
}
@TargetApi(11)
public static void bD(int paramInt)
{
boolean bool = true;
if (bdE)
{
if (Build.VERSION.SDK_INT >= 11) {
break label21;
}
bdE = false;
}
label21:
while (bdD == paramInt) {
return;
}
for (;;)
{
try
{
Bundle localBundle = new Bundle();
localBundle.putString("package", aa.getPackageName());
localBundle.putString("class", LauncherUI.class.getName());
localBundle.putInt("badgenumber", paramInt);
if (aa.getContext().getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle) != null)
{
bdE = bool;
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "huawei badge: %d, %b", new Object[] { Integer.valueOf(paramInt), Boolean.valueOf(bdE) });
return;
}
}
catch (Exception localException)
{
t.printErrStackTrace("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", localException, "no huawei badge", new Object[0]);
bdE = false;
return;
}
bool = false;
}
}
public static void bE(int paramInt)
{
if (aa.getContext() == null) {}
Context localContext;
int i;
do
{
do
{
return;
} while (!nJ());
localContext = aa.getContext();
i = paramInt;
if (paramInt == -1) {
i = g.pV();
}
} while ((localContext == null) || (!nJ()) || (bdI == i));
bdI = i;
Intent localIntent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
localIntent.putExtra("badge_count", i);
localIntent.putExtra("badge_count_package_name", aa.getPackageName());
localIntent.putExtra("badge_count_class_name", LauncherUI.class.getName());
t.i("!44@/B4Tb64lLpJWy6nzbK2gSQ+BwUfX6bAvIhnrnzV63VM=", "samsungNotification: %d, %s", new Object[] { Integer.valueOf(i), Build.BRAND });
localContext.sendBroadcast(localIntent);
}
private static boolean nJ()
{
if (bdH) {
return bdG;
}
bdH = true;
if (!Build.BRAND.equals(bdF))
{
bdG = false;
return false;
}
bdG = true;
return true;
}
}
/* Location:
* Qualified Name: com.tencent.mm.booter.notification.c
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 6,097 | 0.613416 | 0.600787 | 230 | 25.513044 | 27.323462 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673913 | false | false | 15 |
de9d00139b9999abdcdd7c8d3d1713a1381d03cd | 33,225,867,053,355 | d51679766b6c92adc6f747520b7b4e48cabc41d0 | /hprof-heap/src/main/java/org/netbeans/lib/profiler/heap/HeapProgress.java | 622abe1b7c244eb957c57aac628140c134606d6e | [
"Apache-2.0",
"GPL-2.0-only"
]
| permissive | konigsbergg/jvm-tools | https://github.com/konigsbergg/jvm-tools | 264c5831fab37d711020c930e01c5b0d3fb337ed | 0db927b3cc6961f872c93fbb9ddbc1a81e4310be | refs/heads/master | 2022-07-19T11:19:58.617000 | 2020-05-24T09:55:32 | 2020-05-24T09:55:32 | 267,233,244 | 1 | 0 | Apache-2.0 | true | 2020-05-27T05:56:08 | 2020-05-27T05:56:07 | 2020-05-27T04:24:14 | 2020-05-26T11:03:53 | 4,831 | 0 | 0 | 0 | null | false | false | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.profiler.heap;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.SwingUtilities;
/**
* @author Tomas Hurka
*/
public final class HeapProgress {
public static final int PROGRESS_MAX = 1000;
private static ThreadLocal<BoundedRangeModel> progressThreadLocal = new ThreadLocal<BoundedRangeModel>();
private HeapProgress() {
}
public static BoundedRangeModel getProgress() {
BoundedRangeModel model = (BoundedRangeModel) progressThreadLocal.get();
if (model == null) {
model = new DefaultBoundedRangeModel(0,0,0,PROGRESS_MAX);
progressThreadLocal.set(model);
}
return model;
}
static void progress(long counter, long startOffset, long value, long endOffset) {
// keep this method short so that it can be inlined
if (counter % 100000 == 0) {
progress(value, endOffset, startOffset);
}
}
static void progress(long value, long endValue) {
progress(value,0,value,endValue);
}
private static void progress(final long value, final long endOffset, final long startOffset) {
BoundedRangeModel model = (BoundedRangeModel) progressThreadLocal.get();
if (model != null) {
long val = PROGRESS_MAX*(value - startOffset)/(endOffset - startOffset);
setValue(model, (int)val);
}
}
static void progressFinish() {
BoundedRangeModel model = (BoundedRangeModel) progressThreadLocal.get();
if (model != null) {
setValue(model, PROGRESS_MAX);
progressThreadLocal.remove();
}
}
private static void setValue(final BoundedRangeModel model, final int val) {
if (SwingUtilities.isEventDispatchThread()) {
model.setValue(val);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() { model.setValue(val); }
});
}
}
}
| UTF-8 | Java | 4,285 | java | HeapProgress.java | Java | [
{
"context": "mport javax.swing.SwingUtilities;\n\n\n/**\n * @author Tomas Hurka\n */\npublic final class HeapProgress {\n\n public",
"end": 2444,
"score": 0.9998089075088501,
"start": 2433,
"tag": "NAME",
"value": "Tomas Hurka"
}
]
| null | []
| /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.lib.profiler.heap;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.SwingUtilities;
/**
* @author <NAME>
*/
public final class HeapProgress {
public static final int PROGRESS_MAX = 1000;
private static ThreadLocal<BoundedRangeModel> progressThreadLocal = new ThreadLocal<BoundedRangeModel>();
private HeapProgress() {
}
public static BoundedRangeModel getProgress() {
BoundedRangeModel model = (BoundedRangeModel) progressThreadLocal.get();
if (model == null) {
model = new DefaultBoundedRangeModel(0,0,0,PROGRESS_MAX);
progressThreadLocal.set(model);
}
return model;
}
static void progress(long counter, long startOffset, long value, long endOffset) {
// keep this method short so that it can be inlined
if (counter % 100000 == 0) {
progress(value, endOffset, startOffset);
}
}
static void progress(long value, long endValue) {
progress(value,0,value,endValue);
}
private static void progress(final long value, final long endOffset, final long startOffset) {
BoundedRangeModel model = (BoundedRangeModel) progressThreadLocal.get();
if (model != null) {
long val = PROGRESS_MAX*(value - startOffset)/(endOffset - startOffset);
setValue(model, (int)val);
}
}
static void progressFinish() {
BoundedRangeModel model = (BoundedRangeModel) progressThreadLocal.get();
if (model != null) {
setValue(model, PROGRESS_MAX);
progressThreadLocal.remove();
}
}
private static void setValue(final BoundedRangeModel model, final int val) {
if (SwingUtilities.isEventDispatchThread()) {
model.setValue(val);
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() { model.setValue(val); }
});
}
}
}
| 4,280 | 0.70105 | 0.691482 | 109 | 38.311928 | 29.836773 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458716 | false | false | 15 |
69207e06cd3e21d8c9c8201eed95f028381a6349 | 27,084,063,822,797 | 43e6832968a5d32d437c0c77252bf5d84bfc6676 | /Hotelvip4.0/src/cn/lut/hotelvip/controller/UserLogin.java | 6ae2b968186fb05657626acae7934c826978c306 | []
| no_license | Tanya11010/designfile | https://github.com/Tanya11010/designfile | 86ee1f4bb8a3180614f9c39eecd665c56ff8c88d | 734fd670dee3aee731500014d35a84a3f1382d4d | refs/heads/master | 2021-06-12T17:56:15.882000 | 2019-06-28T10:57:58 | 2019-06-28T10:57:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.lut.hotelvip.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import cn.lut.hotelvip.domain.po.Administrator;
import cn.lut.hotelvip.domain.po.Customer;
import cn.lut.hotelvip.domain.vo.AdminVo;
import cn.lut.hotelvip.domain.vo.UserVo;
import cn.lut.hotelvip.service.UserService;
import cn.lut.hotelvip.service.impl.UserServiceImpl;
import cn.lut.hotelvip.utils.COMMON;
/**
* 用户登录
*/
public class UserLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
UserService userService = new UserServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//显示登录界面
String token = COMMON.UUID();
request.getSession().setAttribute("token", token);
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//验证登录信息
UserVo uv = COMMON.request2Bean(request, UserVo.class);
AdminVo av = COMMON.request2Bean(request, AdminVo.class);
String radio = request.getParameter("radio");
//防止表单重复提交
String sessiontocken = (String) request.getSession().getAttribute("token");
if ((uv.getToken() == null|| av.getToken() == null) || sessiontocken == null ) {
request.setAttribute("msg", "表单不能重复提交");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
} else {
if (uv.getToken().equals(sessiontocken)||av.getToken().equals(sessiontocken)) {
request.getSession().removeAttribute("token");
} else {
request.setAttribute("msg", "表单不能重复提交");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
}
}
//检查图形验证码
HttpSession session = request.getSession();
String sessionstr = (String) session.getAttribute("imgcodestr");
if (sessionstr == null) {
request.setAttribute("msg", "图片验证码不正确");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
if (sessionstr.equals(uv.getImagecode())||sessionstr.equals(av.getImagecode())) {
// 验证用户名和密码
Customer customer = new Customer();
Administrator administrator = new Administrator();
try {
BeanUtils.copyProperties(customer, uv);
BeanUtils.copyProperties(administrator, av);
} catch (Exception e) {
}
customer = userService.loginCustomer(customer.getUsername(), customer.getUserpass());
administrator = userService.loginAdministrator(administrator.getUsername(), administrator.getUserpass());
//会员登录验证
if (customer != null) {
// 登录成功
// 保留身份信息,权限验证中用来验证是否已登录过。
session.setAttribute("loginstate", customer);
if(radio.equals("userrad")) {
request.getRequestDispatcher("/WEB-INF/views/usermain.jsp").forward(request, response);
return;
}else{
request.setAttribute("msg", "用户名和密码错误");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
//管理员登录验证
}else if(administrator!=null) {
// 登录成功
// 保留身份信息,权限验证中用来验证是否已登录过。
session.setAttribute("loginstate", administrator);
if(radio.equals("adminrad")) {
request.getRequestDispatcher("/WEB-INF/views/adminmain.jsp").forward(request, response);
return;
}else{
request.setAttribute("msg", "用户名和密码错误");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
} else {
request.setAttribute("msg", "用户名和密码错误");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
} else {
request.setAttribute("msg", "图片验证码不正确");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
}
}
| UTF-8 | Java | 4,677 | java | UserLogin.java | Java | []
| null | []
| package cn.lut.hotelvip.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import cn.lut.hotelvip.domain.po.Administrator;
import cn.lut.hotelvip.domain.po.Customer;
import cn.lut.hotelvip.domain.vo.AdminVo;
import cn.lut.hotelvip.domain.vo.UserVo;
import cn.lut.hotelvip.service.UserService;
import cn.lut.hotelvip.service.impl.UserServiceImpl;
import cn.lut.hotelvip.utils.COMMON;
/**
* 用户登录
*/
public class UserLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
UserService userService = new UserServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//显示登录界面
String token = COMMON.UUID();
request.getSession().setAttribute("token", token);
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//验证登录信息
UserVo uv = COMMON.request2Bean(request, UserVo.class);
AdminVo av = COMMON.request2Bean(request, AdminVo.class);
String radio = request.getParameter("radio");
//防止表单重复提交
String sessiontocken = (String) request.getSession().getAttribute("token");
if ((uv.getToken() == null|| av.getToken() == null) || sessiontocken == null ) {
request.setAttribute("msg", "表单不能重复提交");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
} else {
if (uv.getToken().equals(sessiontocken)||av.getToken().equals(sessiontocken)) {
request.getSession().removeAttribute("token");
} else {
request.setAttribute("msg", "表单不能重复提交");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
}
}
//检查图形验证码
HttpSession session = request.getSession();
String sessionstr = (String) session.getAttribute("imgcodestr");
if (sessionstr == null) {
request.setAttribute("msg", "图片验证码不正确");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
if (sessionstr.equals(uv.getImagecode())||sessionstr.equals(av.getImagecode())) {
// 验证用户名和密码
Customer customer = new Customer();
Administrator administrator = new Administrator();
try {
BeanUtils.copyProperties(customer, uv);
BeanUtils.copyProperties(administrator, av);
} catch (Exception e) {
}
customer = userService.loginCustomer(customer.getUsername(), customer.getUserpass());
administrator = userService.loginAdministrator(administrator.getUsername(), administrator.getUserpass());
//会员登录验证
if (customer != null) {
// 登录成功
// 保留身份信息,权限验证中用来验证是否已登录过。
session.setAttribute("loginstate", customer);
if(radio.equals("userrad")) {
request.getRequestDispatcher("/WEB-INF/views/usermain.jsp").forward(request, response);
return;
}else{
request.setAttribute("msg", "用户名和密码错误");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
//管理员登录验证
}else if(administrator!=null) {
// 登录成功
// 保留身份信息,权限验证中用来验证是否已登录过。
session.setAttribute("loginstate", administrator);
if(radio.equals("adminrad")) {
request.getRequestDispatcher("/WEB-INF/views/adminmain.jsp").forward(request, response);
return;
}else{
request.setAttribute("msg", "用户名和密码错误");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
} else {
request.setAttribute("msg", "用户名和密码错误");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
} else {
request.setAttribute("msg", "图片验证码不正确");
request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
return;
}
}
}
| 4,677 | 0.685275 | 0.684585 | 120 | 34.241665 | 31.477768 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.891667 | false | false | 15 |
860bd3279bd88be807d1af2011493dd4bd7d891d | 25,451,976,252,796 | 03ccc2969088b08ac4538fc8c8650c0b3adc7978 | /app/src/main/java/com/hiretaxi/model/Other.java | f31a457afdf34dff503792cea171cdb5a59b85ef | []
| no_license | hutaodediannao/HireTaxi | https://github.com/hutaodediannao/HireTaxi | 805afb5289ccc7ccfea883a3dc782dde356447b2 | c65490fb5ab0977c65907dffc383d25adcc17355 | refs/heads/master | 2020-03-15T20:58:39.051000 | 2018-05-07T17:25:22 | 2018-05-07T17:25:22 | 132,345,414 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hiretaxi.model;
import cn.bmob.v3.BmobObject;
/**
* Created by Administrator on 2017/7/3.
*/
public class Other extends BmobObject {
private String qq, weiXin, phoneNumber, helpUrl;
public Other(String qq, String weiXin, String phoneNumber) {
this.qq = qq;
this.weiXin = weiXin;
this.phoneNumber = phoneNumber;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getWeiXin() {
return weiXin;
}
public void setWeiXin(String weiXin) {
this.weiXin = weiXin;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getHelpUrl() {
return helpUrl;
}
public void setHelpUrl(String helpUrl) {
this.helpUrl = helpUrl;
}
}
| UTF-8 | Java | 949 | java | Other.java | Java | [
{
"context": "\n\nimport cn.bmob.v3.BmobObject;\n\n/**\n * Created by Administrator on 2017/7/3.\n */\npublic class Other extends BmobO",
"end": 91,
"score": 0.5550334453582764,
"start": 78,
"tag": "NAME",
"value": "Administrator"
}
]
| null | []
| package com.hiretaxi.model;
import cn.bmob.v3.BmobObject;
/**
* Created by Administrator on 2017/7/3.
*/
public class Other extends BmobObject {
private String qq, weiXin, phoneNumber, helpUrl;
public Other(String qq, String weiXin, String phoneNumber) {
this.qq = qq;
this.weiXin = weiXin;
this.phoneNumber = phoneNumber;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getWeiXin() {
return weiXin;
}
public void setWeiXin(String weiXin) {
this.weiXin = weiXin;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getHelpUrl() {
return helpUrl;
}
public void setHelpUrl(String helpUrl) {
this.helpUrl = helpUrl;
}
}
| 949 | 0.610116 | 0.60274 | 49 | 18.367348 | 17.732357 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387755 | false | false | 15 |
dd575430edf0c6f71e01547379c217225657a27d | 10,411,000,729,667 | 722c1f162532488248514830aae111d4dfeaa315 | /Java/GUI/GamePanel.java | c020b829a3ff2ddddce8a44ed366590d42d0da60 | []
| no_license | MichaelMMacLeod/comp-sci-playground | https://github.com/MichaelMMacLeod/comp-sci-playground | 28908e7350d0ef87832ecf51d4d085c87949b8fb | b0d715260d6963ded57b42317a90a93ab8a5667b | refs/heads/master | 2020-04-17T06:44:40.751000 | 2018-09-10T06:19:49 | 2018-09-10T06:19:49 | 66,595,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Font;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
private int width, height;
private Grid map = new Grid(30, 20, 1);
private Food food = new Food();
private Snake snake = new Snake(15, 15, 1, 1);
private KeyLis listener = new KeyLis();
private KeyLog log = new KeyLog();
private final String LEFT = "LEFT";
private final String UP = "UP";
private final String RIGHT = "RIGHT";
private final String DOWN = "DOWN";
private final String NONE = "NONE";
private final Color SNAKE_COLOR = Color.GREEN;
private final Color FOOD_COLOR = Color.RED;
private final Color TILE_COLOR = Color.WHITE;
private Menu menu = new Menu(20, 35, false);
private MenuItem snakeLength = new MenuItem();
private MenuItem snakeSpeed = new MenuItem();
private MenuItem snakeGrowth = new MenuItem();
public GamePanel(int width, int height) {
this.width = width;
this.height = height;
this.setFocusable(true);
this.requestFocus();
this.addKeyListener(listener);
food.newLocation(map);
menu.addItem(snakeLength);
menu.addItem(snakeSpeed);
menu.addItem(snakeGrowth);
menu.show();
}
public void getInput() {
if (!log.getKey().equals(NONE)) {
snake.setDirection(log.getKey());
}
}
public void updateLogic() {
switch (snake.getDirection()) {
case LEFT:
snake.setX(snake.getX() - 1);
break;
case UP:
snake.setY(snake.getY() - 1);
break;
case RIGHT:
snake.setX(snake.getX() + 1);
break;
case DOWN:
snake.setY(snake.getY() + 1);
break;
default:
}
log.shift();
// Close the program when the snake goes out of bounds
if (snake.getX() > map.getSize() - 1 || snake.getX() < 0 ||
snake.getY() > map.getSize() - 1 || snake.getY() < 0) {
System.exit(0);
}
// Close the program when the snake hits itself
if (map.getCell(snake.getX(), snake.getY()) > 0 && !snake.getDirection().equals(NONE)) {
System.exit(0);
}
if (snake.getX() == food.getX() && snake.getY() == food.getY()) {
food.newLocation(map);
snake.incrementSize();
}
for (int i = 0; i < map.getSize(); i++) {
for (int j = 0; j < map.getSize(); j++) {
if (map.getCell(i, j) > 0) {
map.decrementCell(i, j);
}
if (i == snake.getX() && j == snake.getY()) {
map.setCell(i, j, snake.getSize());
}
if (i == food.getX() && j == food.getY()) {
map.setCell(i, j, -1);
}
}
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < map.getSize(); i++) {
for (int j = 0; j < map.getSize(); j++) {
if (map.getCell(i, j) > 0) {
g.setColor(SNAKE_COLOR);
} else if (map.getCell(i, j) == -1) {
g.setColor(FOOD_COLOR);
} else {
g.setColor(TILE_COLOR);
}
g.fillRect(
i * map.getBuffer(),
j * map.getBuffer(),
map.getTileSize(),
map.getTileSize());
}
}
snakeLength.setText("[Size: " + Integer.toString(snake.getSize()) + "]");
snakeSpeed.setText("[Speed: " + Integer.toString(Game.getSpeed()) + "]");
snakeGrowth.setText("[Growth: " + Integer.toString(snake.getGrowth()) + "]");
menu.display(g);
}
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
private class KeyLis extends KeyAdapter {
public void keyPressed(KeyEvent e) {
// Don't instantly-kill yourself if you press the key opposite
// your direction, that's just annoying
String opposite = log.oppositeKey(snake.getDirection());
switch (e.getKeyCode()) {
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
if (!opposite.equals(LEFT)) {
log.addKey(LEFT);
}
break;
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
if (!opposite.equals(UP)) {
log.addKey(UP);
}
break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
if (!opposite.equals(RIGHT)) {
log.addKey(RIGHT);
}
break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
if (!opposite.equals(DOWN)) {
log.addKey(DOWN);
}
break;
case KeyEvent.VK_ESCAPE:
System.exit(0);
break;
case KeyEvent.VK_SPACE:
menu.toggle();
break;
case KeyEvent.VK_SHIFT:
Game.toggleSpeed();
break;
case KeyEvent.VK_G:
snake.toggleGrowth();
break;
default:
}
}
}
} | UTF-8 | Java | 4,471 | java | GamePanel.java | Java | []
| null | []
| import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Font;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
private int width, height;
private Grid map = new Grid(30, 20, 1);
private Food food = new Food();
private Snake snake = new Snake(15, 15, 1, 1);
private KeyLis listener = new KeyLis();
private KeyLog log = new KeyLog();
private final String LEFT = "LEFT";
private final String UP = "UP";
private final String RIGHT = "RIGHT";
private final String DOWN = "DOWN";
private final String NONE = "NONE";
private final Color SNAKE_COLOR = Color.GREEN;
private final Color FOOD_COLOR = Color.RED;
private final Color TILE_COLOR = Color.WHITE;
private Menu menu = new Menu(20, 35, false);
private MenuItem snakeLength = new MenuItem();
private MenuItem snakeSpeed = new MenuItem();
private MenuItem snakeGrowth = new MenuItem();
public GamePanel(int width, int height) {
this.width = width;
this.height = height;
this.setFocusable(true);
this.requestFocus();
this.addKeyListener(listener);
food.newLocation(map);
menu.addItem(snakeLength);
menu.addItem(snakeSpeed);
menu.addItem(snakeGrowth);
menu.show();
}
public void getInput() {
if (!log.getKey().equals(NONE)) {
snake.setDirection(log.getKey());
}
}
public void updateLogic() {
switch (snake.getDirection()) {
case LEFT:
snake.setX(snake.getX() - 1);
break;
case UP:
snake.setY(snake.getY() - 1);
break;
case RIGHT:
snake.setX(snake.getX() + 1);
break;
case DOWN:
snake.setY(snake.getY() + 1);
break;
default:
}
log.shift();
// Close the program when the snake goes out of bounds
if (snake.getX() > map.getSize() - 1 || snake.getX() < 0 ||
snake.getY() > map.getSize() - 1 || snake.getY() < 0) {
System.exit(0);
}
// Close the program when the snake hits itself
if (map.getCell(snake.getX(), snake.getY()) > 0 && !snake.getDirection().equals(NONE)) {
System.exit(0);
}
if (snake.getX() == food.getX() && snake.getY() == food.getY()) {
food.newLocation(map);
snake.incrementSize();
}
for (int i = 0; i < map.getSize(); i++) {
for (int j = 0; j < map.getSize(); j++) {
if (map.getCell(i, j) > 0) {
map.decrementCell(i, j);
}
if (i == snake.getX() && j == snake.getY()) {
map.setCell(i, j, snake.getSize());
}
if (i == food.getX() && j == food.getY()) {
map.setCell(i, j, -1);
}
}
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < map.getSize(); i++) {
for (int j = 0; j < map.getSize(); j++) {
if (map.getCell(i, j) > 0) {
g.setColor(SNAKE_COLOR);
} else if (map.getCell(i, j) == -1) {
g.setColor(FOOD_COLOR);
} else {
g.setColor(TILE_COLOR);
}
g.fillRect(
i * map.getBuffer(),
j * map.getBuffer(),
map.getTileSize(),
map.getTileSize());
}
}
snakeLength.setText("[Size: " + Integer.toString(snake.getSize()) + "]");
snakeSpeed.setText("[Speed: " + Integer.toString(Game.getSpeed()) + "]");
snakeGrowth.setText("[Growth: " + Integer.toString(snake.getGrowth()) + "]");
menu.display(g);
}
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
private class KeyLis extends KeyAdapter {
public void keyPressed(KeyEvent e) {
// Don't instantly-kill yourself if you press the key opposite
// your direction, that's just annoying
String opposite = log.oppositeKey(snake.getDirection());
switch (e.getKeyCode()) {
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
if (!opposite.equals(LEFT)) {
log.addKey(LEFT);
}
break;
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
if (!opposite.equals(UP)) {
log.addKey(UP);
}
break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
if (!opposite.equals(RIGHT)) {
log.addKey(RIGHT);
}
break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
if (!opposite.equals(DOWN)) {
log.addKey(DOWN);
}
break;
case KeyEvent.VK_ESCAPE:
System.exit(0);
break;
case KeyEvent.VK_SPACE:
menu.toggle();
break;
case KeyEvent.VK_SHIFT:
Game.toggleSpeed();
break;
case KeyEvent.VK_G:
snake.toggleGrowth();
break;
default:
}
}
}
} | 4,471 | 0.613509 | 0.605681 | 193 | 22.170984 | 18.529259 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.072539 | false | false | 15 |
91c0ca4dd8c550076dca2b9cfb8df27aab09db83 | 35,338,990,949,427 | b352a1a7df050de47ad419b1def017baa155ae23 | /Selenium-Wendriver/src/Webdriver/Demo2.java | 0881ef14f42084750ee001e68a87699354e57072 | []
| no_license | GitikaGupta/Selenium-Script | https://github.com/GitikaGupta/Selenium-Script | 8dc0a140dfe66b6b0697a3ab4421cd6c04b47c83 | b59e3b60a697f6ca964456ca1de25a2d619081b2 | refs/heads/master | 2022-07-14T14:55:12.893000 | 2020-09-28T05:18:32 | 2020-09-28T05:18:32 | 198,776,113 | 0 | 0 | null | false | 2022-06-29T18:21:40 | 2019-07-25T07:00:41 | 2020-09-28T05:19:35 | 2022-06-29T18:21:37 | 2,058 | 0 | 0 | 4 | Java | false | false | package Webdriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo2 {
public static void main(String[] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver","C:\\Users\\IBM_ADMIN\\workspace\\Jars\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://newtours.demoaut.com/");
driver.manage().window().maximize();
WebElement UN = driver.findElement(By.name("userName"));
if(UN.isEnabled())
{
UN.sendKeys("sunil");
Thread.sleep(3000);
UN.clear();
UN.sendKeys("sunil");
}
if (UN.isDisplayed())
{
String nam=UN.getAttribute("name");//this will get the attribute of name which is userName
//driver.findElement(By.name(nam)).clear();
System.out.println("Name attribute is : " + nam);
String sub1 = nam.substring(0,2);
System.out.println("New Name attribute is : " + sub1);
String val1=UN.getAttribute("value"); //this will get the attribute of value
System.out.println("Value attribute is : "+val1);
String val2=UN.getAttribute("type"); //this will get the attribute of type
System.out.println("Type attribute is : "+val2);
WebElement label1 = driver.findElement(By.xpath("//*[contains(text(),'Name:')]"));
System.out.println("Label is: " + label1.getText());
WebElement label2 = driver.findElement(By.xpath("//*[text()='Password:']"));
System.out.println("Password label is : " + label2.getText());
//System.out.println(UN);
}
//driver.findElement(By.name("login")).click();
}
}
| UTF-8 | Java | 1,754 | java | Demo2.java | Java | [
{
"context": "e\"));\r\n\t\tif(UN.isEnabled())\r\n\t\t{\r\n\t\t\tUN.sendKeys(\"sunil\");\r\n\t\t\tThread.sleep(3000);\r\n\t\t\tUN.clear();\r\n\t\t\tUN",
"end": 659,
"score": 0.9905228614807129,
"start": 654,
"tag": "PASSWORD",
"value": "sunil"
},
{
"context": "ead.sleep(3000);\r\n\t\t\tUN.clear();\r\n\t\t\tUN.sendKeys(\"sunil\");\r\n\t\t}\r\n\t\tif (UN.isDisplayed())\r\n\t\t{\r\n\t\t\tString ",
"end": 725,
"score": 0.9906662702560425,
"start": 720,
"tag": "PASSWORD",
"value": "sunil"
}
]
| null | []
| package Webdriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo2 {
public static void main(String[] args) throws InterruptedException{
System.setProperty("webdriver.chrome.driver","C:\\Users\\IBM_ADMIN\\workspace\\Jars\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://newtours.demoaut.com/");
driver.manage().window().maximize();
WebElement UN = driver.findElement(By.name("userName"));
if(UN.isEnabled())
{
UN.sendKeys("<PASSWORD>");
Thread.sleep(3000);
UN.clear();
UN.sendKeys("<PASSWORD>");
}
if (UN.isDisplayed())
{
String nam=UN.getAttribute("name");//this will get the attribute of name which is userName
//driver.findElement(By.name(nam)).clear();
System.out.println("Name attribute is : " + nam);
String sub1 = nam.substring(0,2);
System.out.println("New Name attribute is : " + sub1);
String val1=UN.getAttribute("value"); //this will get the attribute of value
System.out.println("Value attribute is : "+val1);
String val2=UN.getAttribute("type"); //this will get the attribute of type
System.out.println("Type attribute is : "+val2);
WebElement label1 = driver.findElement(By.xpath("//*[contains(text(),'Name:')]"));
System.out.println("Label is: " + label1.getText());
WebElement label2 = driver.findElement(By.xpath("//*[text()='Password:']"));
System.out.println("Password label is : " + label2.getText());
//System.out.println(UN);
}
//driver.findElement(By.name("login")).click();
}
}
| 1,764 | 0.655644 | 0.644812 | 56 | 29.285715 | 29.677862 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.517857 | false | false | 15 |
873a42878deca20b30f6cadd5ae1aa462e96a9b8 | 36,026,185,705,733 | 13c2d3db2d49c40c74c2e6420a9cd89377f1c934 | /program_data/JavaProgramData/99/1411.java | d00aaed7e2d1343934d95686dd27f53f5d9ccdd6 | [
"MIT"
]
| permissive | qiuchili/ggnn_graph_classification | https://github.com/qiuchili/ggnn_graph_classification | c2090fefe11f8bf650e734442eb96996a54dc112 | 291ff02404555511b94a4f477c6974ebd62dcf44 | refs/heads/master | 2021-10-18T14:54:26.154000 | 2018-10-21T23:34:14 | 2018-10-21T23:34:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package <missing>;
public class GlobalMembers
{
public static int Main()
{
int n;
int i;
int a = 0;
int b = 0;
int c = 0;
int e = 0;
int[] m = new int[100];
double a1;
double b1;
double c1;
double e1;
String tempVar = ConsoleInput.scanfRead();
if (tempVar != null)
{
n = Integer.parseInt(tempVar);
}
for (i = 1;i <= n;i++)
{
String tempVar2 = ConsoleInput.scanfRead();
if (tempVar2 != null)
{
m[i] = Integer.parseInt(tempVar2);
}
}
for (i = 1;i <= n;i++)
{
if (m[i] < 19)
{
a = a + 1;
}
else if ((m[i] > 18) && (m[i] < 36))
{
b = b + 1;
}
else if ((m[i] > 35) && (m[i] < 61))
{
c = c + 1;
}
else if (m[i] > 60)
{
e = e+1;
}
}
a1 = (double)a / n;
b1 = (double)b / n;
c1 = (double)c / n;
e1 = (double)e / n;
System.out.printf("1-18: %.2lf%%\n19-35: %.2lf%%\n36-60: %.2lf%%\n60??: %.2lf%%",a1 * 100,b1 * 100,c1 * 100,e1 * 100);
return 0;
}
}
| UTF-8 | Java | 1,011 | java | 1411.java | Java | []
| null | []
| package <missing>;
public class GlobalMembers
{
public static int Main()
{
int n;
int i;
int a = 0;
int b = 0;
int c = 0;
int e = 0;
int[] m = new int[100];
double a1;
double b1;
double c1;
double e1;
String tempVar = ConsoleInput.scanfRead();
if (tempVar != null)
{
n = Integer.parseInt(tempVar);
}
for (i = 1;i <= n;i++)
{
String tempVar2 = ConsoleInput.scanfRead();
if (tempVar2 != null)
{
m[i] = Integer.parseInt(tempVar2);
}
}
for (i = 1;i <= n;i++)
{
if (m[i] < 19)
{
a = a + 1;
}
else if ((m[i] > 18) && (m[i] < 36))
{
b = b + 1;
}
else if ((m[i] > 35) && (m[i] < 61))
{
c = c + 1;
}
else if (m[i] > 60)
{
e = e+1;
}
}
a1 = (double)a / n;
b1 = (double)b / n;
c1 = (double)c / n;
e1 = (double)e / n;
System.out.printf("1-18: %.2lf%%\n19-35: %.2lf%%\n36-60: %.2lf%%\n60??: %.2lf%%",a1 * 100,b1 * 100,c1 * 100,e1 * 100);
return 0;
}
}
| 1,011 | 0.451039 | 0.3818 | 61 | 15.557377 | 18.132051 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.278688 | false | false | 15 |
1032798b4b3aaecbf9cd70ce8a93d4a0b0b277ed | 34,892,314,356,030 | 41e443fa7ff6b25ce7b57f55b1cec561281e8f65 | /BasicMTL_projects/org.inria.mtl.plugin/src/org/inria/mtl/plugin/editors/mtlsyntax/MTLConstantObject.java | a6b22a1364a74c6a9317f3c1cb604f383d3ebe83 | []
| no_license | diverse-project/mtl | https://github.com/diverse-project/mtl | 5ee26c629b2e4f025f9bc58c1b89afdfc7dd5116 | 8182d969fb54600c13738412f4c6f947f044f865 | refs/heads/master | 2021-08-22T08:11:27.101000 | 2020-09-15T09:16:49 | 2020-09-15T09:16:49 | 295,421,411 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* $Id: MTLConstantObject.java,v 1.2 2004-05-19 09:21:37 sdzale Exp $
* Authors : ${user}
*
* Created on ${date}
* Copyright 2004 - INRIA - LGPL license
*/
package org.inria.mtl.plugin.editors.mtlsyntax;
/**
* @author sdzale
*
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class MTLConstantObject extends MTLObject{
public MTLConstantObject(String Name, String Description) {
super(Name, Description);
}
} | UTF-8 | Java | 485 | java | MTLConstantObject.java | Java | [
{
"context": ": MTLConstantObject.java,v 1.2 2004-05-19 09:21:37 sdzale Exp $\n* Authors : ${user}\n*\n* Created on ${date}\n",
"end": 65,
"score": 0.964921236038208,
"start": 59,
"tag": "USERNAME",
"value": "sdzale"
},
{
"context": "nria.mtl.plugin.editors.mtlsyntax;\n\n/**\n * @author sdzale\n *\n * To change this generated comment go to \n * ",
"end": 229,
"score": 0.9996009469032288,
"start": 223,
"tag": "USERNAME",
"value": "sdzale"
}
]
| null | []
| /*
* $Id: MTLConstantObject.java,v 1.2 2004-05-19 09:21:37 sdzale Exp $
* Authors : ${user}
*
* Created on ${date}
* Copyright 2004 - INRIA - LGPL license
*/
package org.inria.mtl.plugin.editors.mtlsyntax;
/**
* @author sdzale
*
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class MTLConstantObject extends MTLObject{
public MTLConstantObject(String Name, String Description) {
super(Name, Description);
}
} | 485 | 0.721649 | 0.680412 | 20 | 23.299999 | 23.188574 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 15 |
4582d98848e04bce131c4cd9e805b0c913ca9ea5 | 35,957,466,228,544 | 4e87e7076805978b660ad0fa9be8c81687999ae9 | /tinkerpatchdemo/src/main/java/com/itxiaox/tinkerdemo/ErrorUtils.java | d1d5567815c58154b9874d7cc838d83db43ce5ce | []
| no_license | itxiaox/HotFixLab | https://github.com/itxiaox/HotFixLab | 96288a24c13ee5bca29209a90fd1642ab3c7192c | 85cad0b6161325d1d0c8c63ebd3cb809c0368878 | refs/heads/master | 2020-06-28T22:54:55.898000 | 2019-08-21T00:57:45 | 2019-08-21T00:57:45 | 200,363,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itxiaox.tinkerdemo;
public class ErrorUtils {
public static int getSum(){
int a = 20;
int b = 1 ;
return a/b;
}
}
| UTF-8 | Java | 161 | java | ErrorUtils.java | Java | []
| null | []
| package com.itxiaox.tinkerdemo;
public class ErrorUtils {
public static int getSum(){
int a = 20;
int b = 1 ;
return a/b;
}
}
| 161 | 0.546584 | 0.52795 | 10 | 15.1 | 11.894957 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 15 |
94c19c82d96b1d28e83f1d044ee10494abe86718 | 27,668,179,385,274 | 8bf35842317aeee7ab92e85cba6c262eb6e7cc28 | /order-service/src/main/java/top/fan2wan/order/config/ConsumerConfig.java | 7043b8ef8471f944aa2fa4a4bce6e6d582372173 | []
| no_license | wmq95/integrate | https://github.com/wmq95/integrate | c441afe4ab189b34244f1c43c2e92e3808fb1f30 | 38d677d1e1673797b760bae64a7e8a2b2f3cd862 | refs/heads/master | 2023-07-19T07:08:46.135000 | 2021-08-13T06:27:32 | 2021-08-13T06:27:32 | 299,218,445 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package top.fan2wan.order.config;
import org.springframework.context.annotation.Configuration;
import top.fan2wan.database.rocketmq.simple.AbstractConsumerConfig;
/**
* @Author: fanT
* @Date: 2021/3/30 8:57
* @Description: config for consumer
*/
@Configuration
public class ConsumerConfig extends AbstractConsumerConfig{
}
| UTF-8 | Java | 343 | java | ConsumerConfig.java | Java | [
{
"context": "simple.AbstractConsumerConfig;\r\n\r\n/**\r\n * @Author: fanT\r\n * @Date: 2021/3/30 8:57\r\n * @Description: confi",
"end": 191,
"score": 0.9994943141937256,
"start": 187,
"tag": "USERNAME",
"value": "fanT"
}
]
| null | []
| package top.fan2wan.order.config;
import org.springframework.context.annotation.Configuration;
import top.fan2wan.database.rocketmq.simple.AbstractConsumerConfig;
/**
* @Author: fanT
* @Date: 2021/3/30 8:57
* @Description: config for consumer
*/
@Configuration
public class ConsumerConfig extends AbstractConsumerConfig{
}
| 343 | 0.760933 | 0.725947 | 13 | 24.384615 | 23.769854 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 15 |
5ce624d32adc8b6ead2ce2a639a00373cd6a3a66 | 24,756,191,547,086 | 6a46e047adeb2783499fa9014a31ee20397999a2 | /DiffuzerEngine/ejbModule/entities/feeders/Feeder.java | dad49fbabb87112d7021b9c812e8ce81c399f9d2 | []
| no_license | emilianofs/difuzzer-engine | https://github.com/emilianofs/difuzzer-engine | 94311b40210591da6e5cb016a5c5fc6eadf405db | bea9a2f47189ee7a8ec188fca4a16ca38de6ddaa | refs/heads/master | 2016-09-14T01:13:37.948000 | 2016-04-01T07:29:27 | 2016-04-01T07:29:27 | 57,911,405 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package entities.feeders;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import dtos.entities.FeederDTO;
import entities.core.Channel;
import entities.core.User;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "feeders")
public abstract class Feeder implements Serializable{
private static final long serialVersionUID = -1416013689997390278L;
@Transient
private final static Logger logger = Logger.getLogger( Feeder.class.getName() );
public static enum Type{
REMOTE,
RANDOM_TEXT,
RANDOM_PHOTO
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected int id;
@ManyToOne
protected User user;
@Enumerated(EnumType.STRING)
protected Type feederType;
protected String name;
@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "feeder")
protected List<ElementFed> elementsFed = new ArrayList<ElementFed>();
protected int minElements;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<ElementFed> getElementsFed() {
return elementsFed;
}
public void setElementsFed(List<ElementFed> elementsFed) {
this.elementsFed = elementsFed;
}
public Type getFeederType() {
return feederType;
}
public void setFeederType(Type feederType) {
this.feederType = feederType;
}
public int getMinElements() {
return minElements;
}
public void setMinElements(int minElements) {
this.minElements = minElements;
}
public void removeElementFed(ElementFed element){
this.elementsFed.remove(element);
}
/************/
public abstract FeederDTO getDTO();
// SE ENCARGA DE AGREGAR A LA COLECCIÓN
// public abstract List<ElementFed> checkLoadElements();
public List<ElementFed> getNewUnpublishedElements(Integer quantity, Channel channel) {
String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
List<ElementFed> feederElements = this.getUnpublished(channel, quantity);
int unpublishedChannel = feederElements.size();
if(unpublishedChannel < quantity ){
int unpublishedTotal = this.getUnpublished();
int needed = quantity - unpublishedChannel;
if(this.minElements == unpublishedTotal){
if(this.minElements < needed){
int newMin = this.minElements + needed;
logger.info(method+" MIN "+this.minElements+", NEW MIN "+newMin+", NEEDED "+needed+"");
this.minElements = newMin;
}else if(this.minElements == needed){
logger.info(method+" HAVE JUST ENOUGH IN MIN, ELEMENTS NOT SYNCED");
}else if(this.minElements > needed){
logger.info(method+" HAVE MORE THAN ENOUGH IN MIN, ELEMENTS NOT SYNCED OR PROBLEM");
}else{
logger.info(method+" THE UNIVERSE IS EXPLODING");
}
}else if(this.minElements < unpublishedTotal){
int newMin = unpublishedTotal + needed;
logger.info(method+" MIN "+this.minElements+", NEW MIN "+newMin+", NEEDED "+needed+"");
this.minElements = newMin;
}else if(this.minElements > unpublishedTotal){
logger.info(method+" MORE UNPUBLISHED ELEMENTS THAN MIN");
}else{
logger.info(method+" THE UNIVERSE IS EXPLODING TWICE");
}
feederElements = null;
}else{
// VENTANA DESLIZANTE
this.minElements = quantity;
}
return feederElements;
}
public int getUnpublished(){
// String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
int unpublished = 0;
for(int i = 0; i < this.elementsFed.size(); i++){
ElementFed element = this.elementsFed.get(i);
if(!element.isPublished()){
unpublished++;
}
}
return unpublished;
}
protected List<ElementFed> getUnpublished(Channel channel, int quantity){
// String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
List<ElementFed> elements = new ArrayList<ElementFed>();
for(int i = 0; i < this.elementsFed.size() && elements.size() < quantity; i++){
ElementFed element = this.elementsFed.get(i);
if(!element.isPublished(channel)){
elements.add(element);
}
}
return elements;
}
public boolean exists(ElementFed newElement){
// String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
boolean exists = false;
for(int i = 0; i < this.elementsFed.size(); i++){
ElementFed element = this.elementsFed.get(i);
if(element.equals(newElement)){
exists = true;
}
}
return exists;
}
public int getElementGap(){
String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
int gap = 0;
gap = this.minElements - this.getUnpublished();
logger.info(method+" GAP: "+gap);
return gap;
}
}
| ISO-8859-3 | Java | 5,932 | java | Feeder.java | Java | [
{
"context": "\r\n\tpublic void setUser(User user) {\r\n\t\tthis.user = user;\r\n\t}\r\n\t\r\n\tpublic List<ElementFed> getElementsFed(",
"end": 1811,
"score": 0.5604132413864136,
"start": 1807,
"tag": "USERNAME",
"value": "user"
}
]
| null | []
| package entities.feeders;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import dtos.entities.FeederDTO;
import entities.core.Channel;
import entities.core.User;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "feeders")
public abstract class Feeder implements Serializable{
private static final long serialVersionUID = -1416013689997390278L;
@Transient
private final static Logger logger = Logger.getLogger( Feeder.class.getName() );
public static enum Type{
REMOTE,
RANDOM_TEXT,
RANDOM_PHOTO
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected int id;
@ManyToOne
protected User user;
@Enumerated(EnumType.STRING)
protected Type feederType;
protected String name;
@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "feeder")
protected List<ElementFed> elementsFed = new ArrayList<ElementFed>();
protected int minElements;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<ElementFed> getElementsFed() {
return elementsFed;
}
public void setElementsFed(List<ElementFed> elementsFed) {
this.elementsFed = elementsFed;
}
public Type getFeederType() {
return feederType;
}
public void setFeederType(Type feederType) {
this.feederType = feederType;
}
public int getMinElements() {
return minElements;
}
public void setMinElements(int minElements) {
this.minElements = minElements;
}
public void removeElementFed(ElementFed element){
this.elementsFed.remove(element);
}
/************/
public abstract FeederDTO getDTO();
// SE ENCARGA DE AGREGAR A LA COLECCIÓN
// public abstract List<ElementFed> checkLoadElements();
public List<ElementFed> getNewUnpublishedElements(Integer quantity, Channel channel) {
String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
List<ElementFed> feederElements = this.getUnpublished(channel, quantity);
int unpublishedChannel = feederElements.size();
if(unpublishedChannel < quantity ){
int unpublishedTotal = this.getUnpublished();
int needed = quantity - unpublishedChannel;
if(this.minElements == unpublishedTotal){
if(this.minElements < needed){
int newMin = this.minElements + needed;
logger.info(method+" MIN "+this.minElements+", NEW MIN "+newMin+", NEEDED "+needed+"");
this.minElements = newMin;
}else if(this.minElements == needed){
logger.info(method+" HAVE JUST ENOUGH IN MIN, ELEMENTS NOT SYNCED");
}else if(this.minElements > needed){
logger.info(method+" HAVE MORE THAN ENOUGH IN MIN, ELEMENTS NOT SYNCED OR PROBLEM");
}else{
logger.info(method+" THE UNIVERSE IS EXPLODING");
}
}else if(this.minElements < unpublishedTotal){
int newMin = unpublishedTotal + needed;
logger.info(method+" MIN "+this.minElements+", NEW MIN "+newMin+", NEEDED "+needed+"");
this.minElements = newMin;
}else if(this.minElements > unpublishedTotal){
logger.info(method+" MORE UNPUBLISHED ELEMENTS THAN MIN");
}else{
logger.info(method+" THE UNIVERSE IS EXPLODING TWICE");
}
feederElements = null;
}else{
// VENTANA DESLIZANTE
this.minElements = quantity;
}
return feederElements;
}
public int getUnpublished(){
// String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
int unpublished = 0;
for(int i = 0; i < this.elementsFed.size(); i++){
ElementFed element = this.elementsFed.get(i);
if(!element.isPublished()){
unpublished++;
}
}
return unpublished;
}
protected List<ElementFed> getUnpublished(Channel channel, int quantity){
// String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
List<ElementFed> elements = new ArrayList<ElementFed>();
for(int i = 0; i < this.elementsFed.size() && elements.size() < quantity; i++){
ElementFed element = this.elementsFed.get(i);
if(!element.isPublished(channel)){
elements.add(element);
}
}
return elements;
}
public boolean exists(ElementFed newElement){
// String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
boolean exists = false;
for(int i = 0; i < this.elementsFed.size(); i++){
ElementFed element = this.elementsFed.get(i);
if(element.equals(newElement)){
exists = true;
}
}
return exists;
}
public int getElementGap(){
String method = this.getClass().toString()+"/"+Thread.currentThread().getStackTrace()[1].getMethodName();
// logger.info(method);
/*******/
int gap = 0;
gap = this.minElements - this.getUnpublished();
logger.info(method+" GAP: "+gap);
return gap;
}
}
| 5,932 | 0.673074 | 0.668184 | 226 | 24.243362 | 25.011467 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.11062 | false | false | 15 |
2046d081ee1791d76733812ec78fe9473901c86f | 37,177,236,940,681 | 5b87c14b0fccf49d873f96417bdbe06686a1d1c3 | /plugins/plugins-security/plugins-security-jwt/src/main/java/com/skrivet/plugins/security/jwt/service/JwtSecurityService.java | 9a100b563f6a5cc3d5851dbbb0fe2f61fa1a03ed | [
"Apache-2.0"
]
| permissive | polarloves/skrivet | https://github.com/polarloves/skrivet | 76f83f95c845d3747d4886cce0b102c64fa1bb7d | 0a9d5c62326d879ace80c26be5170d27b3dcc284 | refs/heads/main | 2023-07-13T13:30:26.781000 | 2021-08-18T13:17:44 | 2021-08-18T13:17:44 | 397,596,146 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.skrivet.plugins.security.jwt.service;
import com.skrivet.components.jwt.subject.Action;
import com.skrivet.components.jwt.subject.Subject;
import com.skrivet.core.common.exception.NotSupportExp;
import com.skrivet.core.common.exception.account.AccountDisableExp;
import com.skrivet.core.common.exception.account.AccountNotFoundExp;
import com.skrivet.core.common.exception.account.IncorrectPasswordExp;
import com.skrivet.plugins.security.core.encryption.EncryptionService;
import com.skrivet.plugins.security.core.entity.ActiveUser;
import com.skrivet.plugins.security.core.entity.PermissionSet;
import com.skrivet.plugins.security.core.entity.User;
import com.skrivet.plugins.security.core.service.PermissionSetService;
import com.skrivet.plugins.security.core.service.SecurityService;
import com.skrivet.plugins.security.core.service.UserService;
import com.skrivet.plugins.security.jwt.util.JWTUtil;
import com.skrivet.plugins.security.jwt.util.SubjectUtil;
import java.util.List;
public class JwtSecurityService implements SecurityService {
private UserService userService;
private PermissionSetService permissionSetService;
private String signKey;
private long timeout;
private EncryptionService encryptionService;
public JwtSecurityService(UserService userService, PermissionSetService permissionSetService, EncryptionService encryptionServic, String signKey, long timeout) {
this.userService = userService;
this.permissionSetService = permissionSetService;
this.signKey = signKey;
this.timeout = timeout;
this.encryptionService = encryptionServic;
}
@Override
public List<ActiveUser> activeUser(String userId) {
return null;
}
@Override
public String currentUserId() {
User user = currentUser();
if (user != null) {
return user.getId();
}
return null;
}
@Override
public User currentUser() {
Subject subject = SubjectUtil.getSubject();
if (subject != null) {
return (User) subject.getObject();
}
return null;
}
@Override
public void shotOffBySessionId(String sessionId, String msg) {
throw new NotSupportExp().variable("shotOffBySessionId");
}
@Override
public void shotOffByUserId(String userId, String msg) {
throw new NotSupportExp().variable("shotOffByUserId");
}
@Override
public void removeTokenCache(String userName) {
}
@Override
public void removePermissionCache(String userId) {
}
@Override
public String login(String userName, String password, boolean checkPassword, boolean alwaysActive) {
User user = userService.selectUserByUserName(userName);
if (user == null) {
throw new AccountNotFoundExp();
}
if (user.getState() != 1) {
throw new AccountDisableExp(user.getDisableReason());
}
if (checkPassword) {
if (!encryptionService.encryptionPassword(password, user.getSalt()).equals(user.getPassword())) {
throw new IncorrectPasswordExp();
}
}
PermissionSet permissionSet = permissionSetService.selectPermissionSetByUserId(user.getId());
user.setPermissions(permissionSet.getPermissions());
user.setRoles(permissionSet.getRoles());
String token = JWTUtil.createToken(user.getId(), user.getAccount(), signKey, timeout);
Subject subject = new Subject();
subject.setToken(token);
subject.setAction(Action.CREATE);
subject.setObject(user);
SubjectUtil.bindSubject(subject);
SubjectUtil.noticeSubjectChanged(Action.CREATE);
return token;
}
@Override
public void logout() {
SubjectUtil.noticeSubjectChanged(Action.DELETE);
}
}
| UTF-8 | Java | 3,871 | java | JwtSecurityService.java | Java | [
{
"context": " }\n\n @Override\n public String login(String userName, String password, boolean checkPassword, boolean ",
"end": 2642,
"score": 0.9878135919570923,
"start": 2634,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " User user = userService.selectUserByUserName(userName);\n if (user == null) {\n throw n",
"end": 2769,
"score": 0.9563544988632202,
"start": 2761,
"tag": "USERNAME",
"value": "userName"
}
]
| null | []
| package com.skrivet.plugins.security.jwt.service;
import com.skrivet.components.jwt.subject.Action;
import com.skrivet.components.jwt.subject.Subject;
import com.skrivet.core.common.exception.NotSupportExp;
import com.skrivet.core.common.exception.account.AccountDisableExp;
import com.skrivet.core.common.exception.account.AccountNotFoundExp;
import com.skrivet.core.common.exception.account.IncorrectPasswordExp;
import com.skrivet.plugins.security.core.encryption.EncryptionService;
import com.skrivet.plugins.security.core.entity.ActiveUser;
import com.skrivet.plugins.security.core.entity.PermissionSet;
import com.skrivet.plugins.security.core.entity.User;
import com.skrivet.plugins.security.core.service.PermissionSetService;
import com.skrivet.plugins.security.core.service.SecurityService;
import com.skrivet.plugins.security.core.service.UserService;
import com.skrivet.plugins.security.jwt.util.JWTUtil;
import com.skrivet.plugins.security.jwt.util.SubjectUtil;
import java.util.List;
public class JwtSecurityService implements SecurityService {
private UserService userService;
private PermissionSetService permissionSetService;
private String signKey;
private long timeout;
private EncryptionService encryptionService;
public JwtSecurityService(UserService userService, PermissionSetService permissionSetService, EncryptionService encryptionServic, String signKey, long timeout) {
this.userService = userService;
this.permissionSetService = permissionSetService;
this.signKey = signKey;
this.timeout = timeout;
this.encryptionService = encryptionServic;
}
@Override
public List<ActiveUser> activeUser(String userId) {
return null;
}
@Override
public String currentUserId() {
User user = currentUser();
if (user != null) {
return user.getId();
}
return null;
}
@Override
public User currentUser() {
Subject subject = SubjectUtil.getSubject();
if (subject != null) {
return (User) subject.getObject();
}
return null;
}
@Override
public void shotOffBySessionId(String sessionId, String msg) {
throw new NotSupportExp().variable("shotOffBySessionId");
}
@Override
public void shotOffByUserId(String userId, String msg) {
throw new NotSupportExp().variable("shotOffByUserId");
}
@Override
public void removeTokenCache(String userName) {
}
@Override
public void removePermissionCache(String userId) {
}
@Override
public String login(String userName, String password, boolean checkPassword, boolean alwaysActive) {
User user = userService.selectUserByUserName(userName);
if (user == null) {
throw new AccountNotFoundExp();
}
if (user.getState() != 1) {
throw new AccountDisableExp(user.getDisableReason());
}
if (checkPassword) {
if (!encryptionService.encryptionPassword(password, user.getSalt()).equals(user.getPassword())) {
throw new IncorrectPasswordExp();
}
}
PermissionSet permissionSet = permissionSetService.selectPermissionSetByUserId(user.getId());
user.setPermissions(permissionSet.getPermissions());
user.setRoles(permissionSet.getRoles());
String token = JWTUtil.createToken(user.getId(), user.getAccount(), signKey, timeout);
Subject subject = new Subject();
subject.setToken(token);
subject.setAction(Action.CREATE);
subject.setObject(user);
SubjectUtil.bindSubject(subject);
SubjectUtil.noticeSubjectChanged(Action.CREATE);
return token;
}
@Override
public void logout() {
SubjectUtil.noticeSubjectChanged(Action.DELETE);
}
}
| 3,871 | 0.706277 | 0.706019 | 112 | 33.5625 | 29.357944 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580357 | false | false | 15 |
413563125558bdcb7bd2e7208a59d17e954b4fe6 | 369,367,257,129 | 4c7b95cbd83435dc6ce7db75b934872596d22dc7 | /src/main/java/com/duyle/assignmentmanagement/entity/Assignment.java | c51ae85ea562d30ede4fac65ab7e5a08009abc3a | []
| no_license | duyle112/assignmentmanagement | https://github.com/duyle112/assignmentmanagement | 529ff8cd302d4fe0f30cb752b236f05be0cd7282 | 52a9c00b42972b4c2cf66959e2619d2a894204ca | refs/heads/master | 2021-01-19T17:00:47.372000 | 2017-08-22T07:45:59 | 2017-08-22T07:45:59 | 101,035,823 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.duyle.assignmentmanagement.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="Assignment")
public class Assignment implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column()
private String subject;
@Column()
private String content;
@Column()
private String due_date;
@Column()
private String attachment;
@ManyToMany
@JoinTable(name="Group_Assignment",joinColumns ={@JoinColumn(name="assignment_id")},inverseJoinColumns={@JoinColumn(name="group_id")})
private List<Group> groups;
@ManyToOne
@JoinColumn(name="reporter_id")
private User user;
@OneToMany(mappedBy="assignment",cascade=CascadeType.ALL)
private List<Submission> submissions = new ArrayList<>();
public List<Submission> getSubmissions() {
return submissions;
}
public void setSubmissions(List<Submission> submissions) {
this.submissions = submissions;
}
public Assignment(){
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDue_date() {
return due_date;
}
public void setDue_date(String due_date) {
this.due_date = due_date;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
public Assignment(String subject, String content, String due_date, String attachment, List<Group> groups) {
super();
this.subject = subject;
this.content = content;
this.due_date = due_date;
this.attachment = attachment;
this.groups = groups;
}
}
| UTF-8 | Java | 2,642 | java | Assignment.java | Java | []
| null | []
| package com.duyle.assignmentmanagement.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="Assignment")
public class Assignment implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column()
private String subject;
@Column()
private String content;
@Column()
private String due_date;
@Column()
private String attachment;
@ManyToMany
@JoinTable(name="Group_Assignment",joinColumns ={@JoinColumn(name="assignment_id")},inverseJoinColumns={@JoinColumn(name="group_id")})
private List<Group> groups;
@ManyToOne
@JoinColumn(name="reporter_id")
private User user;
@OneToMany(mappedBy="assignment",cascade=CascadeType.ALL)
private List<Submission> submissions = new ArrayList<>();
public List<Submission> getSubmissions() {
return submissions;
}
public void setSubmissions(List<Submission> submissions) {
this.submissions = submissions;
}
public Assignment(){
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDue_date() {
return due_date;
}
public void setDue_date(String due_date) {
this.due_date = due_date;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
public Assignment(String subject, String content, String due_date, String attachment, List<Group> groups) {
super();
this.subject = subject;
this.content = content;
this.due_date = due_date;
this.attachment = attachment;
this.groups = groups;
}
}
| 2,642 | 0.724073 | 0.723694 | 161 | 15.409938 | 20.019392 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.099379 | false | false | 15 |
d2460afd0d12f8f63e16d2a45b5f967750c82118 | 39,487,929,332,129 | 0916da96cc4ffd4fccb68ca71a08f7b5a17c5657 | /src/day15_string_manipulation/WarmUpEmojies.java | e723c728f2568c79cee2e1ec6c3bb21754d7354b | []
| no_license | bogdanovsergei/java-practice | https://github.com/bogdanovsergei/java-practice | 17ff68bec6cdede93fbc826e3e6a1585436ab78e | b0d75a005bb25170adaaaa5f722402a7f32fb1b3 | refs/heads/master | 2020-05-23T12:12:24.422000 | 2019-05-29T22:24:14 | 2019-05-29T22:24:14 | 186,751,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day15_string_manipulation;
import java.util.*;
public class WarmUpEmojies {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter emoji: ");
String emoji = scan.next();
if (emoji.length()!=2) {
System.out.println("Invalid emoji.");
return;
}
if (emoji.charAt(0) == ':') {
switch (emoji.charAt(1)) {
case ')':
System.out.println("Smile");
break;
case '(':
System.out.println("Sad");
break;
case '/':
System.out.println("Upset");
break;
case 'p':
System.out.println("Playful");
break;
default:
System.out.println("Unknown emoji");
}
} else if (emoji.charAt(0) == ';') {
switch (emoji.charAt(1)) {
case ')':
System.out.println("Wink");
break;
case '0':
System.out.println("surprised");
break;
default:
System.out.println("Unknown emoji");
}
} else if (emoji.charAt(0) == ')') {
if (emoji.charAt(1) == ':')
System.out.println("sad");
else
System.out.println("Unknown emoji");
} else if (emoji.charAt(0) == '(') {
if (emoji.charAt(1) == ':')
System.out.println("smile");
else
System.out.println("Unknown emoji");
}
}
}
| UTF-8 | Java | 1,235 | java | WarmUpEmojies.java | Java | []
| null | []
| package day15_string_manipulation;
import java.util.*;
public class WarmUpEmojies {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter emoji: ");
String emoji = scan.next();
if (emoji.length()!=2) {
System.out.println("Invalid emoji.");
return;
}
if (emoji.charAt(0) == ':') {
switch (emoji.charAt(1)) {
case ')':
System.out.println("Smile");
break;
case '(':
System.out.println("Sad");
break;
case '/':
System.out.println("Upset");
break;
case 'p':
System.out.println("Playful");
break;
default:
System.out.println("Unknown emoji");
}
} else if (emoji.charAt(0) == ';') {
switch (emoji.charAt(1)) {
case ')':
System.out.println("Wink");
break;
case '0':
System.out.println("surprised");
break;
default:
System.out.println("Unknown emoji");
}
} else if (emoji.charAt(0) == ')') {
if (emoji.charAt(1) == ':')
System.out.println("sad");
else
System.out.println("Unknown emoji");
} else if (emoji.charAt(0) == '(') {
if (emoji.charAt(1) == ':')
System.out.println("smile");
else
System.out.println("Unknown emoji");
}
}
}
| 1,235 | 0.575709 | 0.565992 | 56 | 21.053572 | 13.878838 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.232143 | false | false | 15 |
66246c9ff6d6d0158c2f89495e792d239c686eeb | 34,969,623,769,291 | f6c4158d03e9104cbf8eac80c33ce9257806c4f4 | /Maven Guru/Exercises/ex7/multimodule-maven/HelloFromEclipse.java | 4694d9ca8de95d68ee6758352d5626dd11122fca | []
| no_license | Vibri/Udemy | https://github.com/Vibri/Udemy | 358f9878cc96c58aaa58ed2a914ac16a381884c0 | 13d9617b93d6a44a34278aea66cfbad572080d6c | refs/heads/master | 2023-05-28T21:51:46.981000 | 2023-05-18T21:37:42 | 2023-05-18T21:37:42 | 242,228,193 | 0 | 0 | null | false | 2022-11-16T11:36:45 | 2020-02-21T20:49:49 | 2022-01-04T21:07:59 | 2022-11-16T11:36:42 | 553 | 0 | 0 | 10 | Java | false | false |
public class HelloFromEclipse {
public String sayHello() {
return "Hello from Eclipse!";
}
}
| UTF-8 | Java | 101 | java | HelloFromEclipse.java | Java | []
| null | []
|
public class HelloFromEclipse {
public String sayHello() {
return "Hello from Eclipse!";
}
}
| 101 | 0.683168 | 0.683168 | 7 | 13.285714 | 14.249955 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 15 |
be290bcc78050432559f34fa40bf0dcedc6d64e6 | 37,580,963,872,354 | 0289fdc02f898d15ad885c583b79d717f87d418f | /automated-testing-AllureSelenoid/src/test/java/ru/cfmc/dev/quotas/tests/Form8802_8803_8804/Form8803.java | dbdc04d919983b9a9b64214b9a635a9d7b7a7772 | []
| no_license | Dust09/requests | https://github.com/Dust09/requests | 962d081698d3b523da57f480c15f8999a2652aa5 | 69af29a5b8afc55f252b382d91984ce3f28147ea | refs/heads/master | 2023-06-29T21:52:16.469000 | 2021-08-02T19:10:34 | 2021-08-02T19:10:34 | 386,059,540 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.cfmc.dev.quotas.tests.Form8802_8803_8804;
import io.qameta.allure.*;
import org.junit.jupiter.api.*;
import org.openqa.selenium.By;
import org.openqa.selenium.TakesScreenshot;
import ru.cfmc.dev.quotas.tests.smoke.smokeForm8802.PageObject88_02;
import java.io.ByteArrayInputStream;
import static io.qameta.allure.Allure.step;
import static org.openqa.selenium.OutputType.BYTES;
@Epic("Форма 88.02")
@Feature("Форма 88.03")
public class Form8803 extends TestBaseFor8802_8803_8804 {
PageObject88_02 pageObject88_02 = new PageObject88_02();
@Description("Названия тест кейса: Сценарий \"Добавить новые ВБР, ОДУ которых устанавливается - откытие диалогового окна")
@Link(name="2.3.1", url="https://atlassian.cfmc.ru/display/CFMC/2.3.1")
@Test
public void t2_3_1(){
//Выбрать любой проект и в столбце действий нажать "Просмотр и редактирование проектов ОДУ"
odu();
Assertions.assertEquals("Проект ОДУ - Ввод и редактирование общих допустимых уловов",getText("//h1[contains(text(),'Проект ОДУ - Ввод и редактирование общих допустимы')]"));
}
//@RepeatedTest(10)
@Description("Названия тест кейса: Сценарий выбора ВБР в районах добычи (вылова)")
@Link(name="2.3.2", url="https://atlassian.cfmc.ru/display/CFMC/2.3.2")
@Test
public void t2_3_2(){
//step("Создать проект приказа");
createOrder();
//step("Нажать ОК");
window_accept();
String comm = stringBuilder();
//Ввести комментарий: "+ comm
enterComment(comm);
//Нажать сохранить
saveButton();
//Навести курсор на кнопку "Меню" и нажать "Добавить пары ОДУ в проект приказа"
menuAddOdu();
//step("Выбираем (ставим галочки) напротив нескольких ВБР");
addVbrCase();
//step("Нажать сохранить");
saveButton();
//step(" перейти на сайт http://quotas-dev.cfmc.ru/fishery/quotatest/applications/applications-nav 2) кликнуть иконку 88.02.");
goTo88_02();
//step("В поле комментарий ввести: "+ comm);
findByComment(comm);
//step("Наводим на курсор на меню действие и нажимаем \"\"Просмотр и редактирование проектов ОДУ\"");
odu();
//проверка
assertVbrCase();
step("Делаем шаг назад в браузере");
driver.navigate().back();
//step("в поле фильтра по колонке \"Комментарий\" набираем: "+ comm);
findByComment(comm);
//step("Наводим на курсор на меню действие и нажимаем \"\"Просмотр и редактирование проектов ОДУ\"");
odu();
//step("Навести курсор на меню и нажать отправить проект приказа в архив");
menuDelete();
//step("Нажать ок");
window_accept();
sleep(300);
//проверка
//goTo88_02();
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Отправить в архив (удалить)\"")
@Link(name="2.3.3", url="https://atlassian.cfmc.ru/display/CFMC/2.3.3")
@Test
public void t2_3_3(){
String comm = stringBuilder();
//step("Нажать кнопку \"Создать новый проект приказа\"");
createOrder();
//step("Нажать Ок");
window_accept();
//step("в поле комментарий вносим текст: " + comm);
enterComment(comm);
//step("нажимаем кнопку \"Сохранить\"");
saveButton();
//step("навести курсор на кнопку \"Меню\" и нажать \"отправить проект приказа в архив(удалить)\"");
menuDelete();
//step("нажимаем кнопку \"Ок\"");
window_accept();
//проверка
//goTo88_02();
findByCommentDelete(comm);
}
// @RepeatedTest(10)
@Test
@Description("Названия тест кейса: Сценарий открытие диалогового окна добавления сносок")
@Link(name="2.3.4", url="https://atlassian.cfmc.ru/display/CFMC/2.3.4")
public void t2_3_4(){
String comm = stringBuilder();
//step("Нажать кнопку \"Создать новый проект приказа\"");
createOrder();
//step("Нажать Ок");
window_accept();
//step("в поле комментарий вносим текст: " + comm);
enterComment(comm);
//step("нажимаем кнопку \"Сохранить\"");
saveButton();
//step("Навести курсор на кнопку \"Меню\" и нажать \"Добавить пары ОДУ в проект приказа\"");
menuAddOdu();
//step("Выбираем (ставим галочки) напротив нескольких ВБР");
addVbrCase();
//step("Нажимаем кнопку \"Сохранить\"");
saveButton();
//step("Делаем \"Шаг назад\" в браузере");
driver.navigate().back();
assertVbrCase();
//step("навести курсор на меню \"Действие и нажать \"Редактирование добавление\" сносок\"");
menuEditSnoski();
//step("Нажимаем кнопку \"Добавить строку\"");
createSnoski();
//step("нажимаем кнопку \" Созранить\"");
saveButton();
//step("нажимаем \"шаг назад\" в браузере\"");
driver.navigate().back();
//step("навести курсор на меню \"Действие и нажать \"Выбор сносок\"");
selectSnoski();
//проверка
//step("Нажать сохранить");
saveButton();
//step("перейти в форму 88.02");
goTo88_02();
//step("найти приказ ");
findByComment(comm);
odu();
//проверка
correctSnoski();
//step("Меню удалить приказ");
menuDelete();
//step("ок");
window_accept();
//проверка
//goTo88_02();
sleep(1000);
findByCommentDelete(comm);
}
@Test
@Description("Названия тест кейса: Сценарий удаления сноски из строки формы 88.03/88.04")
@Link(name="2.3.8", url="https://atlassian.cfmc.ru/display/CFMC/2.3.8")
public void t2_3_8(){
//step("создать пустой проект приказа");
createOrder();
//step("Нажать ок");
window_accept();
String comm = stringBuilder();
//step("в поле комментарий ввести "+comm);
enterComment(comm);
//step("нажать сохранить");
saveButton();
//step("Навести курсор на кнопку 'Меню' и нажать 'Добавить пары ОДУ в проект приказа'");
menuAddOdu();
//step("Выбираем (ставим галочки) напротив нескольких ВБР");
addVbrCase();
//step("нажать сохранить");
saveButton();
step("Делаем \"Шаг назад\" в браузере");
driver.navigate().back();
assertVbrCase();
//step("навести курсор на меню \"Действие и нажать \"Редактирование добавление\" сносок\"");
menuEditSnoski();
createSnoski();
//step("нажимаем кнопку \" Сохранить\"");
saveButton();
//step("нажимаем \"шаг назад\" в браузере\"");
driver.navigate().back();
//step("навести курсор на меню \"Действие и нажать \"Выбор сносок\"");
//добавляем сноски
selectSnoski();
saveButton();
correctSnoski();
//step("перейти в форму 88.02");
goTo88_02();
findByComment(comm);
odu();
//step("Нажать на меню Выбор сносок");
//selectSnoskiDisable();
selectSnoski();
//step("нажать сохранить");
saveButton();
//step("Кликнуть на Действие Просмотр и редактирование сносок");
menuEditSnoski();
//step("удалить сноски");
driver.navigate().refresh();
deleteSnoski(4);
//step("нажать Сохранить");
saveButton();
driver.navigate().back();
//проверка
driver.navigate().refresh();
actionSnoski();
try {
click("//tbody/tr[1]/td[3]/div[1]/div[1]/div[1]/div[1]/div[1]");
step("сноски не удалены");
driver.get("http://quotas-dev.cfmc.ru:8172/fishery/quotatest/applications/applications-nav");
}catch (Exception e){
step("сноски удалены");
driver.navigate().refresh();
}
//step("удалить проект приказа");
menuDelete();
//step("ок");
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Test
@Description("Названия тест кейса: Сценарий просмотра сносок")
@Link(name="2.3.9", url="https://atlassian.cfmc.ru/display/CFMC/2.3.9")
//дубликат кейса 2.15.1
public void t2_3_9(){
// step("Создать пустой проект приказа");
createOrder();
//step("Ok");
window_accept();
String comm = stringBuilder();
// step("в поле комментарий ввести "+ comm);
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
menuEditSnoski();
createSnoski();
saveButton();
driver.navigate().back();
driver.navigate().refresh();
selectSnoski();
saveButton();
correctSnoski();
menuDelete();
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"открытие диалогового окна выбора сносок (проверка наличия элементов)\"")
@Link(name = "2.3.6", url = "https://atlassian.cfmc.ru/display/CFMC/2.3.6")
@Tag("smoke")
@Test
public void t2_3_6(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
assertVbrCase();
menuEditSnoski();
createSnoski();
saveButton();
driver.navigate().back();
selectSnoski();
goTo88_02();
findByComment(comm);
odu();
sleep(500);
menuDelete();
window_accept();
//goTo88_02();
sleep(300);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий удаления ряда\t")
@Link(name = "2.3.10",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.10")
@Test
public void t2_3_10(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
menuEditSnoski();
createSnoski();
saveButton();
deleteSnoski(4);
saveButton();
driver.navigate().back();
menuDelete();
window_accept();
//goTo88_02();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий удаления ряда\t")
@Link(name = "2.3.11",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.11")
@Tag("smoke")
@Test
public void t2_3_11(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
goTo88_02();
findByComment(comm);
}
@Description("Названия тест кейса: Сценарий удаления ряда\t")
@Link(name = "2.3.13",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.13")
@Tag("smoke")
@Test
public void t2_3_13(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
cancelButton();
sleep(500);
window_accept();
goTo88_02();
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий перевода проекта в статус " +
"\"Приказ утвержден\" и проверка доступности для изменения полей приказа в статусе \"Приказ утвержден\"\t")
@Link(name = "2.3.15",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.15")
@Tag("smoke")
@Test
public void t2_3_15() {
createOrder();
window_accept();
String comm = stringBuilder();
String num = numBuilder();
enterComment(comm);
saveButton();
enterNumOrder(num);
delDateOfOrder();
enterDateOfOrder();
statusOrderClick();
statusOrderApprovedClick();
saveButton();
goTo88_02();
//проверка
findByComment(comm);
//assertTableComm(comm);
assertTableDateApproved();
assertTableOrderNum(num);
assertTableStatus("Приказ утвержден");
assertTableDateApprovedLast();
odu();
//проверка
try {
menuDelete();
step("Кнопка меню отображается!!!");
Assertions.assertEquals("Кнопка меню открывается","кнопка");
} catch (Exception e) {
step("Кнопка Меню не отображается");
}
try {
for (int i = 1; i < 5; i++) {
sendKeys("(//input[contains(@readonly,'readonly')]//preceding-sibling::label/following-sibling::input)[" + i + "]", "111");
}
}catch (Exception e){
Assertions.assertEquals(1,2);
}
try {
saveButton();
step("Кнопка сохранить Кликабельна!!");
driver.get("https://cfmc.ru/");
}catch (Exception e){
step("Кнопка сохранить не кликабельна");
}
Assertions.assertEquals(7,statusApprovedAll());
goTo88_02();
}
@Description("Названия тест кейса: Сценарий перевода проекта в статус " +
"\"Согласование\" и проверка доступности для изменения полей приказа в статусе \"Согласование\".\t")
@Link(name = "2.3.16",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.16")
@Test
public void t2_3_16() {
createOrder();
window_accept();
String comm = stringBuilder();
String num = numBuilder();
enterComment(comm);
saveButton();
enterNumOrder(num);
enterDateOfOrder();
saveButton();
statusOrderClick();
statusOrderAgreeClick();
sleep(500);
saveButton();
sleep(500);
goTo88_02();
findByComment(comm);
assertTableComm(comm);
assertTableOrderNum(num);
assertTableDateApproved();
assertTableStatus("Согласование");
odu();
try{
menuAddOdu();
step("Добавить пары ОДУ в проект приказа отображается!!!");
driver.get("https://cfmc.ru/");
menuBtn();
}catch (Exception e){
step("Меню-Добавить пары ОДУ в проект приказ не кликабельна");
}
try {
find("//th[contains(text(),'Действие')]");
step("Кнопка Действие отображается!!!");
driver.get("https://cfmc.ru/");
menuBtn();
}catch (Exception e){
step("Колонка Действие не отображается");
}
System.out.println("----------------------");
Assertions.assertEquals(4,statusApprovedAll()); // в статусе согласование нельзя менять поля год ОДУ и комментарий
String num2 = numBuilder();
delNumOrder();
enterNumOrder(num2);
statusOrderClick();
statusOrderAgreeClick();
saveButton();
goTo88_02();
clearCommTable();
findByComment(comm);
assertTableStatus("Согласование");
assertTableOrderNum(num2);
assertTableComm(comm);
odu();
menuDelete();
window_accept();
//goTo88_02();
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Проверка ввода в поле 'Поиск' в ЭФ \"Таблица сносок\"\t")
@Link(name = "2.3.22",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.22")
@Test
public void t2_3_22() {
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
menuEditSnoski();
createSnoski();
saveButton();
searchInSnoskiField(2);
Assertions.assertEquals(3,driver.findElements(By.xpath("//tr")).size());
driver.navigate().back();
menuDelete();
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Проверка работоспособности кнопок 'Опции' в ЭФ \"Таблица сносок\"\"\t")
@Link(name = "2.3.28",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.28")
@Test
public void t2_3_28() {
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
//optionClick();
optionButtonsClick(12);
pageObject88_02.options_click();
Assertions.assertEquals("Опции для таблицы",
getText("//p[contains(text(),'Опции для таблицы ')]"));
pageObject88_02.options_close();
driver.navigate().refresh();
menuDelete();
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Добавить пары в приказ и перевести его в статус Согласование\"")
@Link(name = "2.3.30",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.30")
@Test
public String t2_3_30() {
generalElements.createProjectClick();
window_accept();
String com = stringBuilder();
enterComment(com);
deleteYear();
enterYear2020();
generalElements.saveButton();
String num = numBuilder();
enterNumOrder(num);
generalElements.saveButton();
menuAddOdu();
addVbrCase();
generalElements.saveButton();
driver.navigate().back();
enterODUcase();
generalElements.saveButton();
statusOrderClick();
statusOrderAgreeClick();
enterDateOfOrder();
generalElements.saveButton();
return com;
}
}
| UTF-8 | Java | 21,416 | java | Form8803.java | Java | []
| null | []
| package ru.cfmc.dev.quotas.tests.Form8802_8803_8804;
import io.qameta.allure.*;
import org.junit.jupiter.api.*;
import org.openqa.selenium.By;
import org.openqa.selenium.TakesScreenshot;
import ru.cfmc.dev.quotas.tests.smoke.smokeForm8802.PageObject88_02;
import java.io.ByteArrayInputStream;
import static io.qameta.allure.Allure.step;
import static org.openqa.selenium.OutputType.BYTES;
@Epic("Форма 88.02")
@Feature("Форма 88.03")
public class Form8803 extends TestBaseFor8802_8803_8804 {
PageObject88_02 pageObject88_02 = new PageObject88_02();
@Description("Названия тест кейса: Сценарий \"Добавить новые ВБР, ОДУ которых устанавливается - откытие диалогового окна")
@Link(name="2.3.1", url="https://atlassian.cfmc.ru/display/CFMC/2.3.1")
@Test
public void t2_3_1(){
//Выбрать любой проект и в столбце действий нажать "Просмотр и редактирование проектов ОДУ"
odu();
Assertions.assertEquals("Проект ОДУ - Ввод и редактирование общих допустимых уловов",getText("//h1[contains(text(),'Проект ОДУ - Ввод и редактирование общих допустимы')]"));
}
//@RepeatedTest(10)
@Description("Названия тест кейса: Сценарий выбора ВБР в районах добычи (вылова)")
@Link(name="2.3.2", url="https://atlassian.cfmc.ru/display/CFMC/2.3.2")
@Test
public void t2_3_2(){
//step("Создать проект приказа");
createOrder();
//step("Нажать ОК");
window_accept();
String comm = stringBuilder();
//Ввести комментарий: "+ comm
enterComment(comm);
//Нажать сохранить
saveButton();
//Навести курсор на кнопку "Меню" и нажать "Добавить пары ОДУ в проект приказа"
menuAddOdu();
//step("Выбираем (ставим галочки) напротив нескольких ВБР");
addVbrCase();
//step("Нажать сохранить");
saveButton();
//step(" перейти на сайт http://quotas-dev.cfmc.ru/fishery/quotatest/applications/applications-nav 2) кликнуть иконку 88.02.");
goTo88_02();
//step("В поле комментарий ввести: "+ comm);
findByComment(comm);
//step("Наводим на курсор на меню действие и нажимаем \"\"Просмотр и редактирование проектов ОДУ\"");
odu();
//проверка
assertVbrCase();
step("Делаем шаг назад в браузере");
driver.navigate().back();
//step("в поле фильтра по колонке \"Комментарий\" набираем: "+ comm);
findByComment(comm);
//step("Наводим на курсор на меню действие и нажимаем \"\"Просмотр и редактирование проектов ОДУ\"");
odu();
//step("Навести курсор на меню и нажать отправить проект приказа в архив");
menuDelete();
//step("Нажать ок");
window_accept();
sleep(300);
//проверка
//goTo88_02();
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Отправить в архив (удалить)\"")
@Link(name="2.3.3", url="https://atlassian.cfmc.ru/display/CFMC/2.3.3")
@Test
public void t2_3_3(){
String comm = stringBuilder();
//step("Нажать кнопку \"Создать новый проект приказа\"");
createOrder();
//step("Нажать Ок");
window_accept();
//step("в поле комментарий вносим текст: " + comm);
enterComment(comm);
//step("нажимаем кнопку \"Сохранить\"");
saveButton();
//step("навести курсор на кнопку \"Меню\" и нажать \"отправить проект приказа в архив(удалить)\"");
menuDelete();
//step("нажимаем кнопку \"Ок\"");
window_accept();
//проверка
//goTo88_02();
findByCommentDelete(comm);
}
// @RepeatedTest(10)
@Test
@Description("Названия тест кейса: Сценарий открытие диалогового окна добавления сносок")
@Link(name="2.3.4", url="https://atlassian.cfmc.ru/display/CFMC/2.3.4")
public void t2_3_4(){
String comm = stringBuilder();
//step("Нажать кнопку \"Создать новый проект приказа\"");
createOrder();
//step("Нажать Ок");
window_accept();
//step("в поле комментарий вносим текст: " + comm);
enterComment(comm);
//step("нажимаем кнопку \"Сохранить\"");
saveButton();
//step("Навести курсор на кнопку \"Меню\" и нажать \"Добавить пары ОДУ в проект приказа\"");
menuAddOdu();
//step("Выбираем (ставим галочки) напротив нескольких ВБР");
addVbrCase();
//step("Нажимаем кнопку \"Сохранить\"");
saveButton();
//step("Делаем \"Шаг назад\" в браузере");
driver.navigate().back();
assertVbrCase();
//step("навести курсор на меню \"Действие и нажать \"Редактирование добавление\" сносок\"");
menuEditSnoski();
//step("Нажимаем кнопку \"Добавить строку\"");
createSnoski();
//step("нажимаем кнопку \" Созранить\"");
saveButton();
//step("нажимаем \"шаг назад\" в браузере\"");
driver.navigate().back();
//step("навести курсор на меню \"Действие и нажать \"Выбор сносок\"");
selectSnoski();
//проверка
//step("Нажать сохранить");
saveButton();
//step("перейти в форму 88.02");
goTo88_02();
//step("найти приказ ");
findByComment(comm);
odu();
//проверка
correctSnoski();
//step("Меню удалить приказ");
menuDelete();
//step("ок");
window_accept();
//проверка
//goTo88_02();
sleep(1000);
findByCommentDelete(comm);
}
@Test
@Description("Названия тест кейса: Сценарий удаления сноски из строки формы 88.03/88.04")
@Link(name="2.3.8", url="https://atlassian.cfmc.ru/display/CFMC/2.3.8")
public void t2_3_8(){
//step("создать пустой проект приказа");
createOrder();
//step("Нажать ок");
window_accept();
String comm = stringBuilder();
//step("в поле комментарий ввести "+comm);
enterComment(comm);
//step("нажать сохранить");
saveButton();
//step("Навести курсор на кнопку 'Меню' и нажать 'Добавить пары ОДУ в проект приказа'");
menuAddOdu();
//step("Выбираем (ставим галочки) напротив нескольких ВБР");
addVbrCase();
//step("нажать сохранить");
saveButton();
step("Делаем \"Шаг назад\" в браузере");
driver.navigate().back();
assertVbrCase();
//step("навести курсор на меню \"Действие и нажать \"Редактирование добавление\" сносок\"");
menuEditSnoski();
createSnoski();
//step("нажимаем кнопку \" Сохранить\"");
saveButton();
//step("нажимаем \"шаг назад\" в браузере\"");
driver.navigate().back();
//step("навести курсор на меню \"Действие и нажать \"Выбор сносок\"");
//добавляем сноски
selectSnoski();
saveButton();
correctSnoski();
//step("перейти в форму 88.02");
goTo88_02();
findByComment(comm);
odu();
//step("Нажать на меню Выбор сносок");
//selectSnoskiDisable();
selectSnoski();
//step("нажать сохранить");
saveButton();
//step("Кликнуть на Действие Просмотр и редактирование сносок");
menuEditSnoski();
//step("удалить сноски");
driver.navigate().refresh();
deleteSnoski(4);
//step("нажать Сохранить");
saveButton();
driver.navigate().back();
//проверка
driver.navigate().refresh();
actionSnoski();
try {
click("//tbody/tr[1]/td[3]/div[1]/div[1]/div[1]/div[1]/div[1]");
step("сноски не удалены");
driver.get("http://quotas-dev.cfmc.ru:8172/fishery/quotatest/applications/applications-nav");
}catch (Exception e){
step("сноски удалены");
driver.navigate().refresh();
}
//step("удалить проект приказа");
menuDelete();
//step("ок");
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Test
@Description("Названия тест кейса: Сценарий просмотра сносок")
@Link(name="2.3.9", url="https://atlassian.cfmc.ru/display/CFMC/2.3.9")
//дубликат кейса 2.15.1
public void t2_3_9(){
// step("Создать пустой проект приказа");
createOrder();
//step("Ok");
window_accept();
String comm = stringBuilder();
// step("в поле комментарий ввести "+ comm);
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
menuEditSnoski();
createSnoski();
saveButton();
driver.navigate().back();
driver.navigate().refresh();
selectSnoski();
saveButton();
correctSnoski();
menuDelete();
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"открытие диалогового окна выбора сносок (проверка наличия элементов)\"")
@Link(name = "2.3.6", url = "https://atlassian.cfmc.ru/display/CFMC/2.3.6")
@Tag("smoke")
@Test
public void t2_3_6(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
assertVbrCase();
menuEditSnoski();
createSnoski();
saveButton();
driver.navigate().back();
selectSnoski();
goTo88_02();
findByComment(comm);
odu();
sleep(500);
menuDelete();
window_accept();
//goTo88_02();
sleep(300);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий удаления ряда\t")
@Link(name = "2.3.10",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.10")
@Test
public void t2_3_10(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
menuEditSnoski();
createSnoski();
saveButton();
deleteSnoski(4);
saveButton();
driver.navigate().back();
menuDelete();
window_accept();
//goTo88_02();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий удаления ряда\t")
@Link(name = "2.3.11",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.11")
@Tag("smoke")
@Test
public void t2_3_11(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
goTo88_02();
findByComment(comm);
}
@Description("Названия тест кейса: Сценарий удаления ряда\t")
@Link(name = "2.3.13",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.13")
@Tag("smoke")
@Test
public void t2_3_13(){
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
cancelButton();
sleep(500);
window_accept();
goTo88_02();
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий перевода проекта в статус " +
"\"Приказ утвержден\" и проверка доступности для изменения полей приказа в статусе \"Приказ утвержден\"\t")
@Link(name = "2.3.15",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.15")
@Tag("smoke")
@Test
public void t2_3_15() {
createOrder();
window_accept();
String comm = stringBuilder();
String num = numBuilder();
enterComment(comm);
saveButton();
enterNumOrder(num);
delDateOfOrder();
enterDateOfOrder();
statusOrderClick();
statusOrderApprovedClick();
saveButton();
goTo88_02();
//проверка
findByComment(comm);
//assertTableComm(comm);
assertTableDateApproved();
assertTableOrderNum(num);
assertTableStatus("Приказ утвержден");
assertTableDateApprovedLast();
odu();
//проверка
try {
menuDelete();
step("Кнопка меню отображается!!!");
Assertions.assertEquals("Кнопка меню открывается","кнопка");
} catch (Exception e) {
step("Кнопка Меню не отображается");
}
try {
for (int i = 1; i < 5; i++) {
sendKeys("(//input[contains(@readonly,'readonly')]//preceding-sibling::label/following-sibling::input)[" + i + "]", "111");
}
}catch (Exception e){
Assertions.assertEquals(1,2);
}
try {
saveButton();
step("Кнопка сохранить Кликабельна!!");
driver.get("https://cfmc.ru/");
}catch (Exception e){
step("Кнопка сохранить не кликабельна");
}
Assertions.assertEquals(7,statusApprovedAll());
goTo88_02();
}
@Description("Названия тест кейса: Сценарий перевода проекта в статус " +
"\"Согласование\" и проверка доступности для изменения полей приказа в статусе \"Согласование\".\t")
@Link(name = "2.3.16",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.16")
@Test
public void t2_3_16() {
createOrder();
window_accept();
String comm = stringBuilder();
String num = numBuilder();
enterComment(comm);
saveButton();
enterNumOrder(num);
enterDateOfOrder();
saveButton();
statusOrderClick();
statusOrderAgreeClick();
sleep(500);
saveButton();
sleep(500);
goTo88_02();
findByComment(comm);
assertTableComm(comm);
assertTableOrderNum(num);
assertTableDateApproved();
assertTableStatus("Согласование");
odu();
try{
menuAddOdu();
step("Добавить пары ОДУ в проект приказа отображается!!!");
driver.get("https://cfmc.ru/");
menuBtn();
}catch (Exception e){
step("Меню-Добавить пары ОДУ в проект приказ не кликабельна");
}
try {
find("//th[contains(text(),'Действие')]");
step("Кнопка Действие отображается!!!");
driver.get("https://cfmc.ru/");
menuBtn();
}catch (Exception e){
step("Колонка Действие не отображается");
}
System.out.println("----------------------");
Assertions.assertEquals(4,statusApprovedAll()); // в статусе согласование нельзя менять поля год ОДУ и комментарий
String num2 = numBuilder();
delNumOrder();
enterNumOrder(num2);
statusOrderClick();
statusOrderAgreeClick();
saveButton();
goTo88_02();
clearCommTable();
findByComment(comm);
assertTableStatus("Согласование");
assertTableOrderNum(num2);
assertTableComm(comm);
odu();
menuDelete();
window_accept();
//goTo88_02();
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Проверка ввода в поле 'Поиск' в ЭФ \"Таблица сносок\"\t")
@Link(name = "2.3.22",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.22")
@Test
public void t2_3_22() {
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
menuEditSnoski();
createSnoski();
saveButton();
searchInSnoskiField(2);
Assertions.assertEquals(3,driver.findElements(By.xpath("//tr")).size());
driver.navigate().back();
menuDelete();
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Проверка работоспособности кнопок 'Опции' в ЭФ \"Таблица сносок\"\"\t")
@Link(name = "2.3.28",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.28")
@Test
public void t2_3_28() {
createOrder();
window_accept();
String comm = stringBuilder();
enterComment(comm);
saveButton();
menuAddOdu();
addVbrCase();
saveButton();
driver.navigate().back();
//optionClick();
optionButtonsClick(12);
pageObject88_02.options_click();
Assertions.assertEquals("Опции для таблицы",
getText("//p[contains(text(),'Опции для таблицы ')]"));
pageObject88_02.options_close();
driver.navigate().refresh();
menuDelete();
window_accept();
sleep(1000);
findByCommentDelete(comm);
}
@Description("Названия тест кейса: Сценарий \"Добавить пары в приказ и перевести его в статус Согласование\"")
@Link(name = "2.3.30",url = "https://atlassian.cfmc.ru/display/CFMC/2.3.30")
@Test
public String t2_3_30() {
generalElements.createProjectClick();
window_accept();
String com = stringBuilder();
enterComment(com);
deleteYear();
enterYear2020();
generalElements.saveButton();
String num = numBuilder();
enterNumOrder(num);
generalElements.saveButton();
menuAddOdu();
addVbrCase();
generalElements.saveButton();
driver.navigate().back();
enterODUcase();
generalElements.saveButton();
statusOrderClick();
statusOrderAgreeClick();
enterDateOfOrder();
generalElements.saveButton();
return com;
}
}
| 21,416 | 0.569251 | 0.547447 | 562 | 30.989325 | 25.146755 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.740214 | false | false | 15 |
7a91be0191bfa6359c81067bc9c61159a7b1e4a9 | 39,144,331,969,019 | 42b01f5c6c5a555b1ff0be8eaa232b42e761184b | /cx2t/unittest/claw/tatsu/xcodeml/xnode/fortran/FmoduleDefinitionTest.java | c072bfcef44f93ca2aaa18b4f1b1d00848d77cbd | [
"BSD-2-Clause"
]
| permissive | claw-project/claw-compiler | https://github.com/claw-project/claw-compiler | 55a04665c168458de28180e85d7de97e89eb0cd7 | 87dde2a11b5ea7b7e30b83dec1e0e7d8b1e00fcb | refs/heads/master | 2022-12-21T23:51:59.535000 | 2021-06-30T15:06:11 | 2021-06-30T15:06:11 | 49,862,342 | 37 | 11 | BSD-2-Clause | false | 2021-08-13T22:15:02 | 2016-01-18T08:23:03 | 2021-06-30T15:06:15 | 2021-08-09T21:45:15 | 8,889 | 38 | 13 | 25 | Java | false | false | /*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package claw.tatsu.xcodeml.xnode.fortran;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import claw.tatsu.common.Context;
import claw.tatsu.xcodeml.xnode.common.Xcode;
import claw.tatsu.xcodeml.xnode.common.XcodeProgram;
import claw.tatsu.xcodeml.xnode.common.Xnode;
import helper.TestConstant;
import helper.Utils.TestContext;
import helper.XmlHelper;
/**
* Test features of the FmoduleDefinition class.
*
* @author clementval
*/
public class FmoduleDefinitionTest
{
private static final String module1 = "<FmoduleDefinition name=\"module\" "
+ "lineno=\"4\" file=\"./src/module.f90\"></FmoduleDefinition>";
@Test
public void simpleModuleDefinitionTest()
{
Context context = new TestContext();
Xnode node = XmlHelper.createXnode(module1);
FmoduleDefinition mod = new FmoduleDefinition(node);
assertNotNull(mod);
assertEquals("module", mod.getName());
assertEquals(4, mod.lineNo());
assertEquals("./src/module.f90", mod.filename());
assertNull(mod.getSymbolTable());
assertNull(mod.getDeclarationTable());
XcodeProgram xcodeml = XcodeProgram.createFromFile(TestConstant.TEST_DECLARATIONS, context);
assertNotNull(xcodeml);
List<Xnode> nodes = xcodeml.matchAll(Xcode.F_MODULE_DEFINITION);
assertFalse(nodes.isEmpty());
FmoduleDefinition modDef = new FmoduleDefinition(nodes.get(0));
assertEquals("mod1", modDef.getName());
assertFalse(modDef.getFunctionDefinition(null).isPresent());
assertFalse(modDef.getFunctionDefinition("").isPresent());
assertTrue(modDef.getFunctionDefinition("sub1").isPresent());
assertNotNull(modDef.cloneNode());
}
}
| UTF-8 | Java | 2,061 | java | FmoduleDefinitionTest.java | Java | [
{
"context": "ures of the FmoduleDefinition class.\n *\n * @author clementval\n */\npublic class FmoduleDefinitionTest\n{\n\n pri",
"end": 756,
"score": 0.9993807673454285,
"start": 746,
"tag": "USERNAME",
"value": "clementval"
}
]
| null | []
| /*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package claw.tatsu.xcodeml.xnode.fortran;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import claw.tatsu.common.Context;
import claw.tatsu.xcodeml.xnode.common.Xcode;
import claw.tatsu.xcodeml.xnode.common.XcodeProgram;
import claw.tatsu.xcodeml.xnode.common.Xnode;
import helper.TestConstant;
import helper.Utils.TestContext;
import helper.XmlHelper;
/**
* Test features of the FmoduleDefinition class.
*
* @author clementval
*/
public class FmoduleDefinitionTest
{
private static final String module1 = "<FmoduleDefinition name=\"module\" "
+ "lineno=\"4\" file=\"./src/module.f90\"></FmoduleDefinition>";
@Test
public void simpleModuleDefinitionTest()
{
Context context = new TestContext();
Xnode node = XmlHelper.createXnode(module1);
FmoduleDefinition mod = new FmoduleDefinition(node);
assertNotNull(mod);
assertEquals("module", mod.getName());
assertEquals(4, mod.lineNo());
assertEquals("./src/module.f90", mod.filename());
assertNull(mod.getSymbolTable());
assertNull(mod.getDeclarationTable());
XcodeProgram xcodeml = XcodeProgram.createFromFile(TestConstant.TEST_DECLARATIONS, context);
assertNotNull(xcodeml);
List<Xnode> nodes = xcodeml.matchAll(Xcode.F_MODULE_DEFINITION);
assertFalse(nodes.isEmpty());
FmoduleDefinition modDef = new FmoduleDefinition(nodes.get(0));
assertEquals("mod1", modDef.getName());
assertFalse(modDef.getFunctionDefinition(null).isPresent());
assertFalse(modDef.getFunctionDefinition("").isPresent());
assertTrue(modDef.getFunctionDefinition("sub1").isPresent());
assertNotNull(modDef.cloneNode());
}
}
| 2,061 | 0.715672 | 0.710335 | 61 | 32.786884 | 25.172268 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655738 | false | false | 15 |
76db452319b99db3279deceb16d7c8a89baad172 | 34,832,184,820,430 | c50a4367f4bcc6e6d29d9ce6b914f6211087ac6d | /server/data/data-api/src/main/java/org/apache/james/domainlist/api/DomainList.java | fd22361f4f03faec6298ce1c39459df0c3e28479 | [
"Apache-2.0",
"LicenseRef-scancode-unknown"
]
| permissive | linagora/james-project | https://github.com/linagora/james-project | 413a715d984a514108089d7b644eb6b4accd856a | 4ca681621b59cb8938bdc6245c307d200f9d74ae | refs/heads/master | 2017-05-04T05:48:24.029000 | 2017-04-28T10:08:43 | 2017-05-04T02:25:52 | 39,182,136 | 81 | 65 | Apache-2.0 | true | 2023-09-04T06:16:09 | 2015-07-16T07:04:59 | 2023-08-18T08:48:52 | 2023-09-04T06:16:03 | 115,214 | 66 | 63 | 52 | 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.james.domainlist.api;
import java.util.List;
/**
* This interface should be implemented by services which offer domains for
* which email will accepted.
*/
public interface DomainList {
/**
* Return array of domains which should be used as localdomains. Return null
* if no domain is found.
*
* @return domains
*/
List<String> getDomains() throws DomainListException;
/**
* Return true if the domain exists in the service
*
* @param domain
* the domain
* @return true if the given domain exists in the service
*/
boolean containsDomain(String domain) throws DomainListException;
/**
* Add domain to the service
*
* @param domain
* domain to add
* @throws DomainListException
* If the domain could not be added
*/
void addDomain(String domain) throws DomainListException;
/**
* Remove domain from the service
*
* @param domain
* domain to remove
* @throws DomainListException
* If the domain could not be removed
*/
void removeDomain(String domain) throws DomainListException;
/**
* Return the default domain which will get used to deliver mail to if only
* the localpart was given on rcpt to.
*
* @return the defaultdomain
*/
String getDefaultDomain() throws DomainListException;
}
| UTF-8 | Java | 2,651 | java | DomainList.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.james.domainlist.api;
import java.util.List;
/**
* This interface should be implemented by services which offer domains for
* which email will accepted.
*/
public interface DomainList {
/**
* Return array of domains which should be used as localdomains. Return null
* if no domain is found.
*
* @return domains
*/
List<String> getDomains() throws DomainListException;
/**
* Return true if the domain exists in the service
*
* @param domain
* the domain
* @return true if the given domain exists in the service
*/
boolean containsDomain(String domain) throws DomainListException;
/**
* Add domain to the service
*
* @param domain
* domain to add
* @throws DomainListException
* If the domain could not be added
*/
void addDomain(String domain) throws DomainListException;
/**
* Remove domain from the service
*
* @param domain
* domain to remove
* @throws DomainListException
* If the domain could not be removed
*/
void removeDomain(String domain) throws DomainListException;
/**
* Return the default domain which will get used to deliver mail to if only
* the localpart was given on rcpt to.
*
* @return the defaultdomain
*/
String getDefaultDomain() throws DomainListException;
}
| 2,651 | 0.574123 | 0.572614 | 74 | 34.824326 | 26.77754 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.162162 | false | false | 15 |
31d537e927565aeaeaea6a5a3fc6a972afd60fa0 | 37,005,438,256,064 | 2d98fad6f173b792db65e72aa6c214fa1b272102 | /app/src/main/java/com/ntrackmoto/nitolniloy/testapp/MainActivity.java | fdc9a49b47f04c7edfe17a504dca74e331c3c3d0 | []
| no_license | smondalcse/TabFragmentPermission | https://github.com/smondalcse/TabFragmentPermission | f1ae0bc0403772ca1ed2d2eb59a4ca39a75939e2 | 0229c2876557350497f791501914e64376b2c4ee | refs/heads/master | 2020-09-01T02:10:41.698000 | 2020-01-29T09:15:27 | 2020-01-29T09:15:27 | 218,853,775 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ntrackmoto.nitolniloy.testapp;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TextView mTextMessage;
private static final int CAMERA_PERMISSION_CODE = 121;
private static final int LOCATION_PERMISSION_CODE = 100;
private static final int CAMERA_REQUEST = 10;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Log.i(TAG, "navigation_home: ");
//addFragment(R.id.container, new HomeFragment(), "home");
replaceFragment(R.id.container, new HomeFragment(), "home", "home");
return true;
case R.id.navigation_dashboard:
Log.i(TAG, "navigation_dashboard: ");
replaceFragment(R.id.container, new DashboardFragment(), "dashboard", "dashboard");
return true;
case R.id.navigation_notifications:
Log.i(TAG, "navigation_notifications: ");
replaceFragment(R.id.container, new NotificationFragment(), "notification", "notification");
return true;
case R.id.navigation_map:
//mTextMessage.setText(R.string.title_map);
Intent intent = new Intent(MainActivity.this, MapActivity.class);
startActivity(intent);
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
mTextMessage = findViewById(R.id.message);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
addFragment(R.id.container, new HomeFragment(), "home");
}
protected void addFragment(@IdRes int containerViewId,
@NonNull Fragment fragment,
@NonNull String fragmentTag) {
getSupportFragmentManager()
.beginTransaction()
.add(containerViewId, fragment, fragmentTag)
.disallowAddToBackStack()
.commit();
}
protected void replaceFragment(@IdRes int containerViewId,
@NonNull Fragment fragment,
@NonNull String fragmentTag,
@Nullable String backStackStateName) {
getSupportFragmentManager()
.beginTransaction()
.replace(containerViewId, fragment, fragmentTag)
.addToBackStack(backStackStateName)
.commit();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG, "onRequestPermissionsResult: ");
if (requestCode == CAMERA_PERMISSION_CODE) {
for (Fragment frag : getSupportFragmentManager().getFragments()) {
if (frag != null) {
frag.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG, "onRequestPermissionsResult: " + frag.getTag());
}
}
} else if (requestCode == LOCATION_PERMISSION_CODE){
for (Fragment frag : getSupportFragmentManager().getFragments()) {
if (frag != null) {
frag.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG, "onRequestPermissionsResult: " + frag.getTag());
}
}
} else {
Log.i(TAG, "onRequestPermissionsResult: Not match request code");
}
}
}
| UTF-8 | Java | 4,810 | java | MainActivity.java | Java | [
{
"context": "package com.ntrackmoto.nitolniloy.testapp;\n\nimport android.app.FragmentT",
"end": 22,
"score": 0.6782864332199097,
"start": 12,
"tag": "USERNAME",
"value": "ntrackmoto"
}
]
| null | []
| package com.ntrackmoto.nitolniloy.testapp;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TextView mTextMessage;
private static final int CAMERA_PERMISSION_CODE = 121;
private static final int LOCATION_PERMISSION_CODE = 100;
private static final int CAMERA_REQUEST = 10;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Log.i(TAG, "navigation_home: ");
//addFragment(R.id.container, new HomeFragment(), "home");
replaceFragment(R.id.container, new HomeFragment(), "home", "home");
return true;
case R.id.navigation_dashboard:
Log.i(TAG, "navigation_dashboard: ");
replaceFragment(R.id.container, new DashboardFragment(), "dashboard", "dashboard");
return true;
case R.id.navigation_notifications:
Log.i(TAG, "navigation_notifications: ");
replaceFragment(R.id.container, new NotificationFragment(), "notification", "notification");
return true;
case R.id.navigation_map:
//mTextMessage.setText(R.string.title_map);
Intent intent = new Intent(MainActivity.this, MapActivity.class);
startActivity(intent);
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
mTextMessage = findViewById(R.id.message);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
addFragment(R.id.container, new HomeFragment(), "home");
}
protected void addFragment(@IdRes int containerViewId,
@NonNull Fragment fragment,
@NonNull String fragmentTag) {
getSupportFragmentManager()
.beginTransaction()
.add(containerViewId, fragment, fragmentTag)
.disallowAddToBackStack()
.commit();
}
protected void replaceFragment(@IdRes int containerViewId,
@NonNull Fragment fragment,
@NonNull String fragmentTag,
@Nullable String backStackStateName) {
getSupportFragmentManager()
.beginTransaction()
.replace(containerViewId, fragment, fragmentTag)
.addToBackStack(backStackStateName)
.commit();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG, "onRequestPermissionsResult: ");
if (requestCode == CAMERA_PERMISSION_CODE) {
for (Fragment frag : getSupportFragmentManager().getFragments()) {
if (frag != null) {
frag.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG, "onRequestPermissionsResult: " + frag.getTag());
}
}
} else if (requestCode == LOCATION_PERMISSION_CODE){
for (Fragment frag : getSupportFragmentManager().getFragments()) {
if (frag != null) {
frag.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG, "onRequestPermissionsResult: " + frag.getTag());
}
}
} else {
Log.i(TAG, "onRequestPermissionsResult: Not match request code");
}
}
}
| 4,810 | 0.617671 | 0.615593 | 115 | 40.826088 | 28.858051 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.782609 | false | false | 15 |
6a6c6ac3f647c2e6b5c20f8db0aa3ca321c032a7 | 33,767,032,936,567 | 17e8438486cb3e3073966ca2c14956d3ba9209ea | /dso/tags/2.2.0/code/base/dso-performance-tests/tests.base/com/tctest/performance/http/load/AbstractHttpLoadTest.java | 63d077de4fc8c886ab8a29d515a79168bbf76079 | []
| no_license | sirinath/Terracotta | https://github.com/sirinath/Terracotta | fedfc2c4f0f06c990f94b8b6c3b9c93293334345 | 00a7662b9cf530dfdb43f2dd821fa559e998c892 | refs/heads/master | 2021-01-23T05:41:52.414000 | 2015-07-02T15:21:54 | 2015-07-02T15:21:54 | 38,613,711 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
*/
package com.tctest.performance.http.load;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
import EDU.oswego.cs.dl.util.concurrent.ThreadFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
public abstract class AbstractHttpLoadTest {
private static final String REPORT = "report";
private static final String RESULTS_DIR = "results";
private final LinkedBlockingQueue workQ;
private final HttpLoadClient loadClient;
private final int duration;
private final String workingDir;
private final boolean printReport;
private final RequestCounter counter;
protected final TestProperties testProperties;
protected AbstractHttpLoadTest(String[] args) {
validateArgs(args);
this.printReport = (args.length == 3 && args[2].equals(REPORT));
this.workQ = new LinkedBlockingQueue(100);
this.duration = Integer.parseInt(args[0]);
this.workingDir = args[1];
this.testProperties = new TestProperties(this.workingDir);
this.counter = new RequestCounter();
this.loadClient = (printReport || duration == 0) ? null : makeInstance();
}
public HttpLoadClient makeInstance() {
HttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = connMgr.getParams();
params.setMaxTotalConnections(testProperties.getHosts().length * testProperties.getThreadCount());
params.setConnectionTimeout(30 * 10000);
params.setTcpNoDelay(true);
String[] hosts = testProperties.getHosts();
for (int i = 0; i < hosts.length; i++) {
String host = hosts[i];
HostConfiguration hostConfig = new HostConfiguration();
String[] parts = host.split(":");
hostConfig.setHost(parts[0], Integer.valueOf(parts[1]).intValue(), "http");
params.setMaxConnectionsPerHost(hostConfig, testProperties.getThreadCount());
}
connMgr.setParams(params);
PooledExecutor requestExecutor = new PooledExecutor(testProperties.getThreadCount());
requestExecutor.setThreadFactory(new LoadTestThreadFactory(connMgr));
requestExecutor.setKeepAliveTime(1000);
requestExecutor.waitWhenBlocked();
return new HttpLoadClient(workQ, requestExecutor, testProperties.getHosts(), testProperties.getSessionsCount(),
testProperties.getStickyRatio(), counter);
}
protected abstract WorkItem[] generateWarmUpWorkItems();
protected abstract WorkItem generateWorkItem(long endtime);
protected abstract WorkItem[] generateFinishWorkItems();
public void writeResults(File file) throws IOException {
loadClient.getCollector().write(new FileOutputStream(file));
}
protected void warmUp() throws InterruptedException {
WorkItem[] items = generateWarmUpWorkItems();
System.out.println("WARMING UP " + items.length + " SESSIONS");
addWorkItems(workQ, items);
counter.waitForCount(items.length);
}
protected void execute() throws Exception {
if (printReport) {
HttpResponseAnalysisReport.printReport(resultsDir(), getClass().getSimpleName(), duration);
return;
}
Thread worker = new Thread() {
public void run() {
try {
warmUp();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
String time = df.format(new Date(System.currentTimeMillis()));
System.out.println("BEGINNING TIMED LOAD: " + time);
long endTime = System.currentTimeMillis() + (duration * 1000);
while (endTime > System.currentTimeMillis()) {
WorkItem item = generateWorkItem(endTime);
workQ.put(item);
// Thread.sleep(2000);
}
System.out.println(df.format(new Date(System.currentTimeMillis())));
finished();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(0);
}
}
};
worker.setPriority(Thread.MAX_PRIORITY);
worker.start();
loadClient.execute();
File resultsDir = new File(workingDir + File.separator + RESULTS_DIR);
resultsDir.mkdir();
File resultsFile = new File(resultsDir + File.separator + HttpResponseAnalysisReport.RESULTS_FILE);
writeResults(resultsFile);
}
protected void finished() throws InterruptedException {
System.out.println("COOLING DOWN");
final WorkItem[] items = generateFinishWorkItems();
addWorkItems(workQ, items);
counter.waitForCount(items.length); // XXX: I don't think this does anything, isn't count already way past this
// value
workQ.put(new StopWorkItem());
}
protected void validateArgs(String[] args) {
if (args.length < 2) {
System.out.println("Usage:");
System.out.println(" <duration in seconds> <working dir path> [report]");
System.exit(0);
}
}
protected final File resultsDir() {
return new File(workingDir + File.separator + RESULTS_DIR);
}
protected static void addWorkItems(LinkedBlockingQueue q, WorkItem[] items) throws InterruptedException {
for (int i = 0; i < items.length; i++) {
q.put(items[i]);
}
}
private static class LoadTestThreadFactory implements ThreadFactory {
private final HttpConnectionManager connMgr;
public LoadTestThreadFactory(HttpConnectionManager connMgr) {
this.connMgr = connMgr;
}
public Thread newThread(Runnable run) {
return new LoadTestThread(run, connMgr);
}
}
static class LoadTestThread extends Thread {
private final HttpClient httpClient;
LoadTestThread(Runnable run, HttpConnectionManager connMgr) {
super(run);
httpClient = new HttpClient(connMgr);
}
HttpClient getHttpClient() {
return httpClient;
}
}
}
| UTF-8 | Java | 6,379 | java | AbstractHttpLoadTest.java | Java | []
| null | []
| /*
* All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
*/
package com.tctest.performance.http.load;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
import EDU.oswego.cs.dl.util.concurrent.ThreadFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
public abstract class AbstractHttpLoadTest {
private static final String REPORT = "report";
private static final String RESULTS_DIR = "results";
private final LinkedBlockingQueue workQ;
private final HttpLoadClient loadClient;
private final int duration;
private final String workingDir;
private final boolean printReport;
private final RequestCounter counter;
protected final TestProperties testProperties;
protected AbstractHttpLoadTest(String[] args) {
validateArgs(args);
this.printReport = (args.length == 3 && args[2].equals(REPORT));
this.workQ = new LinkedBlockingQueue(100);
this.duration = Integer.parseInt(args[0]);
this.workingDir = args[1];
this.testProperties = new TestProperties(this.workingDir);
this.counter = new RequestCounter();
this.loadClient = (printReport || duration == 0) ? null : makeInstance();
}
public HttpLoadClient makeInstance() {
HttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = connMgr.getParams();
params.setMaxTotalConnections(testProperties.getHosts().length * testProperties.getThreadCount());
params.setConnectionTimeout(30 * 10000);
params.setTcpNoDelay(true);
String[] hosts = testProperties.getHosts();
for (int i = 0; i < hosts.length; i++) {
String host = hosts[i];
HostConfiguration hostConfig = new HostConfiguration();
String[] parts = host.split(":");
hostConfig.setHost(parts[0], Integer.valueOf(parts[1]).intValue(), "http");
params.setMaxConnectionsPerHost(hostConfig, testProperties.getThreadCount());
}
connMgr.setParams(params);
PooledExecutor requestExecutor = new PooledExecutor(testProperties.getThreadCount());
requestExecutor.setThreadFactory(new LoadTestThreadFactory(connMgr));
requestExecutor.setKeepAliveTime(1000);
requestExecutor.waitWhenBlocked();
return new HttpLoadClient(workQ, requestExecutor, testProperties.getHosts(), testProperties.getSessionsCount(),
testProperties.getStickyRatio(), counter);
}
protected abstract WorkItem[] generateWarmUpWorkItems();
protected abstract WorkItem generateWorkItem(long endtime);
protected abstract WorkItem[] generateFinishWorkItems();
public void writeResults(File file) throws IOException {
loadClient.getCollector().write(new FileOutputStream(file));
}
protected void warmUp() throws InterruptedException {
WorkItem[] items = generateWarmUpWorkItems();
System.out.println("WARMING UP " + items.length + " SESSIONS");
addWorkItems(workQ, items);
counter.waitForCount(items.length);
}
protected void execute() throws Exception {
if (printReport) {
HttpResponseAnalysisReport.printReport(resultsDir(), getClass().getSimpleName(), duration);
return;
}
Thread worker = new Thread() {
public void run() {
try {
warmUp();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
String time = df.format(new Date(System.currentTimeMillis()));
System.out.println("BEGINNING TIMED LOAD: " + time);
long endTime = System.currentTimeMillis() + (duration * 1000);
while (endTime > System.currentTimeMillis()) {
WorkItem item = generateWorkItem(endTime);
workQ.put(item);
// Thread.sleep(2000);
}
System.out.println(df.format(new Date(System.currentTimeMillis())));
finished();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(0);
}
}
};
worker.setPriority(Thread.MAX_PRIORITY);
worker.start();
loadClient.execute();
File resultsDir = new File(workingDir + File.separator + RESULTS_DIR);
resultsDir.mkdir();
File resultsFile = new File(resultsDir + File.separator + HttpResponseAnalysisReport.RESULTS_FILE);
writeResults(resultsFile);
}
protected void finished() throws InterruptedException {
System.out.println("COOLING DOWN");
final WorkItem[] items = generateFinishWorkItems();
addWorkItems(workQ, items);
counter.waitForCount(items.length); // XXX: I don't think this does anything, isn't count already way past this
// value
workQ.put(new StopWorkItem());
}
protected void validateArgs(String[] args) {
if (args.length < 2) {
System.out.println("Usage:");
System.out.println(" <duration in seconds> <working dir path> [report]");
System.exit(0);
}
}
protected final File resultsDir() {
return new File(workingDir + File.separator + RESULTS_DIR);
}
protected static void addWorkItems(LinkedBlockingQueue q, WorkItem[] items) throws InterruptedException {
for (int i = 0; i < items.length; i++) {
q.put(items[i]);
}
}
private static class LoadTestThreadFactory implements ThreadFactory {
private final HttpConnectionManager connMgr;
public LoadTestThreadFactory(HttpConnectionManager connMgr) {
this.connMgr = connMgr;
}
public Thread newThread(Runnable run) {
return new LoadTestThread(run, connMgr);
}
}
static class LoadTestThread extends Thread {
private final HttpClient httpClient;
LoadTestThread(Runnable run, HttpConnectionManager connMgr) {
super(run);
httpClient = new HttpClient(connMgr);
}
HttpClient getHttpClient() {
return httpClient;
}
}
}
| 6,379 | 0.703088 | 0.696504 | 177 | 35.039547 | 29.674194 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.677966 | false | false | 15 |
294f0440b31398aad4809c5f1627a0e1d040a559 | 26,843,545,624,386 | 4c39fb566dda9f8ea5d5c9a56bdb0e689288b783 | /src/main/java/com/hujiang/project/zhgd/hjLogging/service/HjLoggingServiceImpl.java | f16b21cd6992a55d2c34e9c0767473ca0c8ec12e | [
"MIT"
]
| permissive | xieyagit/zhgd | https://github.com/xieyagit/zhgd | 5ed86dfb5a34705ba39cac774226d8c438f2dfb5 | 45ac870a62c7323a1bb40b99fb8f0c93e38aed0d | refs/heads/master | 2021-04-23T19:40:18.508000 | 2020-05-21T09:20:44 | 2020-05-21T09:20:44 | 249,984,958 | 0 | 0 | MIT | true | 2020-03-25T13:24:35 | 2020-03-25T13:24:35 | 2020-03-24T10:09:48 | 2020-03-25T12:41:02 | 61,741 | 0 | 0 | 0 | null | false | false | package com.hujiang.project.zhgd.hjLogging.service;
import java.util.List;
import java.util.Map;
import com.hujiang.project.zhgd.hjLogging.domain.HjLogging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.hujiang.project.zhgd.hjLogging.mapper.HjLoggingMapper;
import com.hujiang.common.support.Convert;
/**
* 考勤,实名制日志 服务层实现
*
* @author hujiang
* @date 2019-06-14
*/
@Service@Transactional
public class HjLoggingServiceImpl implements IHjLoggingService
{
@Autowired
private HjLoggingMapper hjLoggingMapper;
/**
* 查询考勤,实名制日志信息
*
* @param id 考勤,实名制日志ID
* @return 考勤,实名制日志信息
*/
@Override
public HjLogging selectHjLoggingById(Integer id)
{
return hjLoggingMapper.selectHjLoggingById(id);
}
public List<HjLogging> selectHjLoggingListNew(Map<String,Object> map){
return hjLoggingMapper.selectHjLoggingListNew(map);
}
/**
* 查询考勤,实名制日志列表
*
* @param hjLogging 考勤,实名制日志信息
* @return 考勤,实名制日志集合
*/
@Override
public List<HjLogging> selectHjLoggingList(HjLogging hjLogging)
{
return hjLoggingMapper.selectHjLoggingList(hjLogging);
}
/**
* 新增考勤,实名制日志
*
* @param hjLogging 考勤,实名制日志信息
* @return 结果
*/
@Override
public int insertHjLogging(HjLogging hjLogging)
{
return hjLoggingMapper.insertHjLogging(hjLogging);
}
/**
* 修改考勤,实名制日志
*
* @param hjLogging 考勤,实名制日志信息
* @return 结果
*/
@Override
public int updateHjLogging(HjLogging hjLogging)
{
return hjLoggingMapper.updateHjLogging(hjLogging);
}
/**
* 删除考勤,实名制日志对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteHjLoggingByIds(String ids)
{
return hjLoggingMapper.deleteHjLoggingByIds(Convert.toStrArray(ids));
}
}
| UTF-8 | Java | 2,279 | java | HjLoggingServiceImpl.java | Java | [
{
"context": "onvert;\r\n\r\n/**\r\n * 考勤,实名制日志 服务层实现\r\n * \r\n * @author hujiang\r\n * @date 2019-06-14\r\n */\r\n@Service@Transactional",
"end": 501,
"score": 0.999382734298706,
"start": 494,
"tag": "USERNAME",
"value": "hujiang"
}
]
| null | []
| package com.hujiang.project.zhgd.hjLogging.service;
import java.util.List;
import java.util.Map;
import com.hujiang.project.zhgd.hjLogging.domain.HjLogging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.hujiang.project.zhgd.hjLogging.mapper.HjLoggingMapper;
import com.hujiang.common.support.Convert;
/**
* 考勤,实名制日志 服务层实现
*
* @author hujiang
* @date 2019-06-14
*/
@Service@Transactional
public class HjLoggingServiceImpl implements IHjLoggingService
{
@Autowired
private HjLoggingMapper hjLoggingMapper;
/**
* 查询考勤,实名制日志信息
*
* @param id 考勤,实名制日志ID
* @return 考勤,实名制日志信息
*/
@Override
public HjLogging selectHjLoggingById(Integer id)
{
return hjLoggingMapper.selectHjLoggingById(id);
}
public List<HjLogging> selectHjLoggingListNew(Map<String,Object> map){
return hjLoggingMapper.selectHjLoggingListNew(map);
}
/**
* 查询考勤,实名制日志列表
*
* @param hjLogging 考勤,实名制日志信息
* @return 考勤,实名制日志集合
*/
@Override
public List<HjLogging> selectHjLoggingList(HjLogging hjLogging)
{
return hjLoggingMapper.selectHjLoggingList(hjLogging);
}
/**
* 新增考勤,实名制日志
*
* @param hjLogging 考勤,实名制日志信息
* @return 结果
*/
@Override
public int insertHjLogging(HjLogging hjLogging)
{
return hjLoggingMapper.insertHjLogging(hjLogging);
}
/**
* 修改考勤,实名制日志
*
* @param hjLogging 考勤,实名制日志信息
* @return 结果
*/
@Override
public int updateHjLogging(HjLogging hjLogging)
{
return hjLoggingMapper.updateHjLogging(hjLogging);
}
/**
* 删除考勤,实名制日志对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteHjLoggingByIds(String ids)
{
return hjLoggingMapper.deleteHjLoggingByIds(Convert.toStrArray(ids));
}
}
| 2,279 | 0.676838 | 0.672836 | 87 | 20.977011 | 23.07707 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62069 | false | false | 15 |
38f826bceb43848f48e422c18028f8816301e6bd | 26,843,545,624,696 | 3d3ca704656fa15008ffc0135f0dd0f1e8a31b1b | /hong_java/day16/src/inter/basic/MainClass.java | fd47c12435b49ee26a550beb33b639155ae81394 | []
| no_license | kisunssong/java | https://github.com/kisunssong/java | 1e4bb7e5da92f54beceb91c651f2769e590236a9 | 9e71b7a06112ffa6c0789590b740aebd2812b1a7 | refs/heads/master | 2023-01-19T05:35:30.519000 | 2020-11-18T08:53:08 | 2020-11-18T08:53:08 | 309,292,367 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package inter.basic;
public class MainClass {
public static void main(String[] args) {
//인터페이스는 객체를 생성할 수 없습니다.
// Inter1 i1 = new Inter1();
InterClass ic = new InterClass();
System.out.println(Inter1.INCH);
System.out.println(Inter2.ABC);
ic.method1();
ic.method2();
ic.method3();
/*
* 인터페이스 이름도 하나의 타입으로 취급할 수 있습니다.
* 인터페이스를 통해 상속 없이도 다형성을 구현할 수 있습니다.
*/
System.out.println("===============================");
Inter1 i1 = ic; //Promotion: InterClass -> Inter1
Inter2 i2 = new InterClass(); //InterClass -> Inter2
i2.method2();
// i1.method3();
// i2.method3();
//method3()은 InterClass메서드는 본인꺼이기때문에 타입변경시 사용불가
//아래에 다운캐스팅을 한후에 가능
InterClass icc = (InterClass)i1;
InterClass icc2 = (InterClass)i2;
icc.method3();
}
}
| UHC | Java | 990 | java | MainClass.java | Java | []
| null | []
| package inter.basic;
public class MainClass {
public static void main(String[] args) {
//인터페이스는 객체를 생성할 수 없습니다.
// Inter1 i1 = new Inter1();
InterClass ic = new InterClass();
System.out.println(Inter1.INCH);
System.out.println(Inter2.ABC);
ic.method1();
ic.method2();
ic.method3();
/*
* 인터페이스 이름도 하나의 타입으로 취급할 수 있습니다.
* 인터페이스를 통해 상속 없이도 다형성을 구현할 수 있습니다.
*/
System.out.println("===============================");
Inter1 i1 = ic; //Promotion: InterClass -> Inter1
Inter2 i2 = new InterClass(); //InterClass -> Inter2
i2.method2();
// i1.method3();
// i2.method3();
//method3()은 InterClass메서드는 본인꺼이기때문에 타입변경시 사용불가
//아래에 다운캐스팅을 한후에 가능
InterClass icc = (InterClass)i1;
InterClass icc2 = (InterClass)i2;
icc.method3();
}
}
| 990 | 0.610406 | 0.57868 | 36 | 20.888889 | 17.017601 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.166667 | false | false | 15 |
86d57d9bbe5d9182bd000e770f2da41b8db24d55 | 29,635,274,382,311 | 3f845730d07e3e1f847dc285905e77a132d6edcc | /src/main/java/adapter/ejercicio/Computadora.java | 8e5b59972bd6c2be16c767f37869c18d7c82ec31 | []
| no_license | AleChirinos/Todo-DP | https://github.com/AleChirinos/Todo-DP | 2d4911e2910e8f7a2418cd81004352337659c16c | c076cb66c9eb5395c8448081249585e53f892ef4 | refs/heads/main | 2023-06-08T14:19:18.364000 | 2021-07-01T06:12:10 | 2021-07-01T06:12:10 | 372,260,222 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package adapter.ejercicio;
public class Computadora implements IArtefactosElectronicosGrande{
private String marca;
private int modelo;
public Computadora(String marca, int modelo){
this.marca=marca;
this.modelo=modelo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public int getModelo() {
return modelo;
}
public void setModelo(int modelo) {
this.modelo = modelo;
}
@Override
public void precio() {
showInfo();
if(marca.equals("APPLE")){
System.out.println("Precio esta por encima de los 5000 $");
System.out.println();
}else if(marca.equals("HP")){
System.out.println("Precio esta por encima de los 4000 $ y por debajo de los 5000 $");
System.out.println();
}else if(marca.equals("LENOVO")){
System.out.println("Precio esta por encima de los 3000 $ y por debajo de los 4000 $");
System.out.println();
}else if(marca.equals("DELL")){
System.out.println("Precio esta por encima de los 2000 $ y por debajo de los 3000 $");
System.out.println();
}else {
System.out.println("Precio esta por debajo de los 2000$ ");
System.out.println();
}
}
@Override
public void tiempoDeVida() {
showInfo();
if(modelo>=10){
System.out.println("Tiempo de vida es mayor a los 10 años");
System.out.println();
}else if(modelo>=7 && modelo<10){
System.out.println("Tiempo de vida es mayor a los 7 años pero menor a los 10 años");
System.out.println();
}else if(modelo>=5 && modelo<7){
System.out.println("Tiempo de vida es mayor a los 5 años pero menor a los 7 años");
System.out.println();
}else{
System.out.println("Tiempo de vida es menor a los 5 años ");
System.out.println();
}
}
public void showInfo(){
System.out.println("Marca: "+marca);
System.out.println("Modelo: "+modelo);
}
}
| UTF-8 | Java | 2,204 | java | Computadora.java | Java | []
| null | []
| package adapter.ejercicio;
public class Computadora implements IArtefactosElectronicosGrande{
private String marca;
private int modelo;
public Computadora(String marca, int modelo){
this.marca=marca;
this.modelo=modelo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public int getModelo() {
return modelo;
}
public void setModelo(int modelo) {
this.modelo = modelo;
}
@Override
public void precio() {
showInfo();
if(marca.equals("APPLE")){
System.out.println("Precio esta por encima de los 5000 $");
System.out.println();
}else if(marca.equals("HP")){
System.out.println("Precio esta por encima de los 4000 $ y por debajo de los 5000 $");
System.out.println();
}else if(marca.equals("LENOVO")){
System.out.println("Precio esta por encima de los 3000 $ y por debajo de los 4000 $");
System.out.println();
}else if(marca.equals("DELL")){
System.out.println("Precio esta por encima de los 2000 $ y por debajo de los 3000 $");
System.out.println();
}else {
System.out.println("Precio esta por debajo de los 2000$ ");
System.out.println();
}
}
@Override
public void tiempoDeVida() {
showInfo();
if(modelo>=10){
System.out.println("Tiempo de vida es mayor a los 10 años");
System.out.println();
}else if(modelo>=7 && modelo<10){
System.out.println("Tiempo de vida es mayor a los 7 años pero menor a los 10 años");
System.out.println();
}else if(modelo>=5 && modelo<7){
System.out.println("Tiempo de vida es mayor a los 5 años pero menor a los 7 años");
System.out.println();
}else{
System.out.println("Tiempo de vida es menor a los 5 años ");
System.out.println();
}
}
public void showInfo(){
System.out.println("Marca: "+marca);
System.out.println("Modelo: "+modelo);
}
}
| 2,204 | 0.568699 | 0.547316 | 71 | 29.957747 | 26.186459 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.450704 | false | false | 15 |
6f2a32635c0fdf4496ce75f273ae42ada3b57ad1 | 6,339,371,763,996 | d8582acbef282b9ffa4b0133c349203a8e9a7f47 | /app/src/main/java/tg/abiguime/keepalong/main/todos/TaskFragment.java | 16892d11628cba70536167cb7d14ab95d26b8555 | []
| no_license | blackgerman/keep.along | https://github.com/blackgerman/keep.along | d0697eb02f3f7e0c26ac367e50da5c697d6f4f44 | 9377440e489c4bc34ace0da3b7875acba54ea5a4 | refs/heads/master | 2020-07-02T20:51:35.895000 | 2017-12-11T09:22:19 | 2017-12-11T09:22:19 | 74,282,820 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tg.abiguime.keepalong.main.todos;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import java.util.List;
import tg.abiguime.keepalong.R;
import tg.abiguime.keepalong._commons.decorators.StaggeredDivider;
import tg.abiguime.keepalong._core.AppConstant;
import tg.abiguime.keepalong._data.Task;
import tg.abiguime.keepalong._data.TaskList;
import tg.abiguime.keepalong.main.home.HomeContract;
import tg.abiguime.keepalong.main.todos.adapter.MyTaskRecyclerViewAdapter;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class TaskFragment extends Fragment implements TaskContract.View{
// TODO: Customize parameter argument names
private OnListFragmentInteractionListener mListener;
TaskPresenter presenter;
private MyTaskRecyclerViewAdapter adapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TaskFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static TaskFragment newInstance() {
TaskFragment fragment = new TaskFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
ProgressBar pb;
RecyclerView recyclerView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_list, container, false);
initViews(view);
recyclerView.setVisibility(View.INVISIBLE);
pb.setVisibility(View.VISIBLE);
pb.postDelayed(new Runnable() {
@Override
public void run() {
presenter.loadTasksFromDb();
}
}, AppConstant.LOCAL_LOADING_DELAY);
return view;
}
private void initViews(View view) {
pb = (ProgressBar) view.findViewById(R.id.loading_progressbar);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void noResult() {
// show no results
}
@Override
public void showTask(List<TaskList> data) {
// inflate the recycler view
adapter = new MyTaskRecyclerViewAdapter(data, mListener);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.addItemDecoration(new StaggeredDivider(getResources().getDrawable(R.drawable.decorator_divider)));
recyclerView.setAdapter(adapter);
pb.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
@Override
public void setPresenter(Object presenter) {
this.presenter = (TaskPresenter) presenter;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(Task item);
}
}
| UTF-8 | Java | 4,677 | java | TaskFragment.java | Java | []
| null | []
| package tg.abiguime.keepalong.main.todos;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import java.util.List;
import tg.abiguime.keepalong.R;
import tg.abiguime.keepalong._commons.decorators.StaggeredDivider;
import tg.abiguime.keepalong._core.AppConstant;
import tg.abiguime.keepalong._data.Task;
import tg.abiguime.keepalong._data.TaskList;
import tg.abiguime.keepalong.main.home.HomeContract;
import tg.abiguime.keepalong.main.todos.adapter.MyTaskRecyclerViewAdapter;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class TaskFragment extends Fragment implements TaskContract.View{
// TODO: Customize parameter argument names
private OnListFragmentInteractionListener mListener;
TaskPresenter presenter;
private MyTaskRecyclerViewAdapter adapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TaskFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static TaskFragment newInstance() {
TaskFragment fragment = new TaskFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
ProgressBar pb;
RecyclerView recyclerView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_list, container, false);
initViews(view);
recyclerView.setVisibility(View.INVISIBLE);
pb.setVisibility(View.VISIBLE);
pb.postDelayed(new Runnable() {
@Override
public void run() {
presenter.loadTasksFromDb();
}
}, AppConstant.LOCAL_LOADING_DELAY);
return view;
}
private void initViews(View view) {
pb = (ProgressBar) view.findViewById(R.id.loading_progressbar);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void noResult() {
// show no results
}
@Override
public void showTask(List<TaskList> data) {
// inflate the recycler view
adapter = new MyTaskRecyclerViewAdapter(data, mListener);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.addItemDecoration(new StaggeredDivider(getResources().getDrawable(R.drawable.decorator_divider)));
recyclerView.setAdapter(adapter);
pb.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
@Override
public void setPresenter(Object presenter) {
this.presenter = (TaskPresenter) presenter;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(Task item);
}
}
| 4,677 | 0.701304 | 0.700021 | 154 | 29.370131 | 27.540277 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.38961 | false | false | 15 |
7552ce98e875bf3b840bf099180e6f6cf1230209 | 26,568,667,733,076 | e07acb18b4017db7ecae57a0c023467aeba96de6 | /src/com/supermarket/model/StockModel.java | 3580961489a1ae8686f32306b721f3f481a9ae76 | []
| no_license | L-MXH/supermarket | https://github.com/L-MXH/supermarket | 2ca5d528bc8795a50e6fc2193e387470fb6e219f | d942b0b6a3bac744520fb63c8ccca6d2b7c812e6 | refs/heads/master | 2023-03-29T13:21:52.972000 | 2021-03-26T13:21:02 | 2021-03-26T13:21:02 | 351,788,917 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* 部门管理模板
*/
package com.supermarket.model;
public class StockModel extends javax.swing.table.DefaultTableModel {
Class[] types = new Class[] { java.lang.Object.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class };
boolean[] canEdit = new boolean[] { false, false, false };
public StockModel() {
super(new Object[][] {}, new String[] { "编号", "订单号", "货品名称", "交货日期",
"进货商", "数量", "金额" });
}
public Class getColumnClass(int columIndex) {
return types[columIndex];
}
public boolean isCellEditable(int rowIndex, int columIndex) {
return canEdit[columIndex];
}
}
| GB18030 | Java | 773 | java | StockModel.java | Java | []
| null | []
| /**
* 部门管理模板
*/
package com.supermarket.model;
public class StockModel extends javax.swing.table.DefaultTableModel {
Class[] types = new Class[] { java.lang.Object.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class,
java.lang.String.class };
boolean[] canEdit = new boolean[] { false, false, false };
public StockModel() {
super(new Object[][] {}, new String[] { "编号", "订单号", "货品名称", "交货日期",
"进货商", "数量", "金额" });
}
public Class getColumnClass(int columIndex) {
return types[columIndex];
}
public boolean isCellEditable(int rowIndex, int columIndex) {
return canEdit[columIndex];
}
}
| 773 | 0.683773 | 0.683773 | 28 | 24.75 | 24.52495 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.892857 | false | false | 15 |
fbf7efda320657a3b7077f9979b9dcf473bb8faf | 32,229,434,627,004 | 299457e71b4a6d82cbd97a7150c6eccbe255745c | /leetcode-solution/code/Closest_Binary_Search_Tree_Value.java | ff3479e3c88641ca627b38e29dcc384337ec100f | []
| no_license | david-grey/leetcode-github | https://github.com/david-grey/leetcode-github | 7ada100473d0c849d44b3602567421b1c1d89455 | c8758fff080fb4fb62d797a2f37750b986faf723 | refs/heads/master | 2020-12-03T00:32:06.873000 | 2017-12-03T23:36:33 | 2017-12-03T23:36:33 | 96,041,276 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
int close = 0;
if(root == null){
return -1;
}
if (target < root.val){
close = closestValue(root.left, target);
}
else{
close = closestValue(root.right, target);
}
if(close == -1){
return root.val;
}
double closeDiff = Math.abs(close - target);
double rootDiff = Math.abs(root.val - target);
if(closeDiff > rootDiff){
return root.val;
}
else {
return close;
}
}
} | UTF-8 | Java | 851 | java | Closest_Binary_Search_Tree_Value.java | Java | []
| null | []
| /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
int close = 0;
if(root == null){
return -1;
}
if (target < root.val){
close = closestValue(root.left, target);
}
else{
close = closestValue(root.right, target);
}
if(close == -1){
return root.val;
}
double closeDiff = Math.abs(close - target);
double rootDiff = Math.abs(root.val - target);
if(closeDiff > rootDiff){
return root.val;
}
else {
return close;
}
}
} | 851 | 0.47121 | 0.467685 | 34 | 23.088236 | 16.094149 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 15 |
7858423a58d4b756a11468bfc2d526397dcef4d8 | 32,229,434,624,602 | 2bda835528acfc88631b13170e0c867a8784bdf8 | /Clothes/src/clothes/model/ShoeType.java | 1c89fd3a1e4fedf6fe71ece9a0235f5033184778 | []
| no_license | lehel91/mezei_lehel_homework_projects | https://github.com/lehel91/mezei_lehel_homework_projects | 2ad0d57f30c90aece44c44512c4b65ff842c6c4e | 0a5f3373ddf93c4f98b2a8a5109c2e269d32930b | refs/heads/master | 2020-05-07T19:06:33.949000 | 2019-04-11T14:40:09 | 2019-04-11T14:40:09 | 180,797,452 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clothes.model;
public enum ShoeType {
URBAN {
@Override
public String toString() {
return "Urban shoes";
}
},
HIKING {
@Override
public String toString() {
return "Hiking shoes";
}
},
SPORT {
@Override
public String toString() {
return "Sport shoes";
}
};
}
| UTF-8 | Java | 399 | java | ShoeType.java | Java | []
| null | []
| package clothes.model;
public enum ShoeType {
URBAN {
@Override
public String toString() {
return "Urban shoes";
}
},
HIKING {
@Override
public String toString() {
return "Hiking shoes";
}
},
SPORT {
@Override
public String toString() {
return "Sport shoes";
}
};
}
| 399 | 0.466165 | 0.466165 | 22 | 17.136364 | 11.510056 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 15 |
6d341a3709af20b24ab9024ce1bead623d7e4a59 | 22,359,599,773,061 | 8478f3087fb989fbc8bd66fb97dcfd880254adaa | /core/src/main/java/com/predic8/membrane/core/interceptor/apimanagement/quota/AMQuota.java | 55e906e6685f42caa2c5f02b2a799b63d2c532ec | [
"Apache-2.0"
]
| permissive | membrane/service-proxy | https://github.com/membrane/service-proxy | e3596dab7b911e156785036ca6d8aeab6beec2e2 | b8b38cc8466e3c7da2d9ec369c0ff237496244ac | refs/heads/master | 2023-08-30T16:32:53.454000 | 2023-08-30T14:27:19 | 2023-08-30T14:27:19 | 6,332,635 | 415 | 159 | Apache-2.0 | false | 2023-09-14T06:15:25 | 2012-10-22T09:39:24 | 2023-09-13T03:10:53 | 2023-09-14T06:15:24 | 46,705 | 418 | 133 | 37 | Java | false | false | /*
* Copyright 2015 predic8 GmbH, www.predic8.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.predic8.membrane.core.interceptor.apimanagement.quota;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.predic8.membrane.annot.MCElement;
import com.predic8.membrane.core.exchange.Exchange;
import com.predic8.membrane.core.http.*;
import com.predic8.membrane.core.interceptor.Outcome;
import com.predic8.membrane.core.interceptor.apimanagement.ApiManagementConfiguration;
import com.predic8.membrane.core.interceptor.apimanagement.Key;
import com.predic8.membrane.core.interceptor.apimanagement.policy.Policy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import static com.predic8.membrane.core.http.MimeType.*;
/**
* Unfinished
*/
@MCElement(name = "amQuota")
public class AMQuota {
private static final Logger log = LoggerFactory.getLogger(AMQuota.class);
private ApiManagementConfiguration amc;
public ConcurrentHashMap<String, ApiKeyByteCounter> keyByteCounter = new ConcurrentHashMap<>();
public ConcurrentHashMap<String, PolicyQuota> policyQuotas = new ConcurrentHashMap<>();
public ApiManagementConfiguration getAmc() {
return amc;
}
private final Runnable observer = () -> {
log.info("Getting new config");
fillPolicyQuotas();
keyByteCounter = new ConcurrentHashMap<>();
};
public void setAmc(ApiManagementConfiguration amc) {
if (this.amc != null) {
this.amc.configChangeObservers.remove(observer);
}
this.amc = amc;
fillPolicyQuotas();
amc.configChangeObservers.add(observer);
}
private void fillPolicyQuotas() {
policyQuotas.clear();
for (Policy policy : amc.getPolicies().values()) {
String name = policy.getName();
long quotaSize = policy.getQuota().getSize();
int interval = policy.getQuota().getInterval();
HashSet<String> services = new HashSet<>(policy.getServiceProxies());
PolicyQuota pq = new PolicyQuota();
pq.setName(name);
pq.setSize(quotaSize);
pq.setInterval(Duration.standardSeconds(interval));
pq.incrementNextCleanup();
pq.setServices(services);
policyQuotas.put(name, pq);
}
}
public Outcome handleRequest(Exchange exc) {
return handle(exc, exc.getRequest());
}
public Outcome handleResponse(Exchange exc) {
return handle(exc, exc.getResponse());
}
private Outcome handle(Exchange exc, Message msg) {
Object apiKeyObj = exc.getProperty(Exchange.API_KEY);
if (apiKeyObj == null) {
log.warn("No api key set in exchange");
return Outcome.RETURN;
}
String apiKey = (String) apiKeyObj;
String requestedService = exc.getRule().getName();
QuotaReachedAnswer answer = isQuotaReached(msg, requestedService, apiKey);
if (msg instanceof Request) { // lets responses over the limit always through
if (answer.isQuotaReached()) {
setResponseToServiceUnavailable(exc, answer.getPq());
return Outcome.RETURN;
}
}
return Outcome.CONTINUE;
}
private void setResponseToServiceUnavailable(Exchange exc, PolicyQuota pq) {
//TODO do a better response here
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
try (JsonGenerator jgen = new JsonFactory().createGenerator(os)) {
jgen.writeStartObject();
jgen.writeObjectField("Statuscode", 429);
jgen.writeObjectField("Message", "Quota Exceeded");
jgen.writeEndObject();
}
Header hd = new Header();
Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType(APPLICATION_JSON).body(os.toByteArray()).build();
exc.setResponse(resp);
} catch (IOException ignored) {
}
}
private QuotaReachedAnswer isQuotaReached(Message msg, String requestedService, String apiKey) {
doCleanup();
long size = msg.getHeader().toString().getBytes().length + msg.getHeader().getContentLength();
addRequestEntry(apiKey, size);
ApiKeyByteCounter info = keyByteCounter.get(apiKey);
boolean resultTemp = false;
PolicyQuota pqTemp = null;
synchronized (info) {
for (String policy : info.getPolicyByteCounters().keySet()) {
PolicyQuota pq = policyQuotas.get(policy);
if (!pq.getServices().contains(requestedService)) {
// the service is not in this policy
//System.out.println("service not found in " + policy);
continue;
}
if (info.getPolicyByteCounters().get(policy).get() > pq.getSize()) {
resultTemp = true;
pqTemp = pq;
//System.out.println("limit reached for " + policy);
continue;
}
// if atleast one policy has available quota, then let it through
resultTemp = false;
//System.out.println("limit not reached for " + policy);
break;
}
}
if (resultTemp) {
return QuotaReachedAnswer.createQuotaReached(pqTemp);
} else {
return QuotaReachedAnswer.createQuotaNotReached();
}
}
private void addRequestEntry(String apiKey, long sizeOfBytes) {
synchronized (keyByteCounter) {
if (!keyByteCounter.containsKey(apiKey)) {
ApiKeyByteCounter value = new ApiKeyByteCounter();
Key key = amc.getKeys().get(apiKey);
for (Policy p : key.getPolicies()) {
value.getPolicyByteCounters().put(p.getName(), new AtomicLong());
}
keyByteCounter.put(apiKey, value);
}
}
ApiKeyByteCounter keyInfo = keyByteCounter.get(apiKey);
for (AtomicLong counter : keyInfo.getPolicyByteCounters().values()) {
counter.addAndGet(sizeOfBytes);
}
}
private void doCleanup() {
synchronized (policyQuotas) {
for (PolicyQuota pq : policyQuotas.values()) {
if (DateTime.now().isAfter(pq.getNextCleanup())) {
for (ApiKeyByteCounter keyInfo : keyByteCounter.values()) {
if (keyInfo.getPolicyByteCounters().containsKey(pq.getName())) {
keyInfo.getPolicyByteCounters().get(pq.getName()).set(0);
}
}
pq.incrementNextCleanup();
}
}
}
}
}
| UTF-8 | Java | 7,824 | java | AMQuota.java | Java | []
| null | []
| /*
* Copyright 2015 predic8 GmbH, www.predic8.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.predic8.membrane.core.interceptor.apimanagement.quota;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.predic8.membrane.annot.MCElement;
import com.predic8.membrane.core.exchange.Exchange;
import com.predic8.membrane.core.http.*;
import com.predic8.membrane.core.interceptor.Outcome;
import com.predic8.membrane.core.interceptor.apimanagement.ApiManagementConfiguration;
import com.predic8.membrane.core.interceptor.apimanagement.Key;
import com.predic8.membrane.core.interceptor.apimanagement.policy.Policy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import static com.predic8.membrane.core.http.MimeType.*;
/**
* Unfinished
*/
@MCElement(name = "amQuota")
public class AMQuota {
private static final Logger log = LoggerFactory.getLogger(AMQuota.class);
private ApiManagementConfiguration amc;
public ConcurrentHashMap<String, ApiKeyByteCounter> keyByteCounter = new ConcurrentHashMap<>();
public ConcurrentHashMap<String, PolicyQuota> policyQuotas = new ConcurrentHashMap<>();
public ApiManagementConfiguration getAmc() {
return amc;
}
private final Runnable observer = () -> {
log.info("Getting new config");
fillPolicyQuotas();
keyByteCounter = new ConcurrentHashMap<>();
};
public void setAmc(ApiManagementConfiguration amc) {
if (this.amc != null) {
this.amc.configChangeObservers.remove(observer);
}
this.amc = amc;
fillPolicyQuotas();
amc.configChangeObservers.add(observer);
}
private void fillPolicyQuotas() {
policyQuotas.clear();
for (Policy policy : amc.getPolicies().values()) {
String name = policy.getName();
long quotaSize = policy.getQuota().getSize();
int interval = policy.getQuota().getInterval();
HashSet<String> services = new HashSet<>(policy.getServiceProxies());
PolicyQuota pq = new PolicyQuota();
pq.setName(name);
pq.setSize(quotaSize);
pq.setInterval(Duration.standardSeconds(interval));
pq.incrementNextCleanup();
pq.setServices(services);
policyQuotas.put(name, pq);
}
}
public Outcome handleRequest(Exchange exc) {
return handle(exc, exc.getRequest());
}
public Outcome handleResponse(Exchange exc) {
return handle(exc, exc.getResponse());
}
private Outcome handle(Exchange exc, Message msg) {
Object apiKeyObj = exc.getProperty(Exchange.API_KEY);
if (apiKeyObj == null) {
log.warn("No api key set in exchange");
return Outcome.RETURN;
}
String apiKey = (String) apiKeyObj;
String requestedService = exc.getRule().getName();
QuotaReachedAnswer answer = isQuotaReached(msg, requestedService, apiKey);
if (msg instanceof Request) { // lets responses over the limit always through
if (answer.isQuotaReached()) {
setResponseToServiceUnavailable(exc, answer.getPq());
return Outcome.RETURN;
}
}
return Outcome.CONTINUE;
}
private void setResponseToServiceUnavailable(Exchange exc, PolicyQuota pq) {
//TODO do a better response here
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
try (JsonGenerator jgen = new JsonFactory().createGenerator(os)) {
jgen.writeStartObject();
jgen.writeObjectField("Statuscode", 429);
jgen.writeObjectField("Message", "Quota Exceeded");
jgen.writeEndObject();
}
Header hd = new Header();
Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType(APPLICATION_JSON).body(os.toByteArray()).build();
exc.setResponse(resp);
} catch (IOException ignored) {
}
}
private QuotaReachedAnswer isQuotaReached(Message msg, String requestedService, String apiKey) {
doCleanup();
long size = msg.getHeader().toString().getBytes().length + msg.getHeader().getContentLength();
addRequestEntry(apiKey, size);
ApiKeyByteCounter info = keyByteCounter.get(apiKey);
boolean resultTemp = false;
PolicyQuota pqTemp = null;
synchronized (info) {
for (String policy : info.getPolicyByteCounters().keySet()) {
PolicyQuota pq = policyQuotas.get(policy);
if (!pq.getServices().contains(requestedService)) {
// the service is not in this policy
//System.out.println("service not found in " + policy);
continue;
}
if (info.getPolicyByteCounters().get(policy).get() > pq.getSize()) {
resultTemp = true;
pqTemp = pq;
//System.out.println("limit reached for " + policy);
continue;
}
// if atleast one policy has available quota, then let it through
resultTemp = false;
//System.out.println("limit not reached for " + policy);
break;
}
}
if (resultTemp) {
return QuotaReachedAnswer.createQuotaReached(pqTemp);
} else {
return QuotaReachedAnswer.createQuotaNotReached();
}
}
private void addRequestEntry(String apiKey, long sizeOfBytes) {
synchronized (keyByteCounter) {
if (!keyByteCounter.containsKey(apiKey)) {
ApiKeyByteCounter value = new ApiKeyByteCounter();
Key key = amc.getKeys().get(apiKey);
for (Policy p : key.getPolicies()) {
value.getPolicyByteCounters().put(p.getName(), new AtomicLong());
}
keyByteCounter.put(apiKey, value);
}
}
ApiKeyByteCounter keyInfo = keyByteCounter.get(apiKey);
for (AtomicLong counter : keyInfo.getPolicyByteCounters().values()) {
counter.addAndGet(sizeOfBytes);
}
}
private void doCleanup() {
synchronized (policyQuotas) {
for (PolicyQuota pq : policyQuotas.values()) {
if (DateTime.now().isAfter(pq.getNextCleanup())) {
for (ApiKeyByteCounter keyInfo : keyByteCounter.values()) {
if (keyInfo.getPolicyByteCounters().containsKey(pq.getName())) {
keyInfo.getPolicyByteCounters().get(pq.getName()).set(0);
}
}
pq.incrementNextCleanup();
}
}
}
}
}
| 7,824 | 0.625128 | 0.621549 | 199 | 38.316582 | 28.354456 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.58794 | false | false | 15 |
89411f6721540386ade17c4ad6c184bcc762d08c | 22,136,261,474,336 | 83025683ad438278a83c8b8b591bd061c79aa8bb | /app/src/main/java/com/kenji1947/rssreader/di/presenter/SettingsPresenterComponent.java | fa2e0043e3434985a461009065a3aa5864832f74 | []
| no_license | kenji47/RssReader | https://github.com/kenji47/RssReader | 7daa47b4e6d8782fdbcde21dc6844db98dc6249d | 0f774072b71db6cf44247f2c6f8665cc26befa76 | refs/heads/master | 2021-12-10T07:24:29.551000 | 2021-09-16T04:41:49 | 2021-09-16T04:41:49 | 126,796,084 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kenji1947.rssreader.di.presenter;
import com.kenji1947.rssreader.di.application.AppComponent;
import com.kenji1947.rssreader.presentation.settings.SettingsPresenter;
import dagger.Component;
/**
* Created by chamber on 27.12.2017.
*/
@PresenterScope
@Component(dependencies = AppComponent.class)
public interface SettingsPresenterComponent {
SettingsPresenter provideSettingsPresenter();
final class Initializer {
public static SettingsPresenterComponent init(AppComponent appComponent) {
return DaggerSettingsPresenterComponent.builder()
.appComponent(appComponent)
.build();
}
private Initializer() {
}
}
}
| UTF-8 | Java | 725 | java | SettingsPresenterComponent.java | Java | [
{
"context": "package com.kenji1947.rssreader.di.presenter;\n\nimport com.kenji1947.rss",
"end": 21,
"score": 0.8321276307106018,
"start": 12,
"tag": "USERNAME",
"value": "kenji1947"
},
{
"context": "com.kenji1947.rssreader.di.presenter;\n\nimport com.kenji1947.rssreader.di.application.AppComponent;\nimport com",
"end": 67,
"score": 0.94240802526474,
"start": 58,
"tag": "USERNAME",
"value": "kenji1947"
},
{
"context": "rssreader.di.application.AppComponent;\nimport com.kenji1947.rssreader.presentation.settings.SettingsPresenter",
"end": 127,
"score": 0.9571345448493958,
"start": 118,
"tag": "USERNAME",
"value": "kenji1947"
},
{
"context": "nter;\n\nimport dagger.Component;\n\n/**\n * Created by chamber on 27.12.2017.\n */\n@PresenterScope\n@Component(dep",
"end": 231,
"score": 0.9993749260902405,
"start": 224,
"tag": "USERNAME",
"value": "chamber"
}
]
| null | []
| package com.kenji1947.rssreader.di.presenter;
import com.kenji1947.rssreader.di.application.AppComponent;
import com.kenji1947.rssreader.presentation.settings.SettingsPresenter;
import dagger.Component;
/**
* Created by chamber on 27.12.2017.
*/
@PresenterScope
@Component(dependencies = AppComponent.class)
public interface SettingsPresenterComponent {
SettingsPresenter provideSettingsPresenter();
final class Initializer {
public static SettingsPresenterComponent init(AppComponent appComponent) {
return DaggerSettingsPresenterComponent.builder()
.appComponent(appComponent)
.build();
}
private Initializer() {
}
}
}
| 725 | 0.710345 | 0.682759 | 27 | 25.851852 | 24.760637 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 15 |
bc318764ed4f8786635c9c61bf31ffb26e8ccf83 | 29,094,108,515,857 | a8c5b7b04eace88b19b5a41a45f1fb030df393e3 | /projects/analytics/src/main/java/com/opengamma/analytics/financial/model/option/pricing/analytic/HullWhiteStochasticVolatilityModel.java | bddd131780aa1994e55cc72092978789830e2989 | [
"Apache-2.0"
]
| permissive | McLeodMoores/starling | https://github.com/McLeodMoores/starling | 3f6cfe89cacfd4332bad4861f6c5d4648046519c | 7ae0689e06704f78fd9497f8ddb57ee82974a9c8 | refs/heads/master | 2022-12-04T14:02:00.480000 | 2020-04-28T17:22:44 | 2020-04-28T17:22:44 | 46,577,620 | 4 | 4 | Apache-2.0 | false | 2022-11-24T07:26:39 | 2015-11-20T17:48:10 | 2022-11-15T07:46:39 | 2022-11-24T07:26:38 | 299,457 | 3 | 4 | 45 | Java | false | false | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.option.pricing.analytic;
import org.apache.commons.lang.Validate;
import org.threeten.bp.ZonedDateTime;
import com.opengamma.analytics.financial.model.option.definition.EuropeanVanillaOptionDefinition;
import com.opengamma.analytics.financial.model.option.definition.HullWhiteStochasticVolatilityModelDataBundle;
import com.opengamma.analytics.financial.model.option.definition.OptionDefinition;
import com.opengamma.analytics.financial.model.option.definition.StandardOptionDataBundle;
import com.opengamma.analytics.financial.model.volatility.surface.VolatilitySurface;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.statistics.distribution.NormalDistribution;
import com.opengamma.analytics.math.statistics.distribution.ProbabilityDistribution;
import com.opengamma.analytics.math.surface.ConstantDoublesSurface;
import com.opengamma.util.CompareUtils;
/**
*
*
*/
public class HullWhiteStochasticVolatilityModel extends AnalyticOptionModel<OptionDefinition, HullWhiteStochasticVolatilityModelDataBundle> {
private static final ProbabilityDistribution<Double> NORMAL = new NormalDistribution(0, 1);
private static final BlackScholesMertonModel BSM = new BlackScholesMertonModel();
private static final double ZERO = 1e-4;
@Override
public Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double> getPricingFunction(final OptionDefinition definition) {
Validate.notNull(definition);
final Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double> pricingFunction =
new Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double>() {
@SuppressWarnings("synthetic-access")
@Override
public Double evaluate(final HullWhiteStochasticVolatilityModelDataBundle data) {
Validate.notNull(data);
final ZonedDateTime date = data.getDate();
final double s = data.getSpot();
final double k = definition.getStrike();
final double t = definition.getTimeToExpiry(date);
final double sigma = data.getVolatility(t, k);
final double r = data.getInterestRate(t);
final double b = data.getCostOfCarry();
final double lambda = data.getHalfLife();
final double sigmaLR = data.getLongRunVolatility();
final double volOfSigma = data.getVolatilityOfVolatility();
final double rho = data.getCorrelation();
final StandardOptionDataBundle bsmData = new StandardOptionDataBundle(data);
final OptionDefinition call = definition.isCall() ? definition : new EuropeanVanillaOptionDefinition(k, definition.getExpiry(), true);
final double beta = -Math.log(2) / lambda;
final double alpha = -beta * sigmaLR * sigmaLR;
final double delta = beta * t;
final double eDelta = Math.exp(delta);
final boolean betaIsZero = CompareUtils.closeEquals(beta, 0, ZERO);
final double variance = sigma * sigma;
final double meanVariance = getMeanVariance(betaIsZero, variance, alpha, t, beta, eDelta, delta);
final double df = getDF(r, b, t);
final double sDf = s * df;
final double d1 = getD(s, k, b, meanVariance, t);
final double d2 = d1 - Math.sqrt(meanVariance * t);
final double nD1 = NORMAL.getPDF(d1);
final double f0 = BSM.getPricingFunction(call)
.evaluate(bsmData.withVolatilitySurface(new VolatilitySurface(ConstantDoublesSurface.from(Math.sqrt(meanVariance)))));
final double f1 = getF1(betaIsZero, variance, rho, alpha, t, beta, delta, eDelta, sDf, nD1, d2, meanVariance);
final double f2 = getF2(betaIsZero, variance, rho, alpha, t, beta, delta, eDelta, sDf, nD1, d1, d2, meanVariance);
final double callPrice = f0 + f1 * volOfSigma + f2 * volOfSigma * volOfSigma;
if (!definition.isCall()) {
return callPrice - s * df + k * Math.exp(-r * t);
}
return callPrice;
}
};
return pricingFunction;
}
double getMeanVariance(final boolean betaIsZero, final double variance, final double alpha, final double t, final double beta, final double eDelta,
final double delta) {
if (betaIsZero) {
return variance + alpha * t / 2.;
}
final double ratio = alpha / beta;
return (variance + ratio) * (eDelta - 1) / delta - ratio;
}
private double getPhi1(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta,
final double beta4, final double eDelta,
final double delta) {
if (betaIsZero) {
return rho * rho * (variance + alpha * t / 4.) * t * t * t / 6.;
}
return rho * rho * ((alpha + beta * variance) * (eDelta * (delta * delta / 2. - delta + 1) - 1) + alpha * (eDelta * (2 - delta) - 2 - delta)) / beta4;
}
private double getPhi2(final boolean betaIsZero, final double phi1, final double variance, final double rho, final double alpha, final double beta,
final double beta4, final double eDelta,
final double delta) {
if (betaIsZero) {
return phi1 * (2 + 1. / (rho * rho));
}
final double eDeltaSq = eDelta * eDelta;
return 2 * phi1 + ((alpha + beta * variance) * (eDeltaSq - 2 * delta * eDelta - 1) - alpha * (eDeltaSq - 4 * eDelta + 2 * delta + 3) / 2.) / (2 * beta4);
}
private double getPhi3(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta,
final double beta4, final double eDelta,
final double delta) {
if (betaIsZero) {
return rho * rho * Math.pow(variance + alpha * t / 3., 2) * t * t * t * t / 8.;
}
final double x = (alpha + beta * variance) * (eDelta - delta * eDelta - 1) - alpha * (1 + delta - eDelta);
return rho * rho * x * x / (2 * beta * beta * beta4);
}
private double getPhi4(final double phi3) {
return 2 * phi3;
}
double getD(final double s, final double k, final double b, final double meanVariance, final double t) {
return (Math.log(s / k) + t * (b + meanVariance / 2)) / Math.sqrt(meanVariance * t);
}
private double getCSV(final double sDf, final double nD1, final double d2, final double meanVariance) {
return -sDf * nD1 * d2 / (2 * meanVariance);
}
private double getCVV(final double sDf, final double sqrtT, final double nD1, final double d1, final double d2, final double meanVariance) {
return sDf * sqrtT * nD1 * (d1 * d2 - 1) / (4 * Math.pow(meanVariance, 1.5));
}
private double getCSVV(final double sDf, final double nD1, final double d1, final double d2, final double meanVariance) {
return sDf * nD1 * (-d1 * d2 * d2 + d1 + 2 * d2) / (4 * meanVariance * meanVariance);
}
private double getCVVV(final double sDf, final double sqrtT, final double nD1, final double d1, final double d2, final double meanVariance) {
return sDf * sqrtT * nD1 * ((d1 * d2 - 1) * (d1 * d2 - 3) - d1 * d1 - d2 * d2) / (8 * Math.pow(meanVariance, 2.5));
}
double getF1(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta, final double delta,
final double eDelta, final double sDf,
final double nD1, final double d2, final double meanVariance) {
final double cSV = getCSV(sDf, nD1, d2, meanVariance);
if (betaIsZero) {
return rho * (variance + alpha * t / 3.) * t * cSV / 2.;
}
return rho * cSV * ((alpha + beta * variance) * (1 - eDelta + delta * eDelta) + alpha * (1 + delta - eDelta)) / (beta * beta * beta * t);
}
double getF2(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta, final double delta,
final double eDelta, final double sDf,
final double nD1, final double d1, final double d2, final double meanVariance) {
final double beta4 = beta * beta * beta * beta;
final double phi1 = getPhi1(betaIsZero, variance, rho, alpha, t, beta, beta4, eDelta, delta);
final double phi2 = getPhi2(betaIsZero, phi1, variance, rho, alpha, beta, beta4, eDelta, delta);
final double phi3 = getPhi3(betaIsZero, variance, rho, alpha, t, beta, beta4, eDelta, delta);
final double phi4 = getPhi4(phi3);
final double sqrtT = Math.sqrt(t);
final double cSV = getCSV(sDf, nD1, d2, meanVariance);
final double cVV = getCVV(sDf, sqrtT, nD1, d1, d2, meanVariance);
final double cSVV = getCSVV(sDf, nD1, d1, d2, meanVariance);
final double cVVV = getCVVV(sDf, sqrtT, nD1, d1, d2, meanVariance);
final double tInv = 1 / t;
return tInv * (phi1 * cSV + tInv * (phi2 * cVV + phi3 * cSVV + tInv * phi4 * cVVV));
}
}
| UTF-8 | Java | 8,844 | java | HullWhiteStochasticVolatilityModel.java | Java | []
| null | []
| /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.option.pricing.analytic;
import org.apache.commons.lang.Validate;
import org.threeten.bp.ZonedDateTime;
import com.opengamma.analytics.financial.model.option.definition.EuropeanVanillaOptionDefinition;
import com.opengamma.analytics.financial.model.option.definition.HullWhiteStochasticVolatilityModelDataBundle;
import com.opengamma.analytics.financial.model.option.definition.OptionDefinition;
import com.opengamma.analytics.financial.model.option.definition.StandardOptionDataBundle;
import com.opengamma.analytics.financial.model.volatility.surface.VolatilitySurface;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.statistics.distribution.NormalDistribution;
import com.opengamma.analytics.math.statistics.distribution.ProbabilityDistribution;
import com.opengamma.analytics.math.surface.ConstantDoublesSurface;
import com.opengamma.util.CompareUtils;
/**
*
*
*/
public class HullWhiteStochasticVolatilityModel extends AnalyticOptionModel<OptionDefinition, HullWhiteStochasticVolatilityModelDataBundle> {
private static final ProbabilityDistribution<Double> NORMAL = new NormalDistribution(0, 1);
private static final BlackScholesMertonModel BSM = new BlackScholesMertonModel();
private static final double ZERO = 1e-4;
@Override
public Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double> getPricingFunction(final OptionDefinition definition) {
Validate.notNull(definition);
final Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double> pricingFunction =
new Function1D<HullWhiteStochasticVolatilityModelDataBundle, Double>() {
@SuppressWarnings("synthetic-access")
@Override
public Double evaluate(final HullWhiteStochasticVolatilityModelDataBundle data) {
Validate.notNull(data);
final ZonedDateTime date = data.getDate();
final double s = data.getSpot();
final double k = definition.getStrike();
final double t = definition.getTimeToExpiry(date);
final double sigma = data.getVolatility(t, k);
final double r = data.getInterestRate(t);
final double b = data.getCostOfCarry();
final double lambda = data.getHalfLife();
final double sigmaLR = data.getLongRunVolatility();
final double volOfSigma = data.getVolatilityOfVolatility();
final double rho = data.getCorrelation();
final StandardOptionDataBundle bsmData = new StandardOptionDataBundle(data);
final OptionDefinition call = definition.isCall() ? definition : new EuropeanVanillaOptionDefinition(k, definition.getExpiry(), true);
final double beta = -Math.log(2) / lambda;
final double alpha = -beta * sigmaLR * sigmaLR;
final double delta = beta * t;
final double eDelta = Math.exp(delta);
final boolean betaIsZero = CompareUtils.closeEquals(beta, 0, ZERO);
final double variance = sigma * sigma;
final double meanVariance = getMeanVariance(betaIsZero, variance, alpha, t, beta, eDelta, delta);
final double df = getDF(r, b, t);
final double sDf = s * df;
final double d1 = getD(s, k, b, meanVariance, t);
final double d2 = d1 - Math.sqrt(meanVariance * t);
final double nD1 = NORMAL.getPDF(d1);
final double f0 = BSM.getPricingFunction(call)
.evaluate(bsmData.withVolatilitySurface(new VolatilitySurface(ConstantDoublesSurface.from(Math.sqrt(meanVariance)))));
final double f1 = getF1(betaIsZero, variance, rho, alpha, t, beta, delta, eDelta, sDf, nD1, d2, meanVariance);
final double f2 = getF2(betaIsZero, variance, rho, alpha, t, beta, delta, eDelta, sDf, nD1, d1, d2, meanVariance);
final double callPrice = f0 + f1 * volOfSigma + f2 * volOfSigma * volOfSigma;
if (!definition.isCall()) {
return callPrice - s * df + k * Math.exp(-r * t);
}
return callPrice;
}
};
return pricingFunction;
}
double getMeanVariance(final boolean betaIsZero, final double variance, final double alpha, final double t, final double beta, final double eDelta,
final double delta) {
if (betaIsZero) {
return variance + alpha * t / 2.;
}
final double ratio = alpha / beta;
return (variance + ratio) * (eDelta - 1) / delta - ratio;
}
private double getPhi1(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta,
final double beta4, final double eDelta,
final double delta) {
if (betaIsZero) {
return rho * rho * (variance + alpha * t / 4.) * t * t * t / 6.;
}
return rho * rho * ((alpha + beta * variance) * (eDelta * (delta * delta / 2. - delta + 1) - 1) + alpha * (eDelta * (2 - delta) - 2 - delta)) / beta4;
}
private double getPhi2(final boolean betaIsZero, final double phi1, final double variance, final double rho, final double alpha, final double beta,
final double beta4, final double eDelta,
final double delta) {
if (betaIsZero) {
return phi1 * (2 + 1. / (rho * rho));
}
final double eDeltaSq = eDelta * eDelta;
return 2 * phi1 + ((alpha + beta * variance) * (eDeltaSq - 2 * delta * eDelta - 1) - alpha * (eDeltaSq - 4 * eDelta + 2 * delta + 3) / 2.) / (2 * beta4);
}
private double getPhi3(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta,
final double beta4, final double eDelta,
final double delta) {
if (betaIsZero) {
return rho * rho * Math.pow(variance + alpha * t / 3., 2) * t * t * t * t / 8.;
}
final double x = (alpha + beta * variance) * (eDelta - delta * eDelta - 1) - alpha * (1 + delta - eDelta);
return rho * rho * x * x / (2 * beta * beta * beta4);
}
private double getPhi4(final double phi3) {
return 2 * phi3;
}
double getD(final double s, final double k, final double b, final double meanVariance, final double t) {
return (Math.log(s / k) + t * (b + meanVariance / 2)) / Math.sqrt(meanVariance * t);
}
private double getCSV(final double sDf, final double nD1, final double d2, final double meanVariance) {
return -sDf * nD1 * d2 / (2 * meanVariance);
}
private double getCVV(final double sDf, final double sqrtT, final double nD1, final double d1, final double d2, final double meanVariance) {
return sDf * sqrtT * nD1 * (d1 * d2 - 1) / (4 * Math.pow(meanVariance, 1.5));
}
private double getCSVV(final double sDf, final double nD1, final double d1, final double d2, final double meanVariance) {
return sDf * nD1 * (-d1 * d2 * d2 + d1 + 2 * d2) / (4 * meanVariance * meanVariance);
}
private double getCVVV(final double sDf, final double sqrtT, final double nD1, final double d1, final double d2, final double meanVariance) {
return sDf * sqrtT * nD1 * ((d1 * d2 - 1) * (d1 * d2 - 3) - d1 * d1 - d2 * d2) / (8 * Math.pow(meanVariance, 2.5));
}
double getF1(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta, final double delta,
final double eDelta, final double sDf,
final double nD1, final double d2, final double meanVariance) {
final double cSV = getCSV(sDf, nD1, d2, meanVariance);
if (betaIsZero) {
return rho * (variance + alpha * t / 3.) * t * cSV / 2.;
}
return rho * cSV * ((alpha + beta * variance) * (1 - eDelta + delta * eDelta) + alpha * (1 + delta - eDelta)) / (beta * beta * beta * t);
}
double getF2(final boolean betaIsZero, final double variance, final double rho, final double alpha, final double t, final double beta, final double delta,
final double eDelta, final double sDf,
final double nD1, final double d1, final double d2, final double meanVariance) {
final double beta4 = beta * beta * beta * beta;
final double phi1 = getPhi1(betaIsZero, variance, rho, alpha, t, beta, beta4, eDelta, delta);
final double phi2 = getPhi2(betaIsZero, phi1, variance, rho, alpha, beta, beta4, eDelta, delta);
final double phi3 = getPhi3(betaIsZero, variance, rho, alpha, t, beta, beta4, eDelta, delta);
final double phi4 = getPhi4(phi3);
final double sqrtT = Math.sqrt(t);
final double cSV = getCSV(sDf, nD1, d2, meanVariance);
final double cVV = getCVV(sDf, sqrtT, nD1, d1, d2, meanVariance);
final double cSVV = getCSVV(sDf, nD1, d1, d2, meanVariance);
final double cVVV = getCVVV(sDf, sqrtT, nD1, d1, d2, meanVariance);
final double tInv = 1 / t;
return tInv * (phi1 * cSV + tInv * (phi2 * cVV + phi3 * cSVV + tInv * phi4 * cVVV));
}
}
| 8,844 | 0.689394 | 0.671303 | 170 | 51.023529 | 44.447979 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.464706 | false | false | 15 |
97801ed9f0f2ace675c90b463854e9a917825784 | 15,831,249,486,301 | 5155fa3d681db67b40bd3320e2828f2df08680c8 | /src/main/java/com/yidatec/model/Activity.java | 65ee11a978128199727d414f92271b4470259f1c | []
| no_license | missaouib/crm | https://github.com/missaouib/crm | f10851105bb4fc96d6f6de4bd7d6de84e87d4b9d | 52f44a8d97b34b1c182262ff858db903fbe03f1a | refs/heads/master | 2021-10-24T22:02:20.862000 | 2019-03-29T05:02:22 | 2019-03-29T05:02:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yidatec.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.yidatec.util.CustomLocalDateSerializer;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* Created by Administrator on 2017/7/21.
*/
public class Activity extends BaseModel{
// @NotBlank(message = "必须选择活动类型", groups = { })
// private String type;
@NotBlank(message = "必须输入活动名称", groups = { })
@Length( max = 200, message = "名称最多由200个字符组成", groups = { })
private String name;
@NotBlank(message = "必须选择活动类型", groups = { })
private String type;
@NotNull(message = "必须输入开始时间", groups = { })
@JsonSerialize(using = CustomLocalDateSerializer.class)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate startDate;
@NotNull(message = "必须输入结束时间", groups = { })
@JsonSerialize(using = CustomLocalDateSerializer.class)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate endDate;
@NotBlank(message = "必须选择国家", groups = { })
private String country;
// @NotBlank(message = "必须选择省份", groups = { })
private String province;
// @NotBlank(message = "必须选择城市", groups = { })
private String city;
// @NotBlank(message = "必须选择区域", groups = { })
private String region;
@Length( max = 200, message = "地址最多由200个字符组成", groups = { })
private String address;
private Integer state;
//展馆
@NotBlank(message = "必须选择展馆", groups = { })
private String exhibitioHall;
private String exhibitioHallName;
//主办方
// @NotBlank(message = "必须选择主办方", groups = { })
private String sponsor;
private String customerName;
// @NotBlank(message = "必须选择承办方", groups = { })
private String organizer;
// @NotBlank(message = "必须选择主场搭建", groups = { })
private String builder;
private String mediaIds;
private String photo;
public String getExhibitioHallName() {
return exhibitioHallName;
}
public void setExhibitioHallName(String exhibitioHallName) {
this.exhibitioHallName = exhibitioHallName;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getExhibitioHall() {
return exhibitioHall;
}
public void setExhibitioHall(String exhibitioHall) {
this.exhibitioHall = exhibitioHall;
}
public String getSponsor() {
return sponsor;
}
public void setSponsor(String sponsor) {
this.sponsor = sponsor;
}
public String getStartDateStr(){
if(startDate == null)return "";
return startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
public String getEndDateStr(){
if(endDate == null)return "";
return endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
public String getMediaIds() {
return mediaIds;
}
public void setMediaIds(String mediaIds) {
this.mediaIds = mediaIds;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOrganizer() {
return organizer;
}
public void setOrganizer(String organizer) {
this.organizer = organizer;
}
public String getBuilder() {
return builder;
}
public void setBuilder(String builder) {
this.builder = builder;
}
}
| UTF-8 | Java | 5,387 | java | Activity.java | Java | [
{
"context": ".time.format.DateTimeFormatter;\n\n/**\n * Created by Administrator on 2017/7/21.\n */\npublic class Activity extends B",
"end": 457,
"score": 0.8909680247306824,
"start": 444,
"tag": "USERNAME",
"value": "Administrator"
}
]
| null | []
| package com.yidatec.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.yidatec.util.CustomLocalDateSerializer;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* Created by Administrator on 2017/7/21.
*/
public class Activity extends BaseModel{
// @NotBlank(message = "必须选择活动类型", groups = { })
// private String type;
@NotBlank(message = "必须输入活动名称", groups = { })
@Length( max = 200, message = "名称最多由200个字符组成", groups = { })
private String name;
@NotBlank(message = "必须选择活动类型", groups = { })
private String type;
@NotNull(message = "必须输入开始时间", groups = { })
@JsonSerialize(using = CustomLocalDateSerializer.class)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate startDate;
@NotNull(message = "必须输入结束时间", groups = { })
@JsonSerialize(using = CustomLocalDateSerializer.class)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate endDate;
@NotBlank(message = "必须选择国家", groups = { })
private String country;
// @NotBlank(message = "必须选择省份", groups = { })
private String province;
// @NotBlank(message = "必须选择城市", groups = { })
private String city;
// @NotBlank(message = "必须选择区域", groups = { })
private String region;
@Length( max = 200, message = "地址最多由200个字符组成", groups = { })
private String address;
private Integer state;
//展馆
@NotBlank(message = "必须选择展馆", groups = { })
private String exhibitioHall;
private String exhibitioHallName;
//主办方
// @NotBlank(message = "必须选择主办方", groups = { })
private String sponsor;
private String customerName;
// @NotBlank(message = "必须选择承办方", groups = { })
private String organizer;
// @NotBlank(message = "必须选择主场搭建", groups = { })
private String builder;
private String mediaIds;
private String photo;
public String getExhibitioHallName() {
return exhibitioHallName;
}
public void setExhibitioHallName(String exhibitioHallName) {
this.exhibitioHallName = exhibitioHallName;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getExhibitioHall() {
return exhibitioHall;
}
public void setExhibitioHall(String exhibitioHall) {
this.exhibitioHall = exhibitioHall;
}
public String getSponsor() {
return sponsor;
}
public void setSponsor(String sponsor) {
this.sponsor = sponsor;
}
public String getStartDateStr(){
if(startDate == null)return "";
return startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
public String getEndDateStr(){
if(endDate == null)return "";
return endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
public String getMediaIds() {
return mediaIds;
}
public void setMediaIds(String mediaIds) {
this.mediaIds = mediaIds;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOrganizer() {
return organizer;
}
public void setOrganizer(String organizer) {
this.organizer = organizer;
}
public String getBuilder() {
return builder;
}
public void setBuilder(String builder) {
this.builder = builder;
}
}
| 5,387 | 0.634 | 0.630312 | 217 | 22.746544 | 19.511908 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391705 | false | false | 15 |
e4033e970bf8ea278f4af3e5fa972b051366793a | 5,686,536,733,520 | 7b97590e7a9363db0f40da748f257692ce93b373 | /src/ejercicio/pkg7/interfazgrafica7.java | 99a5aeabb6d530f59b444922856e1a23da92ea30 | []
| no_license | jpayares4/Ejercicio-7 | https://github.com/jpayares4/Ejercicio-7 | cb0e91f58e6eb36a2f549bef5cc05404e8a502b6 | 33bca2988f4671975cc9a6ce49af756564d56d4b | refs/heads/master | 2020-09-17T05:20:36.887000 | 2016-08-22T18:04:24 | 2016-08-22T18:04:24 | 66,295,758 | 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 ejercicio.pkg7;
import javax.swing.JOptionPane;
/**
*
* @author Payares
*/
public class interfazgrafica7 extends javax.swing.JFrame {
/**
* Creates new form interfazgrafica7
*/
public interfazgrafica7() {
initComponents();
}
public void borrar(){
años.setText("");
años.requestFocus();
pago.setText("");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
años = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
pago = new javax.swing.JTextField();
cmbcalcular = new javax.swing.JButton();
cmbborrar = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setFont(new java.awt.Font("Tempus Sans ITC", 0, 18)); // NOI18N
jLabel1.setText("Calculadora de pago");
jLabel2.setText("años laborados:");
años.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
añosKeyTyped(evt);
}
});
jLabel3.setText("total a pagar:");
pago.setAutoscrolls(false);
pago.setEnabled(false);
cmbcalcular.setText("Calcular");
cmbcalcular.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbcalcularActionPerformed(evt);
}
});
cmbborrar.setText("Borrar");
cmbborrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbborrarActionPerformed(evt);
}
});
jButton3.setText("Salir");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(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()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pago, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(años, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(cmbcalcular)
.addGap(51, 51, 51)
.addComponent(cmbborrar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 110, Short.MAX_VALUE)
.addComponent(jButton3)))))
.addGap(21, 21, 21))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(años, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(33, 33, 33)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(pago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 105, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbcalcular)
.addComponent(cmbborrar)
.addComponent(jButton3))
.addGap(45, 45, 45))
);
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));
pack();
}// </editor-fold>//GEN-END:initComponents
private void añosKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_añosKeyTyped
// TODO add your handling code here:
char c=evt.getKeyChar();
if(!Character.isDigit(c)) {
getToolkit().beep();
evt.consume();
}
}//GEN-LAST:event_añosKeyTyped
private void cmbcalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbcalcularActionPerformed
// TODO add your handling code here:
String res1,res2,res3;
double n1;
double op1,op2,op3;
n1 = Double.parseDouble(años.getText());
if (n1 == 0){
JOptionPane.showMessageDialog(this,"Digita al menos un numero distinto a cero(0)","Error",JOptionPane.ERROR_MESSAGE);
borrar();
años.requestFocusInWindow();
}
else{
op1 = (n1 * 120000)-20000;
res1 = String.valueOf(op1);
pago.setText(res1);
}
}
private void cmbBorrarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
borrar();
}
private void cantidad1KeyTyped(java.awt.event.KeyEvent evt) {
char c=evt.getKeyChar();
if(!Character.isDigit(c)) {
getToolkit().beep();
evt.consume();
}
}//GEN-LAST:event_cmbcalcularActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_jButton3ActionPerformed
private void cmbborrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbborrarActionPerformed
// TODO add your handling code here:
borrar();
}//GEN-LAST:event_cmbborrarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new interfazgrafica7().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField años;
private javax.swing.JButton cmbborrar;
private javax.swing.JButton cmbcalcular;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField pago;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 10,941 | java | interfazgrafica7.java | Java | [
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author Payares\n */\npublic class interfazgrafica7 extends javax.s",
"end": 268,
"score": 0.9997398853302002,
"start": 261,
"tag": "NAME",
"value": "Payares"
}
]
| 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 ejercicio.pkg7;
import javax.swing.JOptionPane;
/**
*
* @author Payares
*/
public class interfazgrafica7 extends javax.swing.JFrame {
/**
* Creates new form interfazgrafica7
*/
public interfazgrafica7() {
initComponents();
}
public void borrar(){
años.setText("");
años.requestFocus();
pago.setText("");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
años = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
pago = new javax.swing.JTextField();
cmbcalcular = new javax.swing.JButton();
cmbborrar = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setFont(new java.awt.Font("Tempus Sans ITC", 0, 18)); // NOI18N
jLabel1.setText("Calculadora de pago");
jLabel2.setText("años laborados:");
años.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
añosKeyTyped(evt);
}
});
jLabel3.setText("total a pagar:");
pago.setAutoscrolls(false);
pago.setEnabled(false);
cmbcalcular.setText("Calcular");
cmbcalcular.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbcalcularActionPerformed(evt);
}
});
cmbborrar.setText("Borrar");
cmbborrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbborrarActionPerformed(evt);
}
});
jButton3.setText("Salir");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(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()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pago, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(años, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(cmbcalcular)
.addGap(51, 51, 51)
.addComponent(cmbborrar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 110, Short.MAX_VALUE)
.addComponent(jButton3)))))
.addGap(21, 21, 21))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(años, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(33, 33, 33)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(pago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 105, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbcalcular)
.addComponent(cmbborrar)
.addComponent(jButton3))
.addGap(45, 45, 45))
);
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));
pack();
}// </editor-fold>//GEN-END:initComponents
private void añosKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_añosKeyTyped
// TODO add your handling code here:
char c=evt.getKeyChar();
if(!Character.isDigit(c)) {
getToolkit().beep();
evt.consume();
}
}//GEN-LAST:event_añosKeyTyped
private void cmbcalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbcalcularActionPerformed
// TODO add your handling code here:
String res1,res2,res3;
double n1;
double op1,op2,op3;
n1 = Double.parseDouble(años.getText());
if (n1 == 0){
JOptionPane.showMessageDialog(this,"Digita al menos un numero distinto a cero(0)","Error",JOptionPane.ERROR_MESSAGE);
borrar();
años.requestFocusInWindow();
}
else{
op1 = (n1 * 120000)-20000;
res1 = String.valueOf(op1);
pago.setText(res1);
}
}
private void cmbBorrarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
borrar();
}
private void cantidad1KeyTyped(java.awt.event.KeyEvent evt) {
char c=evt.getKeyChar();
if(!Character.isDigit(c)) {
getToolkit().beep();
evt.consume();
}
}//GEN-LAST:event_cmbcalcularActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_jButton3ActionPerformed
private void cmbborrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbborrarActionPerformed
// TODO add your handling code here:
borrar();
}//GEN-LAST:event_cmbborrarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(interfazgrafica7.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new interfazgrafica7().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField años;
private javax.swing.JButton cmbborrar;
private javax.swing.JButton cmbcalcular;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField pago;
// End of variables declaration//GEN-END:variables
}
| 10,941 | 0.596596 | 0.581587 | 258 | 41.352715 | 35.499039 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515504 | false | false | 15 |
5fdf812ed503782b5adbd7eb672e2a1ee4d6ea72 | 2,001,454,807,124 | 441b52b2ebb6457d8a05a9b1655a3fa932377307 | /src/tables/Movie.java | c4b7aee03c695802c7c9691975ca2178be98bfd9 | []
| no_license | zlczlc/cs5200-final-project | https://github.com/zlczlc/cs5200-final-project | 6cb4d69c101e72a0dc83aeaabc3f9522b019ebb6 | 06ef1bb886846efef2d0d1cb32cb880995aee81b | refs/heads/master | 2020-07-04T03:45:49.885000 | 2016-02-05T04:50:16 | 2016-02-05T04:50:16 | 27,897,217 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tables;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the movie database table.
*
*/
@Entity
@NamedQueries({
@NamedQuery(name="Movie.findAll", query="SELECT s FROM Movie s"),
@NamedQuery(name="Movie.findOne", query="SELECT s FROM Movie s where s.moviename=:name")})
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@OneToMany(mappedBy="movie")
private List<Event> events;
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(String releaseYear) {
this.releaseYear = releaseYear;
}
public String getRunTime() {
return runTime;
}
public void setRunTime(String runTime) {
this.runTime = runTime;
}
private String moviename;
private String longDescription;
private String shortDescription;
private String imageUrl;
private String officialUrl;
private String releaseYear;
private String runTime;
private String qualityRating;
private String ratingsBody;
private String topCast;
public String getOfficialUrl() {
return officialUrl;
}
public void setOfficialUrl(String officialUrl) {
this.officialUrl = officialUrl;
}
public String getQualityRating() {
return qualityRating;
}
public void setQualityRating(String qualityRating) {
this.qualityRating = qualityRating;
}
public String getRatingsBody() {
return ratingsBody;
}
public void setRatingsBody(String ratingsBody) {
this.ratingsBody = ratingsBody;
}
public String getTopCast() {
return topCast;
}
public void setTopCast(String topCast) {
this.topCast = topCast;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
private String rating;
//bi-directional many-to-many association to Movietype
@ManyToMany
@JoinTable(
name="movie_type"
, joinColumns={
@JoinColumn(name="movieId")
}
, inverseJoinColumns={
@JoinColumn(name="movieType")
})
private List<Movietype> movietypes;
//bi-directional many-to-many association to User
@ManyToMany(mappedBy="movies")
private List<User> users;
public Movie() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getMoviename() {
return this.moviename;
}
public void setMoviename(String moviename) {
this.moviename = moviename;
}
public List<Movietype> getMovietypes() {
return this.movietypes;
}
public void setMovietypes(List<Movietype> movietypes) {
this.movietypes = movietypes;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
} | UTF-8 | Java | 3,293 | java | Movie.java | Java | []
| null | []
| package tables;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the movie database table.
*
*/
@Entity
@NamedQueries({
@NamedQuery(name="Movie.findAll", query="SELECT s FROM Movie s"),
@NamedQuery(name="Movie.findOne", query="SELECT s FROM Movie s where s.moviename=:name")})
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@OneToMany(mappedBy="movie")
private List<Event> events;
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(String releaseYear) {
this.releaseYear = releaseYear;
}
public String getRunTime() {
return runTime;
}
public void setRunTime(String runTime) {
this.runTime = runTime;
}
private String moviename;
private String longDescription;
private String shortDescription;
private String imageUrl;
private String officialUrl;
private String releaseYear;
private String runTime;
private String qualityRating;
private String ratingsBody;
private String topCast;
public String getOfficialUrl() {
return officialUrl;
}
public void setOfficialUrl(String officialUrl) {
this.officialUrl = officialUrl;
}
public String getQualityRating() {
return qualityRating;
}
public void setQualityRating(String qualityRating) {
this.qualityRating = qualityRating;
}
public String getRatingsBody() {
return ratingsBody;
}
public void setRatingsBody(String ratingsBody) {
this.ratingsBody = ratingsBody;
}
public String getTopCast() {
return topCast;
}
public void setTopCast(String topCast) {
this.topCast = topCast;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
private String rating;
//bi-directional many-to-many association to Movietype
@ManyToMany
@JoinTable(
name="movie_type"
, joinColumns={
@JoinColumn(name="movieId")
}
, inverseJoinColumns={
@JoinColumn(name="movieType")
})
private List<Movietype> movietypes;
//bi-directional many-to-many association to User
@ManyToMany(mappedBy="movies")
private List<User> users;
public Movie() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getMoviename() {
return this.moviename;
}
public void setMoviename(String moviename) {
this.moviename = moviename;
}
public List<Movietype> getMovietypes() {
return this.movietypes;
}
public void setMovietypes(List<Movietype> movietypes) {
this.movietypes = movietypes;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
} | 3,293 | 0.730944 | 0.730641 | 179 | 17.402235 | 18.011021 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.22905 | false | false | 15 |
7279a3346dc02c1343ba408ce8ed24f715dddb8d | 21,534,966,028,553 | a4e2d087e4f3a1ad689946f843e313b6a3ebd8ac | /src/test/java/com/pragmatic/examples/selenium/ui/checkbox/ICheckbox.java | 74dc9f2d1ca35d524cfff2fb29e484c0b13b480b | []
| no_license | pragmatictesters/Pragmatic-Learning-SeleniumWebDriver-B01D2020 | https://github.com/pragmatictesters/Pragmatic-Learning-SeleniumWebDriver-B01D2020 | 564226b7ebefab1dc6f7bb55feb15e330aaa6219 | 2b47c139fc357850439520cbfe5cd4177b43f322 | refs/heads/master | 2023-02-08T15:32:08.246000 | 2020-12-30T04:27:27 | 2020-12-30T04:27:27 | 319,577,917 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pragmatic.examples.selenium.ui.checkbox;
/**
* Created by Pragmatic Test Labs (Private) Limited
*
* @Auth0r Janesh Kodikara
*/
public interface ICheckbox {
public void check();
public void uncheck();
public void toggle();
public boolean isChecked();
}
| UTF-8 | Java | 290 | java | ICheckbox.java | Java | [
{
"context": "ragmatic Test Labs (Private) Limited\n *\n * @Auth0r Janesh Kodikara\n */\npublic interface ICheckbox {\n\n public void",
"end": 139,
"score": 0.999875545501709,
"start": 124,
"tag": "NAME",
"value": "Janesh Kodikara"
}
]
| null | []
| package com.pragmatic.examples.selenium.ui.checkbox;
/**
* Created by Pragmatic Test Labs (Private) Limited
*
* @Auth0r <NAME>
*/
public interface ICheckbox {
public void check();
public void uncheck();
public void toggle();
public boolean isChecked();
}
| 281 | 0.686207 | 0.682759 | 18 | 15.111111 | 17.505201 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false | 15 |
f7b74821e56c254620fe0f145f97138347a29bd3 | 9,440,338,161,236 | d3107e77326f9bf1ab610e5b748a6a33782cb419 | /app/src/main/java/webdevils/webdevilsapp/SubmitConceptFragment.java | 4aeeec9c76ab0216cce052ac01729d525bdb74f2 | []
| no_license | cfroke/WebDevilsApp | https://github.com/cfroke/WebDevilsApp | 73ea8e38d4233dc194edfac832b49527e68c1614 | cd0ea8d20ea3a095a9b11fac279bddc4829733c3 | refs/heads/master | 2021-01-11T19:44:40.337000 | 2017-07-18T17:14:18 | 2017-07-18T17:14:18 | 79,385,840 | 0 | 1 | null | false | 2017-04-19T04:22:52 | 2017-01-18T21:24:23 | 2017-01-18T21:25:04 | 2017-04-19T04:22:52 | 7,735 | 0 | 1 | 0 | Java | null | null | /**
* SER 401 / 402 -- Senior Project -- WebDevils -- Project 11
*/
package webdevils.webdevilsapp;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import common.Concept;
import common.User;
import server.Services;
/**
* This fragment allows a user to submit a new concept to the
* server. Users must provide a Title, Type, and Description
* for a new concept. Optionally they may use the toggle button
* to add a collaborator (of their choosing), providing another
* members user name to make them a co-author of the concept.
*/
public class SubmitConceptFragment extends Fragment {
private String conceptTitle = "";
private String conceptDesc = "";
private String conceptType = "";
private String collaboratorName = "";
private final String commented = "";
private Concept concept;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_submit_concept, container, false);
}
@Override
public void onStart() {
super.onStart();
Spinner dropdown = (Spinner) getView().findViewById(R.id.spinnerType);
String[] items = new String[]{"Select Concept Type", "Product", "Service", "Improvement"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
//getting user object that has been passed by other pages
//final User user = (User) getIntent().getSerializableExtra("userObject");
final Services services = new Services();
final CheckBox toggle = (CheckBox) getView().findViewById(R.id.collabCheckBox);
final EditText collaborator = (EditText) getView().findViewById(R.id.collaboratorText);
collaborator.setFocusable(false); // initially set collaborator text box to disabled
collaborator.setBackgroundColor(Color.LTGRAY);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) { // enables collab text field
collaborator.setFocusableInTouchMode(true);
collaborator.setBackgroundColor(Color.WHITE);
} else { // clears collab text and disables entry
collaborator.setText("");
collaborator.setBackgroundColor(Color.LTGRAY);
collaborator.setFocusable(false);
}
}
});
//Create concept
Button submit = (Button) getView().findViewById(R.id.buttonSubmit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(v.getContext());
EditText title = (EditText) getView().findViewById(R.id.titleText);
EditText description = (EditText) getView().findViewById(R.id.descriptionText);
Spinner type = (Spinner) getView().findViewById(R.id.spinnerType);
if (type.getSelectedItem().toString().equals("Select Concept Type")) {
dlgAlert.setMessage("Please select a concept type.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else if (title.getText().toString().equals("")) {
dlgAlert.setMessage("Please enter a title.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else if (description.getText().toString().equals("")) {
dlgAlert.setMessage("Please enter a description.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else if (toggle.isChecked() && collaborator.getText().toString().equals("")) {
dlgAlert.setMessage("Please enter a collaborator.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else {
conceptTitle = title.getText().toString();
conceptDesc = description.getText().toString();
conceptType = type.getSelectedItem().toString();
if (toggle.isChecked() ) {
collaboratorName = collaborator.getText().toString();
} else {
collaboratorName = "";
}
//Gets user stored in MainActivity
final User user = ((MainActivity)getActivity()).getUser();
//Submits concept to Storage
concept = services.createConcept(user, conceptTitle, conceptDesc, conceptType, collaboratorName);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.addToBackStack(null)
.replace(R.id.content_frame, new ConceptsFragment()).commit();
}
}
});
}
}
| UTF-8 | Java | 7,534 | java | SubmitConceptFragment.java | Java | []
| null | []
| /**
* SER 401 / 402 -- Senior Project -- WebDevils -- Project 11
*/
package webdevils.webdevilsapp;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import common.Concept;
import common.User;
import server.Services;
/**
* This fragment allows a user to submit a new concept to the
* server. Users must provide a Title, Type, and Description
* for a new concept. Optionally they may use the toggle button
* to add a collaborator (of their choosing), providing another
* members user name to make them a co-author of the concept.
*/
public class SubmitConceptFragment extends Fragment {
private String conceptTitle = "";
private String conceptDesc = "";
private String conceptType = "";
private String collaboratorName = "";
private final String commented = "";
private Concept concept;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_submit_concept, container, false);
}
@Override
public void onStart() {
super.onStart();
Spinner dropdown = (Spinner) getView().findViewById(R.id.spinnerType);
String[] items = new String[]{"Select Concept Type", "Product", "Service", "Improvement"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
//getting user object that has been passed by other pages
//final User user = (User) getIntent().getSerializableExtra("userObject");
final Services services = new Services();
final CheckBox toggle = (CheckBox) getView().findViewById(R.id.collabCheckBox);
final EditText collaborator = (EditText) getView().findViewById(R.id.collaboratorText);
collaborator.setFocusable(false); // initially set collaborator text box to disabled
collaborator.setBackgroundColor(Color.LTGRAY);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) { // enables collab text field
collaborator.setFocusableInTouchMode(true);
collaborator.setBackgroundColor(Color.WHITE);
} else { // clears collab text and disables entry
collaborator.setText("");
collaborator.setBackgroundColor(Color.LTGRAY);
collaborator.setFocusable(false);
}
}
});
//Create concept
Button submit = (Button) getView().findViewById(R.id.buttonSubmit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(v.getContext());
EditText title = (EditText) getView().findViewById(R.id.titleText);
EditText description = (EditText) getView().findViewById(R.id.descriptionText);
Spinner type = (Spinner) getView().findViewById(R.id.spinnerType);
if (type.getSelectedItem().toString().equals("Select Concept Type")) {
dlgAlert.setMessage("Please select a concept type.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else if (title.getText().toString().equals("")) {
dlgAlert.setMessage("Please enter a title.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else if (description.getText().toString().equals("")) {
dlgAlert.setMessage("Please enter a description.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else if (toggle.isChecked() && collaborator.getText().toString().equals("")) {
dlgAlert.setMessage("Please enter a collaborator.");
dlgAlert.setTitle("Invalid Selection");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
} else {
conceptTitle = title.getText().toString();
conceptDesc = description.getText().toString();
conceptType = type.getSelectedItem().toString();
if (toggle.isChecked() ) {
collaboratorName = collaborator.getText().toString();
} else {
collaboratorName = "";
}
//Gets user stored in MainActivity
final User user = ((MainActivity)getActivity()).getUser();
//Submits concept to Storage
concept = services.createConcept(user, conceptTitle, conceptDesc, conceptType, collaboratorName);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.addToBackStack(null)
.replace(R.id.content_frame, new ConceptsFragment()).commit();
}
}
});
}
}
| 7,534 | 0.568622 | 0.567428 | 153 | 48.241829 | 26.835501 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.732026 | false | false | 15 |
14ec9961b5947aac2e6c8178cec8ddbd443efb09 | 9,191,230,026,906 | a3cb653937e72374a1c5e53bfcd03d04663ee3a6 | /app01/src/main/resources/temp/it/gov/agenziaentrate/ivaservizi/docs/xsd/fatture/v12/impl/FatturaPrincipaleTypeImpl.java | 50a157373afeeb1a7387ba2f793f569310b417fa | []
| no_license | siletti/AccessToFatturaPA | https://github.com/siletti/AccessToFatturaPA | 469697d3085a49dec6bac2ecac936a9e8ebd15ab | cbed89a15c2e5df4ef25f3afbdc4c232a65e9733 | refs/heads/master | 2021-07-08T03:18:51.272000 | 2019-06-02T13:35:15 | 2019-06-02T13:35:15 | 189,826,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* XML Type: FatturaPrincipaleType
* Namespace: http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2
* Java type: it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.FatturaPrincipaleType
*
* Automatically generated - do not modify.
*/
package it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.impl;
/**
* An XML FatturaPrincipaleType(@http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2).
*
* This is a complex type.
*/
public class FatturaPrincipaleTypeImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.FatturaPrincipaleType
{
private static final long serialVersionUID = 1L;
public FatturaPrincipaleTypeImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName NUMEROFATTURAPRINCIPALE$0 =
new javax.xml.namespace.QName("", "NumeroFatturaPrincipale");
private static final javax.xml.namespace.QName DATAFATTURAPRINCIPALE$2 =
new javax.xml.namespace.QName("", "DataFatturaPrincipale");
/**
* Gets the "NumeroFatturaPrincipale" element
*/
public java.lang.String getNumeroFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "NumeroFatturaPrincipale" element
*/
public it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type xgetNumeroFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type target = null;
target = (it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
return target;
}
}
/**
* Sets the "NumeroFatturaPrincipale" element
*/
public void setNumeroFatturaPrincipale(java.lang.String numeroFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(NUMEROFATTURAPRINCIPALE$0);
}
target.setStringValue(numeroFatturaPrincipale);
}
}
/**
* Sets (as xml) the "NumeroFatturaPrincipale" element
*/
public void xsetNumeroFatturaPrincipale(it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type numeroFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type target = null;
target = (it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
if (target == null)
{
target = (it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type)get_store().add_element_user(NUMEROFATTURAPRINCIPALE$0);
}
target.set(numeroFatturaPrincipale);
}
}
/**
* Gets the "DataFatturaPrincipale" element
*/
public java.util.Calendar getDataFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
if (target == null)
{
return null;
}
return target.getCalendarValue();
}
}
/**
* Gets (as xml) the "DataFatturaPrincipale" element
*/
public org.apache.xmlbeans.XmlDate xgetDataFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlDate target = null;
target = (org.apache.xmlbeans.XmlDate)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
return target;
}
}
/**
* Sets the "DataFatturaPrincipale" element
*/
public void setDataFatturaPrincipale(java.util.Calendar dataFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(DATAFATTURAPRINCIPALE$2);
}
target.setCalendarValue(dataFatturaPrincipale);
}
}
/**
* Sets (as xml) the "DataFatturaPrincipale" element
*/
public void xsetDataFatturaPrincipale(org.apache.xmlbeans.XmlDate dataFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlDate target = null;
target = (org.apache.xmlbeans.XmlDate)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
if (target == null)
{
target = (org.apache.xmlbeans.XmlDate)get_store().add_element_user(DATAFATTURAPRINCIPALE$2);
}
target.set(dataFatturaPrincipale);
}
}
}
| UTF-8 | Java | 6,103 | java | FatturaPrincipaleTypeImpl.java | Java | []
| null | []
| /*
* XML Type: FatturaPrincipaleType
* Namespace: http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2
* Java type: it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.FatturaPrincipaleType
*
* Automatically generated - do not modify.
*/
package it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.impl;
/**
* An XML FatturaPrincipaleType(@http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2).
*
* This is a complex type.
*/
public class FatturaPrincipaleTypeImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.FatturaPrincipaleType
{
private static final long serialVersionUID = 1L;
public FatturaPrincipaleTypeImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName NUMEROFATTURAPRINCIPALE$0 =
new javax.xml.namespace.QName("", "NumeroFatturaPrincipale");
private static final javax.xml.namespace.QName DATAFATTURAPRINCIPALE$2 =
new javax.xml.namespace.QName("", "DataFatturaPrincipale");
/**
* Gets the "NumeroFatturaPrincipale" element
*/
public java.lang.String getNumeroFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "NumeroFatturaPrincipale" element
*/
public it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type xgetNumeroFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type target = null;
target = (it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
return target;
}
}
/**
* Sets the "NumeroFatturaPrincipale" element
*/
public void setNumeroFatturaPrincipale(java.lang.String numeroFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(NUMEROFATTURAPRINCIPALE$0);
}
target.setStringValue(numeroFatturaPrincipale);
}
}
/**
* Sets (as xml) the "NumeroFatturaPrincipale" element
*/
public void xsetNumeroFatturaPrincipale(it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type numeroFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type target = null;
target = (it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type)get_store().find_element_user(NUMEROFATTURAPRINCIPALE$0, 0);
if (target == null)
{
target = (it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v12.String20Type)get_store().add_element_user(NUMEROFATTURAPRINCIPALE$0);
}
target.set(numeroFatturaPrincipale);
}
}
/**
* Gets the "DataFatturaPrincipale" element
*/
public java.util.Calendar getDataFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
if (target == null)
{
return null;
}
return target.getCalendarValue();
}
}
/**
* Gets (as xml) the "DataFatturaPrincipale" element
*/
public org.apache.xmlbeans.XmlDate xgetDataFatturaPrincipale()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlDate target = null;
target = (org.apache.xmlbeans.XmlDate)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
return target;
}
}
/**
* Sets the "DataFatturaPrincipale" element
*/
public void setDataFatturaPrincipale(java.util.Calendar dataFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(DATAFATTURAPRINCIPALE$2);
}
target.setCalendarValue(dataFatturaPrincipale);
}
}
/**
* Sets (as xml) the "DataFatturaPrincipale" element
*/
public void xsetDataFatturaPrincipale(org.apache.xmlbeans.XmlDate dataFatturaPrincipale)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlDate target = null;
target = (org.apache.xmlbeans.XmlDate)get_store().find_element_user(DATAFATTURAPRINCIPALE$2, 0);
if (target == null)
{
target = (org.apache.xmlbeans.XmlDate)get_store().add_element_user(DATAFATTURAPRINCIPALE$2);
}
target.set(dataFatturaPrincipale);
}
}
}
| 6,103 | 0.607406 | 0.597411 | 164 | 35.213413 | 37.923023 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.323171 | false | false | 15 |
9cf716019c2d155fd579a63a63a11e4d2b75757b | 10,634,339,089,261 | aa77c69b68e1fb01263b80694ead024f9c33f5ef | /src/com/scrumers/dao/TaskDao.java | 809fa794e7930a98f7c3b712cfa215a82ec61d75 | []
| no_license | aurelianoHose/scrumers | https://github.com/aurelianoHose/scrumers | e93576b5c6ce5189111ff7b0db2a226aee39054e | d6afd3be0466a2596775bd24c13fa54d5cdb6952 | refs/heads/master | 2021-01-10T13:21:27.026000 | 2016-01-14T12:50:23 | 2016-01-14T12:50:23 | 49,598,037 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scrumers.dao;
import java.util.List;
import com.scrumers.entity.Comment;
import com.scrumers.entity.Task;
public interface TaskDao extends GenericDao<Long, Task> {
List<Task> readAll();
Long selectId();
void commentTask(Long uid, Long tid, String comment);
void createWithId(Task s, Long sid);
void updateStatus(Long id, Long stid);
void updatePriorityInST(Long tid, Long priority);
List<Task> readByStoryId(Long sid);
void deleteFromStoryTasks(Long id);
void deleteComment(Long cid);
List<Long> readPriorities(Long sid, Long stat_id);
List<Comment> readCommentsByTaskId(Long tid);
}
| UTF-8 | Java | 662 | java | TaskDao.java | Java | []
| null | []
| package com.scrumers.dao;
import java.util.List;
import com.scrumers.entity.Comment;
import com.scrumers.entity.Task;
public interface TaskDao extends GenericDao<Long, Task> {
List<Task> readAll();
Long selectId();
void commentTask(Long uid, Long tid, String comment);
void createWithId(Task s, Long sid);
void updateStatus(Long id, Long stid);
void updatePriorityInST(Long tid, Long priority);
List<Task> readByStoryId(Long sid);
void deleteFromStoryTasks(Long id);
void deleteComment(Long cid);
List<Long> readPriorities(Long sid, Long stat_id);
List<Comment> readCommentsByTaskId(Long tid);
}
| 662 | 0.70997 | 0.70997 | 31 | 20.354839 | 21.01543 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.709677 | false | false | 15 |
6773f57beb3fc69e1c9168ab2b61123be7237ff6 | 644,245,162,663 | d64f8f4432baec5905bd6cc8725150c1c5bb8cb7 | /authentication-service/src/main/java/com/cognizant/authenticationservice/repository/RoleRepository.java | eee69a11909f5e6f636d59a245df08f0a8e06380 | []
| no_license | vetriselvi16/practice | https://github.com/vetriselvi16/practice | b5fc531b5a067daff1433f90448b479d70c1b08b | f7a7c738797c8240aecd3e30f4fdcf0872e1f5d9 | refs/heads/master | 2023-01-08T08:19:53.553000 | 2019-12-05T06:42:44 | 2019-12-05T06:42:44 | 225,843,662 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cognizant.authenticationservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.cognizant.authenticationservice.model.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Integer>{
public Role findByName(String name);
}
| UTF-8 | Java | 411 | java | RoleRepository.java | Java | []
| null | []
| package com.cognizant.authenticationservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.cognizant.authenticationservice.model.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Integer>{
public Role findByName(String name);
}
| 411 | 0.846715 | 0.846715 | 15 | 26.4 | 27.356413 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 15 |
14bc487558123e76e6de11da466bc3325bbe6f0d | 506,806,185,504 | 67d98c02b1ab4fe6b317f5423c8890722e81beaa | /src/leetcode/CountingBitsSolution.java | 6bd1916f38a87701cc3b384ecc80cfc9f5991b66 | []
| no_license | jjsahalf/leetcode | https://github.com/jjsahalf/leetcode | 23c77c22c4d913638aaf12f28eecc752e1c83d90 | 71628d2e3d88acecae9131538602d60161e64830 | refs/heads/master | 2021-01-23T15:27:29.940000 | 2016-11-21T04:34:12 | 2016-11-21T04:34:12 | 28,071,355 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
/**
* Created by yufeijiang on 8/29/16.
*/
public class CountingBitsSolution {
public int[] countBits(int num) {
int[] array=new int[num+1];
array[0]=0;
if(num==0){
return array;
}
array[1]=1;
if(num==1){
return array;
}
int powerOfTwo=2;
int i=2;
while(i<=num){
int currentGap=0;
if(i==powerOfTwo){
currentGap=powerOfTwo;
powerOfTwo*=2;
}
while(i<=num && i<powerOfTwo){
array[i]=array[i-currentGap]+1;;
i++;
}
}
return array;
}
}
| UTF-8 | Java | 704 | java | CountingBitsSolution.java | Java | [
{
"context": "package leetcode;\n\n/**\n * Created by yufeijiang on 8/29/16.\n */\npublic class CountingBitsSolution",
"end": 47,
"score": 0.9885191917419434,
"start": 37,
"tag": "USERNAME",
"value": "yufeijiang"
}
]
| null | []
| package leetcode;
/**
* Created by yufeijiang on 8/29/16.
*/
public class CountingBitsSolution {
public int[] countBits(int num) {
int[] array=new int[num+1];
array[0]=0;
if(num==0){
return array;
}
array[1]=1;
if(num==1){
return array;
}
int powerOfTwo=2;
int i=2;
while(i<=num){
int currentGap=0;
if(i==powerOfTwo){
currentGap=powerOfTwo;
powerOfTwo*=2;
}
while(i<=num && i<powerOfTwo){
array[i]=array[i-currentGap]+1;;
i++;
}
}
return array;
}
}
| 704 | 0.430398 | 0.40625 | 32 | 21 | 12.462443 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46875 | false | false | 15 |
a0f7ad4b04dd90c121147a13d51781adbaf228ce | 24,232,205,491,574 | 725b44fb9ecc02970a5902034fd7191ad0e36049 | /app/src/main/java/com/warpdrive/slider/demo/DemoApp.java | 34ca7fbd237e7c4cf6ee51ac563839383b160c43 | [
"Apache-2.0"
]
| permissive | wulijie/Slider | https://github.com/wulijie/Slider | c7d75b7ee653cd3c5850df6df46a25fbe2013a58 | 9e4ed594ae1b3fc28b293d087f80984cf73fdcca | refs/heads/master | 2021-09-04T03:05:02.147000 | 2018-01-15T01:52:52 | 2018-01-15T01:52:52 | 115,601,793 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.warpdrive.slider.demo;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
/**
* Created by wulijie on 2018/1/8.
*/
public class DemoApp extends Application {
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) return;
LeakCanary.install(this);
}
}
| UTF-8 | Java | 368 | java | DemoApp.java | Java | [
{
"context": "squareup.leakcanary.LeakCanary;\n\n/**\n * Created by wulijie on 2018/1/8.\n */\npublic class DemoApp extends App",
"end": 138,
"score": 0.9995161294937134,
"start": 131,
"tag": "USERNAME",
"value": "wulijie"
}
]
| null | []
| package com.warpdrive.slider.demo;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
/**
* Created by wulijie on 2018/1/8.
*/
public class DemoApp extends Application {
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) return;
LeakCanary.install(this);
}
}
| 368 | 0.690217 | 0.673913 | 17 | 20.647058 | 18.009609 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 15 |
83efcf5ebd8f8462c637e89062ebb7728c0f18d8 | 1,657,857,406,505 | 7553c7cbeea4f393339fe24e9a05ab6e4a7dde5e | /threadpool/src/main/java/com/sw/project/teamshrio/client/test/TestTaskEventListener.java | 6a9af7665ac901a9f504103f53ce623d1ba86c23 | []
| no_license | peterAndzeze/knowproject | https://github.com/peterAndzeze/knowproject | ab061718aab022becd92f3a403107d0aea22ebd4 | 2db075e63b29c3c9b4270d831377d67cb491091d | refs/heads/master | 2020-03-27T12:44:24.656000 | 2018-12-10T09:33:18 | 2018-12-10T09:33:18 | 146,565,691 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sw.project.teamshrio.client.test;
import com.sw.project.teamshrio.client.task.TaskEeventListener;
import com.sw.project.teamshrio.client.task.ThreadContext;
public class TestTaskEventListener implements TaskEeventListener {
@Override
public void before(ThreadContext threadContext) {
System.out.println("hello ***********"+threadContext.getLimit());
}
@Override
public void end(ThreadContext threadContext) {
if(threadContext.getCurrentTask().getIsEnding()){
System.out.println("hello ---------------game over!!!");
}
}
}
| UTF-8 | Java | 598 | java | TestTaskEventListener.java | Java | []
| null | []
| package com.sw.project.teamshrio.client.test;
import com.sw.project.teamshrio.client.task.TaskEeventListener;
import com.sw.project.teamshrio.client.task.ThreadContext;
public class TestTaskEventListener implements TaskEeventListener {
@Override
public void before(ThreadContext threadContext) {
System.out.println("hello ***********"+threadContext.getLimit());
}
@Override
public void end(ThreadContext threadContext) {
if(threadContext.getCurrentTask().getIsEnding()){
System.out.println("hello ---------------game over!!!");
}
}
}
| 598 | 0.687291 | 0.687291 | 19 | 30.473684 | 28.145054 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false | 15 |
01b14d4aa1fc6a371cd741176d465ac46c7cbeeb | 11,166,915,038,619 | 5a8cdb54c345e29cae5daa65f9420eac82eca9c7 | /Chapter5_Decisions/PracticeExercises/E5_1.java | 49cc7ff18273120f08e87b352ed49466f3bded38 | []
| no_license | DimasSheldon/Java-Concepts-Early-Objects-7th-Edition-Solutions | https://github.com/DimasSheldon/Java-Concepts-Early-Objects-7th-Edition-Solutions | ff052a5c6e1e2c40a904a88437768562dac5380f | 757ce8b10000404681c4de751511822e86ed2b58 | refs/heads/master | 2021-09-14T12:43:15.914000 | 2018-05-14T03:57:17 | 2018-05-14T03:57:17 | 110,437,223 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package EKPL.Chapter5_Decisions.PracticeExercises;
import java.util.Scanner;
/**
* Created by Sheldon on 11/5/2016.
* A program that reads an integer and prints whether it is
* a negative, zero, or positive.
*/
public class E5_1 {
public static void main(String[] args) {
System.out.print("Please input an integer number: ");
Scanner theInput = new Scanner(System.in);
//Check whether the input is a number or not
if (theInput.hasNextInt()) {
// The input is a number
int number = theInput.nextInt();
System.out.printf("The number %5s%5d%n", ": ", number);
if (number < 0) {
System.out.println("It is a negative number.");
} else if (number == 0) {
System.out.println("It is a zero");
} else {
System.out.println("It is a positive number");
}
} else {
System.out.println("Invalid input");
}
}
}
| UTF-8 | Java | 933 | java | E5_1.java | Java | [
{
"context": "\n\r\nimport java.util.Scanner;\r\n\r\n/**\r\n * Created by Sheldon on 11/5/2016.\r\n * A program that reads an integer",
"end": 109,
"score": 0.9997889399528503,
"start": 102,
"tag": "NAME",
"value": "Sheldon"
}
]
| null | []
| package EKPL.Chapter5_Decisions.PracticeExercises;
import java.util.Scanner;
/**
* Created by Sheldon on 11/5/2016.
* A program that reads an integer and prints whether it is
* a negative, zero, or positive.
*/
public class E5_1 {
public static void main(String[] args) {
System.out.print("Please input an integer number: ");
Scanner theInput = new Scanner(System.in);
//Check whether the input is a number or not
if (theInput.hasNextInt()) {
// The input is a number
int number = theInput.nextInt();
System.out.printf("The number %5s%5d%n", ": ", number);
if (number < 0) {
System.out.println("It is a negative number.");
} else if (number == 0) {
System.out.println("It is a zero");
} else {
System.out.println("It is a positive number");
}
} else {
System.out.println("Invalid input");
}
}
}
| 933 | 0.600214 | 0.585209 | 31 | 28.096775 | 20.333279 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false | 15 |
21aa83a6028b9e262fc9d7073b3f0da2dc62a343 | 30,004,641,535,871 | 9bc4aece68fb2163f9a4f1fbe47ee90b39867a80 | /kodilla-exception/src/main/java/test/FlightExceptionRunner.java | 915046e92271038eb99d2dbd19e8c9494494c758 | []
| no_license | akecka/Agnieszka_Kecka_Kodilla_Java | https://github.com/akecka/Agnieszka_Kecka_Kodilla_Java | ef910442e15b1058f6de7094f89738f659999a61 | a4a2b0cd4250c0f2ff5a6d892e6cda3f4b4d939c | refs/heads/master | 2021-09-07T03:46:06.937000 | 2018-02-16T20:43:30 | 2018-02-16T20:43:30 | 105,171,426 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
public class FlightExceptionRunner {
public static void main(String[] args) throws RouteNotFoundException {
Flight flight = new Flight("Heathrow", "Okęcie");
FlightFinder flightFinder = new FlightFinder();
try {
flightFinder.findFlight(flight);
System.out.println("Flights found: " + flight.getDepartureAirport() + " - " + flight.getArrivalAirport());
} catch (RouteNotFoundException e) {
System.out.println(e);
}
}
}
| UTF-8 | Java | 526 | java | FlightExceptionRunner.java | Java | []
| null | []
| package test;
public class FlightExceptionRunner {
public static void main(String[] args) throws RouteNotFoundException {
Flight flight = new Flight("Heathrow", "Okęcie");
FlightFinder flightFinder = new FlightFinder();
try {
flightFinder.findFlight(flight);
System.out.println("Flights found: " + flight.getDepartureAirport() + " - " + flight.getArrivalAirport());
} catch (RouteNotFoundException e) {
System.out.println(e);
}
}
}
| 526 | 0.622857 | 0.622857 | 22 | 22.863636 | 30.853458 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 15 |
83080f2b1c6c2b7aeee6e75b13b656078c811c15 | 33,578,054,366,498 | 63ef31a01f61de8824831b9694f2dac74d0f6c33 | /src/main/java/com/app/geeks/arrays/TrieDS.java | e6f07b8f08836800e8dad4b6c2c724bbd0b5fc8a | []
| no_license | sugyan84/Challenges | https://github.com/sugyan84/Challenges | d5cdcdbf229f5f3f65a7726544e81348ec4a5864 | f91657e4de01d17021cfb4f51331964b5275d899 | refs/heads/master | 2022-11-18T06:24:15.270000 | 2021-02-12T17:54:25 | 2021-02-12T17:54:25 | 146,978,106 | 1 | 0 | null | false | 2022-11-16T09:28:47 | 2018-09-01T07:33:34 | 2021-02-12T17:54:28 | 2022-11-16T09:28:44 | 3,475 | 1 | 0 | 2 | HTML | false | false | package com.app.geeks.arrays;
import java.util.HashMap;
import java.util.Map;
public class TrieDS {
private Node root;
static class Node {
char val;
Map<Character, Node> children = new HashMap<>();
Node(final char val) {
this.val = val;
}
char getVal() {
return val;
}
void setVal(final char val) {
this.val = val;
}
Map<Character, Node> getChildren() {
return children;
}
void setChildren(final Map<Character, Node> children) {
this.children = children;
}
}
public TrieDS() {
this.root = new Node(' ');
}
public void addString(String str) {
Node currNode = this.root;
boolean isAdded = false;
char[] chars = str.toCharArray();
int i = 0;
while (i < chars.length) {
if (currNode.children.containsKey(chars[i])) {
currNode = currNode.getChildren().get(chars[i]);
} else {
Node newNode = new Node(chars[i]);
currNode.getChildren().put(chars[i], newNode);
}
i++;
}
}
}
| UTF-8 | Java | 1,275 | java | TrieDS.java | Java | []
| null | []
| package com.app.geeks.arrays;
import java.util.HashMap;
import java.util.Map;
public class TrieDS {
private Node root;
static class Node {
char val;
Map<Character, Node> children = new HashMap<>();
Node(final char val) {
this.val = val;
}
char getVal() {
return val;
}
void setVal(final char val) {
this.val = val;
}
Map<Character, Node> getChildren() {
return children;
}
void setChildren(final Map<Character, Node> children) {
this.children = children;
}
}
public TrieDS() {
this.root = new Node(' ');
}
public void addString(String str) {
Node currNode = this.root;
boolean isAdded = false;
char[] chars = str.toCharArray();
int i = 0;
while (i < chars.length) {
if (currNode.children.containsKey(chars[i])) {
currNode = currNode.getChildren().get(chars[i]);
} else {
Node newNode = new Node(chars[i]);
currNode.getChildren().put(chars[i], newNode);
}
i++;
}
}
}
| 1,275 | 0.475294 | 0.47451 | 57 | 20.333334 | 18.596674 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 15 |
e5c85dc496d70f6c3a9919b6a784348fd5f8709f | 773,094,131,639 | f9c63949d20569367f8e19ae6d39d4a708c6d7f6 | /src/main/java/org/newspring/mapper/ZipcodeMapper.java | 98972156254f6cd6eb336e7a814cf2dff4b23cdb | []
| no_license | dauni6/mavenBoard-newMapping190222- | https://github.com/dauni6/mavenBoard-newMapping190222- | f90b2a1eb0597697dedcb2c006c2d49f220cc228 | 9c631753c79a1b7639a5d87148925f3038d2c90f | refs/heads/master | 2020-04-24T14:39:11.586000 | 2019-03-08T04:29:55 | 2019-03-08T04:29:55 | 172,029,344 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.newspring.mapper;
import java.util.List;
import org.newspring.domain.ZipcodeDTO;
public interface ZipcodeMapper {
//ÁýÄÚµå
public List<ZipcodeDTO> ziplist(String dong);
}
| WINDOWS-1252 | Java | 197 | java | ZipcodeMapper.java | Java | []
| null | []
| package org.newspring.mapper;
import java.util.List;
import org.newspring.domain.ZipcodeDTO;
public interface ZipcodeMapper {
//ÁýÄÚµå
public List<ZipcodeDTO> ziplist(String dong);
}
| 197 | 0.774869 | 0.774869 | 12 | 14.916667 | 16.829826 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 15 |
5537fedef5da810898a0ee84f300bb60a8ce6f7c | 773,094,129,025 | acfa080dc5abe1ad303f5d767760ed9e11c8e4ce | /src/main/java/com/example/demo/repo/ContinentRepository.java | e135008789f6dbd7bd747849f5d8d1857ef8ef7f | []
| no_license | ajayaks/flag-search-app | https://github.com/ajayaks/flag-search-app | 5a565ab2636d8e16a0272e346ac605b1b5486f91 | b3ea884606023f8501edbdd40dcb2a0daedb5c5c | refs/heads/master | 2020-09-06T08:23:44.920000 | 2020-01-18T14:51:05 | 2020-01-18T14:51:05 | 220,374,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Continent;
import com.example.demo.model.Country;
@Repository
public interface ContinentRepository extends JpaRepository<Continent, String>{
public List<Continent> findAll();
public Continent findByContinent(String continentName);
}
| UTF-8 | Java | 450 | java | ContinentRepository.java | Java | []
| null | []
| package com.example.demo.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Continent;
import com.example.demo.model.Country;
@Repository
public interface ContinentRepository extends JpaRepository<Continent, String>{
public List<Continent> findAll();
public Continent findByContinent(String continentName);
}
| 450 | 0.802222 | 0.802222 | 18 | 24 | 25.057711 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 15 |
0eea81c575f52be57f10c869c49cd0a6977d4b57 | 3,908,420,253,924 | 47432f940ec502c16496d9f2add70c8536bf5173 | /src/net/andruszko/lepapp/db/LepProviderMetaData.java | 19731e536e244af2336ceae59405cb42b0cff7cc | []
| no_license | wtk300/LepApp | https://github.com/wtk300/LepApp | a8209775071736d35ac1458e302e8a8468361ba8 | 54c0912f37e7e9091b02da46e45d6efdf9d894ae | refs/heads/master | 2016-09-11T09:27:59.939000 | 2011-10-29T18:22:07 | 2011-10-29T18:22:07 | 2,544,335 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.andruszko.lepapp.db;
import android.net.Uri;
import android.provider.BaseColumns;
public class LepProviderMetaData {
public static final String AUTHORITY = "net.andruszko.provider.lepapp";
public static final String DB_NAME = "lepapp.db";
/**
* Opis pytania
*/
public static final String DB_TABLE_LEP_ITEM= "lepitem";
/**
* Słownik lepów
*/
public static final String DB_TABLE_DICTLEPSESSION = "dictlepsession";
/**
* Poprawna odpowiedź
*/
public static final String DB_TABLE_DICTCORRECTANS = "dictcorrectans";
/**
* język testu
*/
public static final String DB_TABLE_DICTLANGUAGE = "dictlanguage";
public static final String DB_TABLE_DICTLEPTYPE = "dictleptype";
public static final String DB_TABLE_DICTSUBSECTION = "dictsubsection";
public static final int DB_VERSION = 2;
public static final class LepItemsTableMetaData implements BaseColumns {
private LepItemsTableMetaData(){}
public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/smsitems");
public static final Uri CONTENT_URI_TO_SEND = Uri.parse("content://"+AUTHORITY+"/smsitemstosend");
/**
* wysłane i z potwierdzeniem
*/
public static final Uri CONTENT_URI_SENT_SMS = Uri.parse("content://"+AUTHORITY+"/sentsms");
/**
* wysłane ale bez potwierdzenia lub błędnie wyslane
*/
public static final Uri CONTENT_URI_SENT_WITHOUT_ACK = Uri.parse("content://"+AUTHORITY+"/withoutack");
public static final Uri CONTENT_URI_NEW_SMS = Uri.parse("content://"+AUTHORITY+"/newsms");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.andruszko.sms";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ibpolsoft.sms";
public static final String KEY_ID = "id"; // unikalne id
public static final String KEY_SESSION_ID = "session_id"; // id sesji
public static final String KEY_LEPTYPE_ID = "leptype_id"; // typ
public static final String KEY_SECTION_ID = "section_id";
public static final String KEY_LANG_ID = "lang_id"; // jezyk
public static final String KEY_QUESTION = "question"; // pytanie
public static final String KEY_POSITION = "position";
public static final String KEY_ANSWER_A = "answer_a";
public static final String KEY_ANSWER_B = "answer_b";
public static final String KEY_ANSWER_C = "answer_c";
public static final String KEY_ANSWER_D = "answer_d";
public static final String KEY_ANSWER_E = "answer_e";
// id poprawnej odpowiedzi
public static final String KEY_CORRECT_ANSWER_ID = "correctans_id";
}
public static final class DictCorrectAns implements BaseColumns {
public static final int ANS_A = 10;
public static final int ANS_B = 20;
public static final int ANS_C = 30;
public static final int ANS_D = 40;
public static final int ANS_E = 50;
}
public static final class DictLepSessionTableMetaData implements BaseColumns {
/**
* 10|pobrany (ale nie wysłany)
20|wyslany
30|odebrany
*/
/**
* pobrany lecz nie wysłany
*/
public static final int SESSION_1 = 10;
/**
* wysłany (bez potwierdzenia)
*/
public static final int SESSION_2 = 20;
/**
* wysłany i otrzymane potwiedzenie pozytywne
*/
public static final int SESSION_3 = 30;
}
} | UTF-8 | Java | 3,731 | java | LepProviderMetaData.java | Java | []
| null | []
| package net.andruszko.lepapp.db;
import android.net.Uri;
import android.provider.BaseColumns;
public class LepProviderMetaData {
public static final String AUTHORITY = "net.andruszko.provider.lepapp";
public static final String DB_NAME = "lepapp.db";
/**
* Opis pytania
*/
public static final String DB_TABLE_LEP_ITEM= "lepitem";
/**
* Słownik lepów
*/
public static final String DB_TABLE_DICTLEPSESSION = "dictlepsession";
/**
* Poprawna odpowiedź
*/
public static final String DB_TABLE_DICTCORRECTANS = "dictcorrectans";
/**
* język testu
*/
public static final String DB_TABLE_DICTLANGUAGE = "dictlanguage";
public static final String DB_TABLE_DICTLEPTYPE = "dictleptype";
public static final String DB_TABLE_DICTSUBSECTION = "dictsubsection";
public static final int DB_VERSION = 2;
public static final class LepItemsTableMetaData implements BaseColumns {
private LepItemsTableMetaData(){}
public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/smsitems");
public static final Uri CONTENT_URI_TO_SEND = Uri.parse("content://"+AUTHORITY+"/smsitemstosend");
/**
* wysłane i z potwierdzeniem
*/
public static final Uri CONTENT_URI_SENT_SMS = Uri.parse("content://"+AUTHORITY+"/sentsms");
/**
* wysłane ale bez potwierdzenia lub błędnie wyslane
*/
public static final Uri CONTENT_URI_SENT_WITHOUT_ACK = Uri.parse("content://"+AUTHORITY+"/withoutack");
public static final Uri CONTENT_URI_NEW_SMS = Uri.parse("content://"+AUTHORITY+"/newsms");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.andruszko.sms";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ibpolsoft.sms";
public static final String KEY_ID = "id"; // unikalne id
public static final String KEY_SESSION_ID = "session_id"; // id sesji
public static final String KEY_LEPTYPE_ID = "leptype_id"; // typ
public static final String KEY_SECTION_ID = "section_id";
public static final String KEY_LANG_ID = "lang_id"; // jezyk
public static final String KEY_QUESTION = "question"; // pytanie
public static final String KEY_POSITION = "position";
public static final String KEY_ANSWER_A = "answer_a";
public static final String KEY_ANSWER_B = "answer_b";
public static final String KEY_ANSWER_C = "answer_c";
public static final String KEY_ANSWER_D = "answer_d";
public static final String KEY_ANSWER_E = "answer_e";
// id poprawnej odpowiedzi
public static final String KEY_CORRECT_ANSWER_ID = "correctans_id";
}
public static final class DictCorrectAns implements BaseColumns {
public static final int ANS_A = 10;
public static final int ANS_B = 20;
public static final int ANS_C = 30;
public static final int ANS_D = 40;
public static final int ANS_E = 50;
}
public static final class DictLepSessionTableMetaData implements BaseColumns {
/**
* 10|pobrany (ale nie wysłany)
20|wyslany
30|odebrany
*/
/**
* pobrany lecz nie wysłany
*/
public static final int SESSION_1 = 10;
/**
* wysłany (bez potwierdzenia)
*/
public static final int SESSION_2 = 20;
/**
* wysłany i otrzymane potwiedzenie pozytywne
*/
public static final int SESSION_3 = 30;
}
} | 3,731 | 0.62221 | 0.615219 | 113 | 31.920355 | 30.864861 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.380531 | false | false | 15 |
970810648b295b6a3d51c2152032c6a6647f0a99 | 3,350,074,512,340 | 244d21c509e6d3739345d6be9bf03cbd94c1c077 | /vr222ed_assign2/MinecraftForPoorPeople.java | 61057133e3920a16799843e64ca54007cd34ce73 | []
| no_license | MrDeathITA/Java-Course | https://github.com/MrDeathITA/Java-Course | 8ebddc7afa2c45842ceb7747a1a1367c50a6785a | 293ab068e40c37ceb0cc6360841dd8c64841b235 | refs/heads/main | 2023-06-27T07:45:17.063000 | 2021-07-28T17:07:54 | 2021-07-28T17:07:54 | 390,435,347 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vr222ed_assign2;
import java.util.Scanner;
public class MinecraftForPoorPeople {
private static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Width of studs");
int width = s.nextInt();
System.out.println("Enter Height of studs");
int height = s.nextInt();
brick b = new brick(width, height);
b.makeCore(b.width);
b.makeUpper(b.width, b.counter);
b.makeLower(b.width, b.counter);
System.out.print(b.upper + "\n");
for (int i=0; i<height; i++) {
System.out.printf(b.core + "\n");
}
System.out.print(b.lower);
}
//counter counts empty spaces, add dots for total wall
public static void makeBrick(int width, int height) {
}
}
class brick {
int width;
int height;
int counter;
String[][] bricc;
String upper = "";
String core = "";
String lower = "";
static String dot = "●";
static String LCorner = "┌";
static String RCorner = "┐";
static String LDCorner = "└";
static String RDCorner = "┘";
static String VWall = "│";
static String HWall = "─";
public brick(int width, int height) {
this.width=width;
this.height=height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public void makeCore(int width) {
this.core += VWall;
for (int i = 0; i<width; i++) {
this.core += dot;
if (i<width-1) {
this.core += " ";
this.counter++;}
}
this.core += VWall;
}
public void makeLower(int width, int counter) {
this.lower += LDCorner;
for (int i = 0; i < width+counter; i++) {
this.lower += HWall;
}
this.lower += RDCorner;
}
public void makeUpper(int width, int counter) {
this.upper += LCorner;
for (int i = 0; i < width+counter; i++) {
this.upper += HWall;
}
this.upper += RCorner;
}
}
| UTF-8 | Java | 2,132 | java | MinecraftForPoorPeople.java | Java | []
| null | []
| package vr222ed_assign2;
import java.util.Scanner;
public class MinecraftForPoorPeople {
private static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Width of studs");
int width = s.nextInt();
System.out.println("Enter Height of studs");
int height = s.nextInt();
brick b = new brick(width, height);
b.makeCore(b.width);
b.makeUpper(b.width, b.counter);
b.makeLower(b.width, b.counter);
System.out.print(b.upper + "\n");
for (int i=0; i<height; i++) {
System.out.printf(b.core + "\n");
}
System.out.print(b.lower);
}
//counter counts empty spaces, add dots for total wall
public static void makeBrick(int width, int height) {
}
}
class brick {
int width;
int height;
int counter;
String[][] bricc;
String upper = "";
String core = "";
String lower = "";
static String dot = "●";
static String LCorner = "┌";
static String RCorner = "┐";
static String LDCorner = "└";
static String RDCorner = "┘";
static String VWall = "│";
static String HWall = "─";
public brick(int width, int height) {
this.width=width;
this.height=height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public void makeCore(int width) {
this.core += VWall;
for (int i = 0; i<width; i++) {
this.core += dot;
if (i<width-1) {
this.core += " ";
this.counter++;}
}
this.core += VWall;
}
public void makeLower(int width, int counter) {
this.lower += LDCorner;
for (int i = 0; i < width+counter; i++) {
this.lower += HWall;
}
this.lower += RDCorner;
}
public void makeUpper(int width, int counter) {
this.upper += LCorner;
for (int i = 0; i < width+counter; i++) {
this.upper += HWall;
}
this.upper += RCorner;
}
}
| 2,132 | 0.626534 | 0.622285 | 112 | 17.892857 | 15.565161 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.883929 | false | false | 15 |
051fbf9cec55b3ec76cac12fb7f6df40416c8ad3 | 25,735,444,051,969 | c51fafc55d3680551d162afb34ded81197151efc | /src/test/java/com/martinetherton/ons/domain/PersonTest.java | feb1a0ab0cfba8d821891a8dd575cef193c1da0e | []
| no_license | metherton/ons-be | https://github.com/metherton/ons-be | c1075563ce809cf983b286d9c368f0bdd6d7a550 | ef6589d3dd2386591ceb97953e9f7c5fde74ed58 | refs/heads/master | 2023-01-03T12:24:36.111000 | 2020-10-27T14:33:42 | 2020-10-27T14:33:42 | 295,844,674 | 1 | 1 | null | false | 2020-10-27T13:32:05 | 2020-09-15T20:42:51 | 2020-09-30T18:49:31 | 2020-10-27T13:32:04 | 18 | 0 | 0 | 0 | Java | false | false | package com.martinetherton.ons.domain;
import org.junit.jupiter.api.Test;
public class PersonTest {
@Test
public void testPersonSetters() {
Person person = new Person("martin", "etherton");
}
}
| UTF-8 | Java | 219 | java | PersonTest.java | Java | [
{
"context": "onSetters() {\n Person person = new Person(\"martin\", \"etherton\");\n\n }\n}\n",
"end": 194,
"score": 0.9994943141937256,
"start": 188,
"tag": "NAME",
"value": "martin"
},
{
"context": ") {\n Person person = new Person(\"martin\", \"etherton\");\n\n }\n}\n",
"end": 206,
"score": 0.9997746348381042,
"start": 198,
"tag": "NAME",
"value": "etherton"
}
]
| null | []
| package com.martinetherton.ons.domain;
import org.junit.jupiter.api.Test;
public class PersonTest {
@Test
public void testPersonSetters() {
Person person = new Person("martin", "etherton");
}
}
| 219 | 0.675799 | 0.675799 | 13 | 15.846154 | 18.985201 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 15 |
6c4c049098998c00a28a5446314a8e67bdcc3701 | 25,735,444,053,795 | 84f90555d679ea55ef53acf89b25ec2191846204 | /MIPS_MP/src/machine/IFID.java | 523cbe78b4741b5a1749b035497981735fc83b88 | []
| no_license | chesteribarrientos/MIPS_MP | https://github.com/chesteribarrientos/MIPS_MP | 0e41f2a19585ab687b45aebceaed45b510d4ab0d | d27e622a56bd76bd3356763633bad42113e52651 | refs/heads/master | 2020-01-23T21:56:02.874000 | 2016-12-13T06:12:40 | 2016-12-13T06:12:40 | 74,728,901 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package machine;
import utils.Stringify;
/**
* @author Chester
*
*/
public class IFID extends Pipeline {
private long npc;
public long NPC() {
return npc;
}
public void setNPC(long value) {
npc = value;
}
public String toString() {
return "IF.IR: " + Stringify.as32bitHex(instructionRegister) + "\nNPC: " + Stringify.as64bitHex(npc);
}
}
| UTF-8 | Java | 372 | java | IFID.java | Java | [
{
"context": " machine;\n\nimport utils.Stringify;\n\n/**\n * @author Chester\n *\n */\npublic class IFID extends Pipeline {\n\n\tpri",
"end": 77,
"score": 0.9947028160095215,
"start": 70,
"tag": "USERNAME",
"value": "Chester"
}
]
| null | []
| /**
*
*/
package machine;
import utils.Stringify;
/**
* @author Chester
*
*/
public class IFID extends Pipeline {
private long npc;
public long NPC() {
return npc;
}
public void setNPC(long value) {
npc = value;
}
public String toString() {
return "IF.IR: " + Stringify.as32bitHex(instructionRegister) + "\nNPC: " + Stringify.as64bitHex(npc);
}
}
| 372 | 0.645161 | 0.634409 | 27 | 12.777778 | 20.704863 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703704 | false | false | 15 |
61c8f312d89ef21cd1910807f828dbfe13ce2ac7 | 1,872,605,761,960 | 702172b3d461126de3d58d8eafc75faac961b017 | /src/main/java/com/example/demo/app/mapper/package-info.java | 7380df15b6e5591ddd4c339b62a9c295a3c5c977 | []
| no_license | Cepr0/sb-db-sample | https://github.com/Cepr0/sb-db-sample | 85f52210e5c45b345c4b855fb4639888a96995e4 | f89338af16fcca8b2784b0b3ac758c1e200ffbe7 | refs/heads/master | 2021-04-21T23:03:09.681000 | 2020-04-12T20:45:58 | 2020-04-12T20:45:58 | 249,824,060 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | @org.springframework.lang.NonNullApi
package com.example.demo.app.mapper;
| UTF-8 | Java | 75 | java | package-info.java | Java | []
| null | []
| @org.springframework.lang.NonNullApi
package com.example.demo.app.mapper;
| 75 | 0.826667 | 0.826667 | 2 | 36 | 0 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
5bc1f2dd98b7d19bed0fa1a864ad65bf6daec5ca | 20,598,663,167,547 | f79f79976ab4c5fd0d48fc04a765cf545a651f1c | /app/src/main/java/kr/co/bsmsoft/beple_shop/adapter/ContactGroupListAdapter.java | 7082552dbfec0aea6bd36245766155a83d82b136 | []
| no_license | junhwanu/beple | https://github.com/junhwanu/beple | 2c073e8a9cf72a3d1f9858c6049136ad1c56a265 | 35b1e35ecd4bfe1b787a9722e5c13b2fcc35cf12 | refs/heads/master | 2020-06-18T19:21:06.725000 | 2017-07-26T10:25:26 | 2017-07-26T10:25:26 | 74,744,660 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.co.bsmsoft.beple_shop.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import kr.co.bsmsoft.beple_shop.R;
import kr.co.bsmsoft.beple_shop.common.NetDefine;
import kr.co.bsmsoft.beple_shop.model.ContactGroupModel;
/**
* Created by Office on 2016-11-18.
*/
public class ContactGroupListAdapter extends ArrayAdapter<ContactGroupModel> implements NetDefine {
private final static String TAG = "ContactGroupListAdapter";
private Context context;
private ArrayList<ContactGroupModel> items = new ArrayList<ContactGroupModel>();
private LayoutInflater vi;
private ListView mListView;
public ContactGroupListAdapter(Context context, ArrayList<ContactGroupModel> data, ListView listview) {
super(context, R.layout.cell_customer_list);
this.context = context;
this.items = data;
this.mListView = listview;
this.vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
class ViewHolder {
TextView txtGroupName;
TextView txtGroupCount;
CheckBox chkSelected;
}
public void addAll(ArrayList<ContactGroupModel> groups) {
items.addAll(groups);
notifyDataSetChanged();
}
public ArrayList<ContactGroupModel> getItems() {
return items;
}
public void addItem(ContactGroupModel item) {
items.add(item);
}
public void removeItem(int position) {
items.remove(position);
}
public ContactGroupModel getItem(int position) {
return items.get(position);
}
public int getCount() {
return items.size();
}
public void clear() {
items.clear();
}
private View createView(int position) {
ContactGroupListAdapter.ViewHolder holder = null;
View v = null;
holder = new ContactGroupListAdapter.ViewHolder();
v = vi.inflate(R.layout.cell_customer_list, null);
holder.txtGroupName = (TextView) v.findViewById(R.id.txtCustomerName);
holder.txtGroupCount = (TextView) v.findViewById(R.id.txtPhone);
holder.chkSelected = (CheckBox) v.findViewById(R.id.checkBox);
//holder.chkSelected.setOnClickListener(mOnMenuClickListener);
v.setTag(holder);
return v;
}
private View.OnClickListener mOnMenuClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
View parent = (View)v.getParent();
int position = mListView.getPositionForView(parent);
ContactGroupModel customer = items.get(position);
CheckBox chk = (CheckBox)v;
if (chk.isChecked()) {
customer.isSelected(1);
}else{
customer.isSelected(0);
}
}
};
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactGroupListAdapter.ViewHolder holder = null;
View v = convertView;
ContactGroupModel item = items.get(position);
if(!item.isVisible()) return vi.inflate(R.layout.cell_null_item, null);
v = createView(position);
holder = (ContactGroupListAdapter.ViewHolder) v.getTag();
holder.txtGroupName.setText(item.getGroupName());
holder.txtGroupCount.setText(String.valueOf(item.getGroupMemberCount()));
if (item.isSelected() == 1) {
holder.chkSelected.setChecked(true);
}else{
holder.chkSelected.setChecked(false);
}
return v;
}
} | UTF-8 | Java | 3,973 | java | ContactGroupListAdapter.java | Java | []
| null | []
| package kr.co.bsmsoft.beple_shop.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import kr.co.bsmsoft.beple_shop.R;
import kr.co.bsmsoft.beple_shop.common.NetDefine;
import kr.co.bsmsoft.beple_shop.model.ContactGroupModel;
/**
* Created by Office on 2016-11-18.
*/
public class ContactGroupListAdapter extends ArrayAdapter<ContactGroupModel> implements NetDefine {
private final static String TAG = "ContactGroupListAdapter";
private Context context;
private ArrayList<ContactGroupModel> items = new ArrayList<ContactGroupModel>();
private LayoutInflater vi;
private ListView mListView;
public ContactGroupListAdapter(Context context, ArrayList<ContactGroupModel> data, ListView listview) {
super(context, R.layout.cell_customer_list);
this.context = context;
this.items = data;
this.mListView = listview;
this.vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
class ViewHolder {
TextView txtGroupName;
TextView txtGroupCount;
CheckBox chkSelected;
}
public void addAll(ArrayList<ContactGroupModel> groups) {
items.addAll(groups);
notifyDataSetChanged();
}
public ArrayList<ContactGroupModel> getItems() {
return items;
}
public void addItem(ContactGroupModel item) {
items.add(item);
}
public void removeItem(int position) {
items.remove(position);
}
public ContactGroupModel getItem(int position) {
return items.get(position);
}
public int getCount() {
return items.size();
}
public void clear() {
items.clear();
}
private View createView(int position) {
ContactGroupListAdapter.ViewHolder holder = null;
View v = null;
holder = new ContactGroupListAdapter.ViewHolder();
v = vi.inflate(R.layout.cell_customer_list, null);
holder.txtGroupName = (TextView) v.findViewById(R.id.txtCustomerName);
holder.txtGroupCount = (TextView) v.findViewById(R.id.txtPhone);
holder.chkSelected = (CheckBox) v.findViewById(R.id.checkBox);
//holder.chkSelected.setOnClickListener(mOnMenuClickListener);
v.setTag(holder);
return v;
}
private View.OnClickListener mOnMenuClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
View parent = (View)v.getParent();
int position = mListView.getPositionForView(parent);
ContactGroupModel customer = items.get(position);
CheckBox chk = (CheckBox)v;
if (chk.isChecked()) {
customer.isSelected(1);
}else{
customer.isSelected(0);
}
}
};
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactGroupListAdapter.ViewHolder holder = null;
View v = convertView;
ContactGroupModel item = items.get(position);
if(!item.isVisible()) return vi.inflate(R.layout.cell_null_item, null);
v = createView(position);
holder = (ContactGroupListAdapter.ViewHolder) v.getTag();
holder.txtGroupName.setText(item.getGroupName());
holder.txtGroupCount.setText(String.valueOf(item.getGroupMemberCount()));
if (item.isSelected() == 1) {
holder.chkSelected.setChecked(true);
}else{
holder.chkSelected.setChecked(false);
}
return v;
}
} | 3,973 | 0.659451 | 0.656683 | 147 | 26.034014 | 25.675213 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482993 | false | false | 15 |
35dcd42f7624b1cba5a7a8339930faa777fcef1e | 21,251,498,195,830 | c559803b285e4fd7f6b31e48b70fb0c69c32b196 | /src/classes/ConnectionBDD.java | 87c281a3fb077c4e4f0b0fdc41da9bf2211ddf85 | []
| no_license | Mynghado/2017_projetFX | https://github.com/Mynghado/2017_projetFX | 2256fd55872e7fab82697d2fddcf9a1b2dd302be | 60259f6d441ec8749b596955c86f9c5f2b20f85d | refs/heads/master | 2021-01-20T00:45:15.169000 | 2017-04-25T16:03:56 | 2017-04-25T16:03:56 | 89,179,396 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package classes;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionBDD {
// URL de connexion
private static String url = "jdbc:mysql://localhost/bdd_stage";
// Nom du user
private static String user = "root";
// Mot de passe de l'utilisateur
private static String passwd = "";
// Objet Connection
private static java.sql.Connection connect;
// Méthode pour récupérer l'instance de connexion, si elle n'éxiste pas déjà, on la créé.
public static java.sql.Connection getCo(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(connect == null){
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connect;
}
}
| ISO-8859-1 | Java | 914 | java | ConnectionBDD.java | Java | []
| null | []
| package classes;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionBDD {
// URL de connexion
private static String url = "jdbc:mysql://localhost/bdd_stage";
// Nom du user
private static String user = "root";
// Mot de passe de l'utilisateur
private static String passwd = "";
// Objet Connection
private static java.sql.Connection connect;
// Méthode pour récupérer l'instance de connexion, si elle n'éxiste pas déjà, on la créé.
public static java.sql.Connection getCo(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(connect == null){
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connect;
}
}
| 914 | 0.665563 | 0.665563 | 35 | 23.885714 | 20.585392 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.942857 | false | false | 15 |
61e7b400487507b8c390c03ba751da458925310c | 21,096,879,378,976 | 7e055627b6e3d94d601ec8f540048e17400379d4 | /code/src/main/java/personnel/officers/OfficerMachine.java | b78146d88d4a90d71e0bf2fdd60f1fccfae0b2af | []
| no_license | larsommen/deap_sea_crew_scheduling | https://github.com/larsommen/deap_sea_crew_scheduling | c3c9877d99ecbea6d8e41602e561e8c377084721 | bbc2bf98d40c4a5ab9b5593a9e60a937f12650f4 | refs/heads/master | 2016-09-18T21:45:16.762000 | 2016-09-18T10:44:17 | 2016-09-18T10:44:17 | 65,990,398 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package personnel.officers;
public class OfficerMachine extends Officers {
} | UTF-8 | Java | 82 | java | OfficerMachine.java | Java | []
| null | []
| package personnel.officers;
public class OfficerMachine extends Officers {
} | 82 | 0.780488 | 0.780488 | 8 | 9.375 | 16.370228 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 15 |
f0de74ac7e440057a65b188306e081fce7db86fc | 19,799,799,257,769 | 6a038125fddda61bae8950f7e0b6edb8b6d6a019 | /src/com/ecannetwork/tech/controller/VwsurveyController.java | 67eca0f6fb723f3b399a42d81329ca389e42803d | []
| no_license | xiaolin8/vwac | https://github.com/xiaolin8/vwac | f9bca83a5c2ef5f3bb3660622b44e05568592fd6 | 273db6f8472dbe66d814dbc8a895e4c57c317188 | refs/heads/master | 2016-09-13T21:13:22.305000 | 2016-03-15T14:09:03 | 2016-03-15T14:09:03 | 57,036,872 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ecannetwork.tech.controller;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ecannetwork.core.i18n.I18N;
import com.ecannetwork.core.module.controller.AjaxResponse;
import com.ecannetwork.core.module.controller.DateBindController;
import com.ecannetwork.core.module.service.CommonService;
import com.ecannetwork.core.util.CoreConsts;
import com.ecannetwork.core.util.ExecuteContext;
import com.ecannetwork.core.util.QRCodeUtil;
import com.ecannetwork.dto.core.EcanUser;
import com.ecannetwork.dto.tech.MwVotecourse;
import com.ecannetwork.dto.tech.MwVotekey;
import com.ecannetwork.dto.tech.MwVoteresult;
import com.ecannetwork.dto.tech.MwVotesubject;
import com.ecannetwork.dto.tech.MwVotesystem;
import com.ecannetwork.dto.tech.SubjectUnit;
import com.ecannetwork.dto.tech.TechTest;
import com.ecannetwork.dto.tech.TechTestAnswer;
import com.ecannetwork.dto.tech.TechTestDb;
import com.ecannetwork.dto.tech.TechTrainCourse;
import com.ecannetwork.dto.tech.TechUserMessage;
import com.ecannetwork.tech.service.TestDbService;
import com.ecannetwork.tech.service.TrainPlanService;
import com.ecannetwork.tech.util.FileUtils;
@Controller
@RequestMapping("/vwsurvey")
public class VwsurveyController extends DateBindController
{
@Autowired
private CommonService commonService;
@Autowired
private TestDbService dbService;
private String tmpPath = "http://123.57.17.189:8084/";
@RequestMapping("index")
public String index(Model model)
{
@SuppressWarnings("unchecked")
List<MwVotecourse> list = commonService.list("from MwVotecourse t order by id desc");// 列表
model.addAttribute("dblist", list);
return "tech/vwsurvey/index";
}
@RequestMapping("del")
public @ResponseBody
AjaxResponse del(Model model, @RequestParam(value = "id", required = true) String id)
{
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
commonService.deleteTX(MwVotecourse.class, id);
return new AjaxResponse(true, "i18n.commit.del.success");
}
return new AjaxResponse(true, "i18n.commit.del.success");
}
@RequestMapping("copy")
public @ResponseBody
AjaxResponse copy(Model model, @RequestParam(value = "id", required = true) String id)
{
// 先查出当前记录
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
mwVotecourse.setId(null);// id是数据库自动生成的
mwVotecourse.setCTitle(mwVotecourse.getCTitle() + "_复制");// title是原来的title+"_复制"
commonService.saveTX(mwVotecourse);// 作为新的记录保存
return new AjaxResponse(true, "复制成功");
}
return new AjaxResponse(true, "复制成功");
}
@RequestMapping("build")
public @ResponseBody
AjaxResponse build(Model model, @RequestParam(value = "id", required = true) String id, @RequestParam(value = "NSysId", required = true) String NSysId)
{
// 先查出当前记录
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
// 读votetemplate文件
String votetemp = "";
String idTemplateFile = ExecuteContext.realPath() + "mw/onlinesurvey/votetemplate_" + id + ".htm";// 对应id的模板
String defaultTemplateFile = ExecuteContext.realPath() + "mw/onlinesurvey/votetemplate.htm";// 默认的模板
if (FileUtils.fileExists(idTemplateFile))
{
votetemp = FileUtils.readFile(idTemplateFile) + "\n";
}
else
{
votetemp = FileUtils.readFile(defaultTemplateFile) + "\n";
}
votetemp = votetemp.replace("{id}", mwVotecourse.getId())
.replace("{path}", ExecuteContext.realPath())
.replace("{title}", mwVotecourse.getCTitle())
.replace("{course}", mwVotecourse.getCCourse())
.replace("{teacher}", mwVotecourse.getCTearcher())
.replace("{address}", mwVotecourse.getCAdrees())
.replace("{starttime}", mwVotecourse.getDtStartDate()==null?"":mwVotecourse.getDtStartDate().toString())
.replace("{endtime}", mwVotecourse.getDtOverDate()==null?"":mwVotecourse.getDtOverDate().toString())
.replace("{coursestarttime}", mwVotecourse.getCourseStart() == null ? "" : mwVotecourse.getCourseStart().toString())
.replace("{courseendtime}", mwVotecourse.getCourseEnd() == null ? "" : mwVotecourse.getCourseEnd().toString());
// 生成内容
votetemp = votetemp.replace("{Content}", pubBuildHtml(mwVotecourse).replace("{Images}", ExecuteContext.realPath() + "/mw/onlinesurvey/SysImages"));
// 生成的新的文件,以id命名
String newFile = ExecuteContext.realPath() + "mw/onlinesurvey/" + id + ".html";
String desFilePath = ExecuteContext.realPath() + "/mw/onlinesurvey/qr";
// 生成当前问卷的二维码
if (votetemp.contains("{QR}"))
{
try
{
QRCodeUtil.encode(newFile, "", ExecuteContext.realPath() + "/mw/onlinesurvey/qr/", true, id);// 生成二维码
// 替换二维码位置
votetemp = votetemp.replace("{QR}", "<img src=\"" + ExecuteContext.realPath() + "/mw/onlinesurvey/qr/" + id + ".jpg\" width=\"100\" height=\"100\" />");
}
catch (Exception e)
{
e.printStackTrace();
}
}
File file = new File(newFile);
if (file.exists())
{
file.delete();
}
FileUtils.writeFile(newFile, votetemp);
System.out.println("build create file : " + newFile);
return new AjaxResponse(true, "生成投票问卷成功");
}
return new AjaxResponse(false, "生成投票问卷失败");
}
@RequestMapping("add")
public String add(Model model)
{
// 绑定调查模板下拉列表数据
List<MwVotesystem> mwVotesystem = this.commonService.list("from MwVotesystem order by id DESC");
model.addAttribute("list", mwVotesystem);
// 绑定培训课程下拉列表数据
List<TechTrainCourse> CCourselist = this.commonService.list("from com.ecannetwork.dto.tech.TechTrainCourse t where t.status=?", CoreConsts.YORN.YES);
model.addAttribute("CCourselist", CCourselist);
return "tech/vwsurvey/save";
}
@RequestMapping("edit")
public String edit(Model model, @RequestParam(value = "id", required = true) String id)
{
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
model.addAttribute("dto", mwVotecourse);
// 绑定调查模板下拉列表数据
List<MwVotesystem> mwVotesystem = this.commonService.list("from MwVotesystem order by id DESC");
model.addAttribute("list", mwVotesystem);
// 绑定培训课程下拉列表数据
List<TechTrainCourse> CCourselist = this.commonService.list("from com.ecannetwork.dto.tech.TechTrainCourse t where t.status=?", CoreConsts.YORN.YES);
model.addAttribute("CCourselist", CCourselist);
return "tech/vwsurvey/save";
}
// //选择老师
@RequestMapping("listteachers")
public String listteachers(Model model)
{
List<EcanUser> teachers = this.commonService.list("from EcanUser e where e.roleId='teacher' and e.status = '1'");
model.addAttribute("list", teachers);
return "tech/message/selectteachers";
}
@RequestMapping("save")
public @ResponseBody
AjaxResponse save(Model model, @Valid MwVotecourse mwVotecourse, BindingResult result, HttpServletRequest request)
{
// 获取是否验证checkbox的值。当选中时,值为on,否则为null
String checkNcodeString = request.getParameter("NCodeSurvey");
if (checkNcodeString == null)
{
mwVotecourse.setNCodeSurvey(0);
}
else
{
mwVotecourse.setNCodeSurvey(1);
}
if (mwVotecourse.getId() == null || mwVotecourse.getId() == "")
{
commonService.saveTX(mwVotecourse);// 保存
return new AjaxResponse(true, I18N.parse("i18n.commit.success"));
}
else
{
commonService.updateTX(mwVotecourse);// 更新
return new AjaxResponse(true, I18N.parse("i18n.commit.success"));
}
}
// 生成调查问卷内容
public String pubBuildHtml(MwVotecourse mwVotecourse)
{
StringBuffer strResult = new StringBuffer();// 最终的结果
strResult.append("<form name=\"VWVoteForm\" id=\"VWVoteForm\" method=\"post\" action=\"/Portal2012/techc/vwsurvey/getresult\" >");
strResult.append("<input name=\"VoteId\" type=\"hidden\" value=\"" + mwVotecourse.getId() + "\" /><input name=\"SubjectId\" type=\"hidden\" value=\"" + mwVotecourse.getNSysId() + "\" />");
strResult.append("<div class=\"survey\">");
Integer xh = 1;
@SuppressWarnings("unchecked")
List<MwVotesubject> list = commonService.list("from MwVotesubject where parentid=0 and NSysId=? order by id desc", mwVotecourse.getNSysId());// 问卷数据
if (!list.isEmpty())
{
for (MwVotesubject mwVotesubject : list)
{
Integer jj = 0;
List<SubjectUnit> subdata = GetSubToKey(mwVotecourse.getNSysId(), mwVotesubject.getParentid(), "");
if (!subdata.isEmpty())
{
for (SubjectUnit subjectUnit : subdata)
{
jj++;
strResult.append("<div class=\"qa" + ((xh * jj > 1) ? " nodisplay" : "") + " \">" + "<h2>" + subjectUnit.getC_SubTitle().replace("\n", "<br/>") + "</h2>" + "<p>"
+ String.valueOf(xh) + ((jj > 0) ? "-" + jj : "") + ". " + subjectUnit.getC_SubTitle().replace("\n", "<br/>") + "</p>");
strResult.append(GetTable(subjectUnit));
strResult.append("</div>");
}
xh++;
}
}
}
// 增加验证码功能
// if (mwVotecourse.getNCodeSurvey().equals(1))
// {
// strResult.append("<div class=\"qa nodisplay\"><p>" +
// String.valueOf(xh++) + ". 请输入图片中文字</p>");
// strResult.append("<input type=\"text\" name=\"Check\" style=\"width:100px\" /> <img id=\"imgObj\" alt=\"验证码\" src=\"${ctxPath}/techc/vwsurvey/code\" /><br/>");
// strResult.append("</div>");
// }
strResult.append("</div><div class=\"btn\"> <a id=\"btnpre\">上一页<br />Previous</a> <span></span> <a id=\"btnnext\">下一页<br />Next</a>");
strResult.append(" </div>");
// strResult.append("<br><br><input type=\"submit\" name=\"Submit\" value=\"提 交\" style=\"width:100px\"></form>");
strResult.append("</form>");
return strResult.toString();
}
public List<SubjectUnit> GetSubToKey(final Integer sysid, final Integer parentid, final String where)
{
final List list = new ArrayList();
// 用此种方法来执行sql语句
this.commonService.executeCallbackTX(new HibernateCallback()
{
@Override
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
try
{
Connection conn = session.connection();
String cmdtext = "SELECT u.N_SubId,s.N_SysId,s.N_SubId as subid,s.C_SubTitle,s.Parentid,s.N_Need FROM mw_voteunit AS u INNER JOIN mw_votesubject AS s ON u.N_SubId = s.N_Type where 1=1 ";
if (sysid > 0)
{
cmdtext += " and u.N_SysId =" + sysid;
}
if (parentid > 0)
{
cmdtext += " and s.Parentid =" + parentid;
}
cmdtext += where + " order by s.N_OrderId,s.N_SubId";
PreparedStatement pst = conn.prepareStatement(cmdtext);
ResultSet rs = pst.executeQuery();
while (rs.next())
{
SubjectUnit unit = new SubjectUnit();
unit.setN_SubId(rs.getInt("N_SubId"));
unit.setN_SysId(rs.getInt("N_SysId"));
unit.setSubid(rs.getInt("subid"));
unit.setC_SubTitle(rs.getString("C_SubTitle"));
unit.setParentid(rs.getInt("Parentid"));
unit.setN_Need(rs.getInt("N_Need"));
list.add(unit);
}
pst.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
});
return list;
}
private String GetTable(SubjectUnit subjectUnit)
{
List<MwVotekey> list = commonService.list("from MwVotekey where NSubId=? order by NOrderId,id desc", subjectUnit.getN_SubId());
StringBuffer strUnitBuffer = new StringBuffer();// 返回的字符串
int num2 = 0;
if (!list.isEmpty())
{
for (MwVotekey mwVotekey : list)
{
num2++;
Integer ntype = mwVotekey.getNType();
switch (ntype)
{
case 1:
if (subjectUnit.getN_Need().equals(1))
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + " <input type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" check=\"^\\S+$\" warning=\""
+ mwVotekey.getCKeyTitle() + "不能为空\" >");
}
else
{
if (!mwVotekey.getCRule().isEmpty() && !mwVotekey.getCRule().startsWith("不限制"))
{
String strArray17[] = mwVotekey.getCRule().split("`");
if (strArray17[1] != "*")
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + "" + "<input type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" check=\"" + strArray17[1]
+ "\" warning=\"" + mwVotekey.getCKeyTitle() + "格式不正确,应填 " + strArray17[0] + "\" >");
}
else
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + "" + "<input type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\">");
}
}
else
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + " <input type=\"text\" name=\" " + String.valueOf(subjectUnit.getSubid()) + "\">");
}
}
break;
case 2:
if (num2 == 1)
{
strUnitBuffer.append("<ul class=\"option\">");
}
if (subjectUnit.getN_Need().equals(1))
{
if (num2 != 1)
{
strUnitBuffer.append("<li><label><input type=\"radio\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
else
{
strUnitBuffer.append("<li><label><input type=\"radio\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId())
+ "\" check=\"^0$\" warning=\"" + subjectUnit.getC_SubTitle() + "最少选一项\" >" + mwVotekey.getCKeyTitle() + "</label></li>");
}
}
else
{
strUnitBuffer.append("<li><label><input type=\"radio\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
if (num2 == list.size())
{
strUnitBuffer.append("</ul>");
}
break;
case 3:
if (num2 == 1)
{
strUnitBuffer.append("<ul class=\"option\">");
}
if (subjectUnit.getN_Need().equals(1))
{
if (num2 == 1)
{
strUnitBuffer.append("<li><label><input type=\"checkbox\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId())
+ "\" check=\"^0{1,}$\" warning=\"" + subjectUnit.getC_SubTitle() + "最少选一项或以上\">" + mwVotekey.getCKeyTitle() + "</label></li>");
}
else
{
strUnitBuffer.append("<li><label><input type=\"checkbox\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
}
else
{
strUnitBuffer.append("<li><label><input type=\"checkbox\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
if (num2 == list.size())
{
strUnitBuffer.append("</ul>");
}
break;
case 4:
if (num2 == 1)
{
strUnitBuffer.append("<select name=\"" + String.valueOf(subjectUnit.getSubid()) + "\"><option value=\"" + String.valueOf(mwVotekey.getId()) + "\" selected=\"selected\">"
+ mwVotekey.getCKeyTitle() + "</option>");
}
else if (num2 == list.size())
{
strUnitBuffer.append("<option value=\"" + String.valueOf(subjectUnit.getSubid()) + "\" >" + mwVotekey.getCKeyTitle() + "</option></select>");
}
else
{
strUnitBuffer.append("<option value=\"" + String.valueOf(subjectUnit.getSubid()) + "\" >" + mwVotekey.getCKeyTitle() + "</option>");
}
break;
case 5:
if (subjectUnit.getN_Need().equals(1))
{
strUnitBuffer.append("<p>" + mwVotekey.getCKeyTitle() + "<textarea name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" rows=\"5\" check=\"^[\\s|\\S]{2,}$\" warning=\""
+ mwVotekey.getCKeyTitle() + "不能为空,且不能少于3个字\"></textarea></p>");
break;
}
else
{
if (!mwVotekey.getCRule().isEmpty() && !mwVotekey.getCRule().startsWith("不限制"))
{
String strArray3[] = mwVotekey.getCRule().split("`");
strUnitBuffer.append("<p>" + mwVotekey.getCKeyTitle() + "<textarea type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" check=\"" + strArray3[1]
+ "\" warning=\"" + mwVotekey.getCKeyTitle() + "格式不正确,应为 " + strArray3[0] + "\" ></textarea></p>");
}
else
{
strUnitBuffer.append("<p>" + mwVotekey.getCKeyTitle() + "<textarea name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" rows=\"5\" ></textarea></p>");
}
}
break;
}
}
}
return strUnitBuffer.toString();
}
@RequestMapping("pushreport")
public String pushreport(Model model, @RequestParam(value = "id", required = true) String id)
{
System.out.println("pushreport : " + id);
// 先查出当前记录
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
// TODO:temp
String webpath = this.tmpPath + "mw/onlinesurvey/" + id + ".html";// 路径
try
{
QRCodeUtil.encode(webpath, "", ExecuteContext.realPath() + "/mw/onlinesurvey/qr/", true, id);// 生成二维码
}
catch (Exception e)
{
e.printStackTrace();
}
// String qrPath = ExecuteContext.realPath() +
// "mw/onlinesurvey/qr/" + id + ".jpg";
String qrPath = ExecuteContext.contextPath() + "/mw/onlinesurvey/qr/" + id + ".jpg";
String content = pubBuildHtml(mwVotecourse);// 代码内容
model.addAttribute("webpath", webpath);
model.addAttribute("qrPath", qrPath);
model.addAttribute("content", content);
}
return "tech/vwsurvey/pushreport";
}
String hostIP = "";// 当前页面客户端的IP
@RequestMapping("getresult")
public @ResponseBody
void getresult(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException
{
hostIP = request.getRemoteAddr();
Integer id = Integer.valueOf(request.getParameter("VoteId"));
Integer sysId = Integer.valueOf(request.getParameter("SubjectId"));
if (id == null && sysId == null)
{
// return new AjaxResponse(true, "参数错误!");
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('参数错误!')</script>");
out.print("<script>location.href='/Portal2012/mw/onlinesurvey/" + id + ".html'</script>");
out.close();
}
int num2;
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(String.valueOf(id), MwVotecourse.class);
if (mwVotecourse.getDtStartDate().after(new Date()))// 调查的时间开始时间在当前时间后
{
// return new AjaxResponse(true, "调查已经过期!");
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('调查已经过期!')</script>");
out.print("<script>location.href='/Portal2012/mw/onlinesurvey/" + id + ".html'</script>");
out.close();
}
// 是否是正式开始
boolean isdovote = mwVotecourse.getDtStartDate().before(new Date());
int num4 = 0;
num2 = AddRes(isdovote, 0, 0, String.valueOf(sysId), 0, sysId, num4, id);
List<SubjectUnit> subdata = GetSubToKey(Integer.valueOf(sysId), 0, "");
for (SubjectUnit subjectUnit : subdata)
{
int num8 = 0;
int num5 = 0;
int num7 = 0;
List<MwVotekey> list = commonService.list("from MwVotekey where NSubId=? order by NOrderId,id desc", subjectUnit.getN_SubId());
for (MwVotekey mwVotekey : list)
{
String[] strArray2;
switch (mwVotekey.getNType())
{
case 1:
if (!String.valueOf(subjectUnit.getSubid()).isEmpty())
{
AddRes(isdovote, Integer.valueOf(mwVotekey.getId()), subjectUnit.getSubid(), String.valueOf(subjectUnit.getSubid()), num2, sysId, num4, id);
}
break;
case 2:
if ((subjectUnit.getSubid() != null) && (num8 == 0))
{
AddRes(isdovote, subjectUnit.getSubid(), subjectUnit.getSubid(), "2", num2, sysId, num4, id);
num8 = 1;
}
break;
case 3:
if ((subjectUnit.getSubid() != null) || (num7 != 0))
{
break;
}
// row["N_SubId"].ToString();
strArray2 = String.valueOf(subjectUnit.getSubid()).split(",");
if (strArray2.length != 0)
{
for (String string2 : strArray2)
{
AddRes(isdovote, Integer.valueOf(string2), subjectUnit.getSubid(), "3", num2, sysId, num4, id);
}
}
num7 = 1;
break;
case 4:
if ((subjectUnit.getSubid() != null) && (num5 == 0))
{
AddRes(isdovote, subjectUnit.getSubid(), subjectUnit.getSubid(), "4", num2, sysId, num4, id);
num5 = 1;
}
break;
case 5:
if (subjectUnit.getSubid() != null)
{
AddRes(isdovote, Integer.valueOf(mwVotekey.getId()), subjectUnit.getSubid(), String.valueOf(subjectUnit.getSubid()), num2, sysId, num4, id);
}
break;
}
}
}
String strA = mwVotecourse.getCReturnUrl();
String resulttemp = "";
String idresultFile = ExecuteContext.realPath() + "mw/onlinesurvey/result_" + id + ".htm";// 对应id的结果
String defaultresultlateFile = ExecuteContext.realPath() + "mw/onlinesurvey/result.htm";// 默认的结果
if (strA.isEmpty())
{
if (FileUtils.fileExists(idresultFile))
{
resulttemp = FileUtils.readFile(idresultFile);
resulttemp = resulttemp.replace("{voteid}", String.valueOf(id));
File file = new File(idresultFile);
if (file.exists())
{
file.delete();
}
FileUtils.writeFile(idresultFile, resulttemp);
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('投票成功!')</script>");
out.print("<script>location.href='" + ExecuteContext.contextPath() + "/mw/onlinesurvey/result_" + id + ".htm" + "'</script>");
out.close();
}
else
{
resulttemp = FileUtils.readFile(defaultresultlateFile);
resulttemp = resulttemp.replace("{voteid}", String.valueOf(id));
File file = new File(defaultresultlateFile);
if (file.exists())
{
file.delete();
}
FileUtils.writeFile(defaultresultlateFile, resulttemp);
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('投票成功!')</script>");
out.print("<script>location.href='" + ExecuteContext.contextPath() + "/mw/onlinesurvey/result.htm" + "'</script>");
out.close();
}
}
else
{
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>location.href='" + strA + "'</script>");
out.close();
}
}
private int AddRes(Boolean istrue, int KeyId, int SubId, String Reuslt, int TestID, int SysID, int N_LogicPageId, int VoteID)
{
int i = 0;
if (istrue)
{
MwVoteresult mwVoteresult = new MwVoteresult();
mwVoteresult.setNKeyId(KeyId);
mwVoteresult.setNSubId(SubId);
mwVoteresult.setCReuslt(Reuslt);
mwVoteresult.setNTestId(TestID);
mwVoteresult.setNSysId(SysID);
mwVoteresult.setNLogicPageId(N_LogicPageId);
mwVoteresult.setNVoteId(VoteID);
mwVoteresult.setDtDate(new Date());
mwVoteresult.setCIp(hostIP);
mwVoteresult.setIsTemp(0);// 正式表,对应C#中的MwVoteresult。用字段来区分
commonService.saveTX(mwVoteresult);// 保存
List<MwVoteresult> list = commonService.list("from MwVoteresult Order By id Desc limit 1");
i = Integer.valueOf(list.get(0).getId());
}
else
{
MwVoteresult mwVoteresult = new MwVoteresult();
mwVoteresult.setNKeyId(KeyId);
mwVoteresult.setNSubId(SubId);
mwVoteresult.setCReuslt(Reuslt);
mwVoteresult.setNTestId(TestID);
mwVoteresult.setNSysId(SysID);
mwVoteresult.setNLogicPageId(N_LogicPageId);
mwVoteresult.setNVoteId(VoteID);
mwVoteresult.setDtDate(new Date());
mwVoteresult.setCIp(hostIP);
mwVoteresult.setIsTemp(1);// 临时表,对应C#中的MwVoteresultTemp。用字段来区分
commonService.saveTX(mwVoteresult);// 保存
List<MwVoteresult> list = commonService.list("from MwVoteresult Order By id Desc limit 1");
i = Integer.valueOf(list.get(0).getId());
}
return i;
}
}
| UTF-8 | Java | 25,977 | java | VwsurveyController.java | Java | [
{
"context": "ice dbService;\n\n\tprivate String tmpPath = \"http://123.57.17.189:8084/\";\n\n\t@RequestMapping(\"index\")\n\tpublic String",
"end": 2759,
"score": 0.9736751914024353,
"start": 2746,
"tag": "IP_ADDRESS",
"value": "123.57.17.189"
}
]
| null | []
| package com.ecannetwork.tech.controller;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ecannetwork.core.i18n.I18N;
import com.ecannetwork.core.module.controller.AjaxResponse;
import com.ecannetwork.core.module.controller.DateBindController;
import com.ecannetwork.core.module.service.CommonService;
import com.ecannetwork.core.util.CoreConsts;
import com.ecannetwork.core.util.ExecuteContext;
import com.ecannetwork.core.util.QRCodeUtil;
import com.ecannetwork.dto.core.EcanUser;
import com.ecannetwork.dto.tech.MwVotecourse;
import com.ecannetwork.dto.tech.MwVotekey;
import com.ecannetwork.dto.tech.MwVoteresult;
import com.ecannetwork.dto.tech.MwVotesubject;
import com.ecannetwork.dto.tech.MwVotesystem;
import com.ecannetwork.dto.tech.SubjectUnit;
import com.ecannetwork.dto.tech.TechTest;
import com.ecannetwork.dto.tech.TechTestAnswer;
import com.ecannetwork.dto.tech.TechTestDb;
import com.ecannetwork.dto.tech.TechTrainCourse;
import com.ecannetwork.dto.tech.TechUserMessage;
import com.ecannetwork.tech.service.TestDbService;
import com.ecannetwork.tech.service.TrainPlanService;
import com.ecannetwork.tech.util.FileUtils;
@Controller
@RequestMapping("/vwsurvey")
public class VwsurveyController extends DateBindController
{
@Autowired
private CommonService commonService;
@Autowired
private TestDbService dbService;
private String tmpPath = "http://192.168.127.12:8084/";
@RequestMapping("index")
public String index(Model model)
{
@SuppressWarnings("unchecked")
List<MwVotecourse> list = commonService.list("from MwVotecourse t order by id desc");// 列表
model.addAttribute("dblist", list);
return "tech/vwsurvey/index";
}
@RequestMapping("del")
public @ResponseBody
AjaxResponse del(Model model, @RequestParam(value = "id", required = true) String id)
{
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
commonService.deleteTX(MwVotecourse.class, id);
return new AjaxResponse(true, "i18n.commit.del.success");
}
return new AjaxResponse(true, "i18n.commit.del.success");
}
@RequestMapping("copy")
public @ResponseBody
AjaxResponse copy(Model model, @RequestParam(value = "id", required = true) String id)
{
// 先查出当前记录
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
mwVotecourse.setId(null);// id是数据库自动生成的
mwVotecourse.setCTitle(mwVotecourse.getCTitle() + "_复制");// title是原来的title+"_复制"
commonService.saveTX(mwVotecourse);// 作为新的记录保存
return new AjaxResponse(true, "复制成功");
}
return new AjaxResponse(true, "复制成功");
}
@RequestMapping("build")
public @ResponseBody
AjaxResponse build(Model model, @RequestParam(value = "id", required = true) String id, @RequestParam(value = "NSysId", required = true) String NSysId)
{
// 先查出当前记录
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
// 读votetemplate文件
String votetemp = "";
String idTemplateFile = ExecuteContext.realPath() + "mw/onlinesurvey/votetemplate_" + id + ".htm";// 对应id的模板
String defaultTemplateFile = ExecuteContext.realPath() + "mw/onlinesurvey/votetemplate.htm";// 默认的模板
if (FileUtils.fileExists(idTemplateFile))
{
votetemp = FileUtils.readFile(idTemplateFile) + "\n";
}
else
{
votetemp = FileUtils.readFile(defaultTemplateFile) + "\n";
}
votetemp = votetemp.replace("{id}", mwVotecourse.getId())
.replace("{path}", ExecuteContext.realPath())
.replace("{title}", mwVotecourse.getCTitle())
.replace("{course}", mwVotecourse.getCCourse())
.replace("{teacher}", mwVotecourse.getCTearcher())
.replace("{address}", mwVotecourse.getCAdrees())
.replace("{starttime}", mwVotecourse.getDtStartDate()==null?"":mwVotecourse.getDtStartDate().toString())
.replace("{endtime}", mwVotecourse.getDtOverDate()==null?"":mwVotecourse.getDtOverDate().toString())
.replace("{coursestarttime}", mwVotecourse.getCourseStart() == null ? "" : mwVotecourse.getCourseStart().toString())
.replace("{courseendtime}", mwVotecourse.getCourseEnd() == null ? "" : mwVotecourse.getCourseEnd().toString());
// 生成内容
votetemp = votetemp.replace("{Content}", pubBuildHtml(mwVotecourse).replace("{Images}", ExecuteContext.realPath() + "/mw/onlinesurvey/SysImages"));
// 生成的新的文件,以id命名
String newFile = ExecuteContext.realPath() + "mw/onlinesurvey/" + id + ".html";
String desFilePath = ExecuteContext.realPath() + "/mw/onlinesurvey/qr";
// 生成当前问卷的二维码
if (votetemp.contains("{QR}"))
{
try
{
QRCodeUtil.encode(newFile, "", ExecuteContext.realPath() + "/mw/onlinesurvey/qr/", true, id);// 生成二维码
// 替换二维码位置
votetemp = votetemp.replace("{QR}", "<img src=\"" + ExecuteContext.realPath() + "/mw/onlinesurvey/qr/" + id + ".jpg\" width=\"100\" height=\"100\" />");
}
catch (Exception e)
{
e.printStackTrace();
}
}
File file = new File(newFile);
if (file.exists())
{
file.delete();
}
FileUtils.writeFile(newFile, votetemp);
System.out.println("build create file : " + newFile);
return new AjaxResponse(true, "生成投票问卷成功");
}
return new AjaxResponse(false, "生成投票问卷失败");
}
@RequestMapping("add")
public String add(Model model)
{
// 绑定调查模板下拉列表数据
List<MwVotesystem> mwVotesystem = this.commonService.list("from MwVotesystem order by id DESC");
model.addAttribute("list", mwVotesystem);
// 绑定培训课程下拉列表数据
List<TechTrainCourse> CCourselist = this.commonService.list("from com.ecannetwork.dto.tech.TechTrainCourse t where t.status=?", CoreConsts.YORN.YES);
model.addAttribute("CCourselist", CCourselist);
return "tech/vwsurvey/save";
}
@RequestMapping("edit")
public String edit(Model model, @RequestParam(value = "id", required = true) String id)
{
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
model.addAttribute("dto", mwVotecourse);
// 绑定调查模板下拉列表数据
List<MwVotesystem> mwVotesystem = this.commonService.list("from MwVotesystem order by id DESC");
model.addAttribute("list", mwVotesystem);
// 绑定培训课程下拉列表数据
List<TechTrainCourse> CCourselist = this.commonService.list("from com.ecannetwork.dto.tech.TechTrainCourse t where t.status=?", CoreConsts.YORN.YES);
model.addAttribute("CCourselist", CCourselist);
return "tech/vwsurvey/save";
}
// //选择老师
@RequestMapping("listteachers")
public String listteachers(Model model)
{
List<EcanUser> teachers = this.commonService.list("from EcanUser e where e.roleId='teacher' and e.status = '1'");
model.addAttribute("list", teachers);
return "tech/message/selectteachers";
}
@RequestMapping("save")
public @ResponseBody
AjaxResponse save(Model model, @Valid MwVotecourse mwVotecourse, BindingResult result, HttpServletRequest request)
{
// 获取是否验证checkbox的值。当选中时,值为on,否则为null
String checkNcodeString = request.getParameter("NCodeSurvey");
if (checkNcodeString == null)
{
mwVotecourse.setNCodeSurvey(0);
}
else
{
mwVotecourse.setNCodeSurvey(1);
}
if (mwVotecourse.getId() == null || mwVotecourse.getId() == "")
{
commonService.saveTX(mwVotecourse);// 保存
return new AjaxResponse(true, I18N.parse("i18n.commit.success"));
}
else
{
commonService.updateTX(mwVotecourse);// 更新
return new AjaxResponse(true, I18N.parse("i18n.commit.success"));
}
}
// 生成调查问卷内容
public String pubBuildHtml(MwVotecourse mwVotecourse)
{
StringBuffer strResult = new StringBuffer();// 最终的结果
strResult.append("<form name=\"VWVoteForm\" id=\"VWVoteForm\" method=\"post\" action=\"/Portal2012/techc/vwsurvey/getresult\" >");
strResult.append("<input name=\"VoteId\" type=\"hidden\" value=\"" + mwVotecourse.getId() + "\" /><input name=\"SubjectId\" type=\"hidden\" value=\"" + mwVotecourse.getNSysId() + "\" />");
strResult.append("<div class=\"survey\">");
Integer xh = 1;
@SuppressWarnings("unchecked")
List<MwVotesubject> list = commonService.list("from MwVotesubject where parentid=0 and NSysId=? order by id desc", mwVotecourse.getNSysId());// 问卷数据
if (!list.isEmpty())
{
for (MwVotesubject mwVotesubject : list)
{
Integer jj = 0;
List<SubjectUnit> subdata = GetSubToKey(mwVotecourse.getNSysId(), mwVotesubject.getParentid(), "");
if (!subdata.isEmpty())
{
for (SubjectUnit subjectUnit : subdata)
{
jj++;
strResult.append("<div class=\"qa" + ((xh * jj > 1) ? " nodisplay" : "") + " \">" + "<h2>" + subjectUnit.getC_SubTitle().replace("\n", "<br/>") + "</h2>" + "<p>"
+ String.valueOf(xh) + ((jj > 0) ? "-" + jj : "") + ". " + subjectUnit.getC_SubTitle().replace("\n", "<br/>") + "</p>");
strResult.append(GetTable(subjectUnit));
strResult.append("</div>");
}
xh++;
}
}
}
// 增加验证码功能
// if (mwVotecourse.getNCodeSurvey().equals(1))
// {
// strResult.append("<div class=\"qa nodisplay\"><p>" +
// String.valueOf(xh++) + ". 请输入图片中文字</p>");
// strResult.append("<input type=\"text\" name=\"Check\" style=\"width:100px\" /> <img id=\"imgObj\" alt=\"验证码\" src=\"${ctxPath}/techc/vwsurvey/code\" /><br/>");
// strResult.append("</div>");
// }
strResult.append("</div><div class=\"btn\"> <a id=\"btnpre\">上一页<br />Previous</a> <span></span> <a id=\"btnnext\">下一页<br />Next</a>");
strResult.append(" </div>");
// strResult.append("<br><br><input type=\"submit\" name=\"Submit\" value=\"提 交\" style=\"width:100px\"></form>");
strResult.append("</form>");
return strResult.toString();
}
public List<SubjectUnit> GetSubToKey(final Integer sysid, final Integer parentid, final String where)
{
final List list = new ArrayList();
// 用此种方法来执行sql语句
this.commonService.executeCallbackTX(new HibernateCallback()
{
@Override
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
try
{
Connection conn = session.connection();
String cmdtext = "SELECT u.N_SubId,s.N_SysId,s.N_SubId as subid,s.C_SubTitle,s.Parentid,s.N_Need FROM mw_voteunit AS u INNER JOIN mw_votesubject AS s ON u.N_SubId = s.N_Type where 1=1 ";
if (sysid > 0)
{
cmdtext += " and u.N_SysId =" + sysid;
}
if (parentid > 0)
{
cmdtext += " and s.Parentid =" + parentid;
}
cmdtext += where + " order by s.N_OrderId,s.N_SubId";
PreparedStatement pst = conn.prepareStatement(cmdtext);
ResultSet rs = pst.executeQuery();
while (rs.next())
{
SubjectUnit unit = new SubjectUnit();
unit.setN_SubId(rs.getInt("N_SubId"));
unit.setN_SysId(rs.getInt("N_SysId"));
unit.setSubid(rs.getInt("subid"));
unit.setC_SubTitle(rs.getString("C_SubTitle"));
unit.setParentid(rs.getInt("Parentid"));
unit.setN_Need(rs.getInt("N_Need"));
list.add(unit);
}
pst.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
});
return list;
}
private String GetTable(SubjectUnit subjectUnit)
{
List<MwVotekey> list = commonService.list("from MwVotekey where NSubId=? order by NOrderId,id desc", subjectUnit.getN_SubId());
StringBuffer strUnitBuffer = new StringBuffer();// 返回的字符串
int num2 = 0;
if (!list.isEmpty())
{
for (MwVotekey mwVotekey : list)
{
num2++;
Integer ntype = mwVotekey.getNType();
switch (ntype)
{
case 1:
if (subjectUnit.getN_Need().equals(1))
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + " <input type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" check=\"^\\S+$\" warning=\""
+ mwVotekey.getCKeyTitle() + "不能为空\" >");
}
else
{
if (!mwVotekey.getCRule().isEmpty() && !mwVotekey.getCRule().startsWith("不限制"))
{
String strArray17[] = mwVotekey.getCRule().split("`");
if (strArray17[1] != "*")
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + "" + "<input type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" check=\"" + strArray17[1]
+ "\" warning=\"" + mwVotekey.getCKeyTitle() + "格式不正确,应填 " + strArray17[0] + "\" >");
}
else
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + "" + "<input type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\">");
}
}
else
{
strUnitBuffer.append(mwVotekey.getCKeyTitle() + " <input type=\"text\" name=\" " + String.valueOf(subjectUnit.getSubid()) + "\">");
}
}
break;
case 2:
if (num2 == 1)
{
strUnitBuffer.append("<ul class=\"option\">");
}
if (subjectUnit.getN_Need().equals(1))
{
if (num2 != 1)
{
strUnitBuffer.append("<li><label><input type=\"radio\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
else
{
strUnitBuffer.append("<li><label><input type=\"radio\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId())
+ "\" check=\"^0$\" warning=\"" + subjectUnit.getC_SubTitle() + "最少选一项\" >" + mwVotekey.getCKeyTitle() + "</label></li>");
}
}
else
{
strUnitBuffer.append("<li><label><input type=\"radio\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
if (num2 == list.size())
{
strUnitBuffer.append("</ul>");
}
break;
case 3:
if (num2 == 1)
{
strUnitBuffer.append("<ul class=\"option\">");
}
if (subjectUnit.getN_Need().equals(1))
{
if (num2 == 1)
{
strUnitBuffer.append("<li><label><input type=\"checkbox\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId())
+ "\" check=\"^0{1,}$\" warning=\"" + subjectUnit.getC_SubTitle() + "最少选一项或以上\">" + mwVotekey.getCKeyTitle() + "</label></li>");
}
else
{
strUnitBuffer.append("<li><label><input type=\"checkbox\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
}
else
{
strUnitBuffer.append("<li><label><input type=\"checkbox\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" value=\"" + String.valueOf(mwVotekey.getId()) + "\">"
+ mwVotekey.getCKeyTitle() + "</label></li>");
}
if (num2 == list.size())
{
strUnitBuffer.append("</ul>");
}
break;
case 4:
if (num2 == 1)
{
strUnitBuffer.append("<select name=\"" + String.valueOf(subjectUnit.getSubid()) + "\"><option value=\"" + String.valueOf(mwVotekey.getId()) + "\" selected=\"selected\">"
+ mwVotekey.getCKeyTitle() + "</option>");
}
else if (num2 == list.size())
{
strUnitBuffer.append("<option value=\"" + String.valueOf(subjectUnit.getSubid()) + "\" >" + mwVotekey.getCKeyTitle() + "</option></select>");
}
else
{
strUnitBuffer.append("<option value=\"" + String.valueOf(subjectUnit.getSubid()) + "\" >" + mwVotekey.getCKeyTitle() + "</option>");
}
break;
case 5:
if (subjectUnit.getN_Need().equals(1))
{
strUnitBuffer.append("<p>" + mwVotekey.getCKeyTitle() + "<textarea name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" rows=\"5\" check=\"^[\\s|\\S]{2,}$\" warning=\""
+ mwVotekey.getCKeyTitle() + "不能为空,且不能少于3个字\"></textarea></p>");
break;
}
else
{
if (!mwVotekey.getCRule().isEmpty() && !mwVotekey.getCRule().startsWith("不限制"))
{
String strArray3[] = mwVotekey.getCRule().split("`");
strUnitBuffer.append("<p>" + mwVotekey.getCKeyTitle() + "<textarea type=\"text\" name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" check=\"" + strArray3[1]
+ "\" warning=\"" + mwVotekey.getCKeyTitle() + "格式不正确,应为 " + strArray3[0] + "\" ></textarea></p>");
}
else
{
strUnitBuffer.append("<p>" + mwVotekey.getCKeyTitle() + "<textarea name=\"" + String.valueOf(subjectUnit.getSubid()) + "\" rows=\"5\" ></textarea></p>");
}
}
break;
}
}
}
return strUnitBuffer.toString();
}
@RequestMapping("pushreport")
public String pushreport(Model model, @RequestParam(value = "id", required = true) String id)
{
System.out.println("pushreport : " + id);
// 先查出当前记录
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(id, MwVotecourse.class);
if (mwVotecourse != null)
{
// TODO:temp
String webpath = this.tmpPath + "mw/onlinesurvey/" + id + ".html";// 路径
try
{
QRCodeUtil.encode(webpath, "", ExecuteContext.realPath() + "/mw/onlinesurvey/qr/", true, id);// 生成二维码
}
catch (Exception e)
{
e.printStackTrace();
}
// String qrPath = ExecuteContext.realPath() +
// "mw/onlinesurvey/qr/" + id + ".jpg";
String qrPath = ExecuteContext.contextPath() + "/mw/onlinesurvey/qr/" + id + ".jpg";
String content = pubBuildHtml(mwVotecourse);// 代码内容
model.addAttribute("webpath", webpath);
model.addAttribute("qrPath", qrPath);
model.addAttribute("content", content);
}
return "tech/vwsurvey/pushreport";
}
String hostIP = "";// 当前页面客户端的IP
@RequestMapping("getresult")
public @ResponseBody
void getresult(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException
{
hostIP = request.getRemoteAddr();
Integer id = Integer.valueOf(request.getParameter("VoteId"));
Integer sysId = Integer.valueOf(request.getParameter("SubjectId"));
if (id == null && sysId == null)
{
// return new AjaxResponse(true, "参数错误!");
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('参数错误!')</script>");
out.print("<script>location.href='/Portal2012/mw/onlinesurvey/" + id + ".html'</script>");
out.close();
}
int num2;
MwVotecourse mwVotecourse = (MwVotecourse) commonService.get(String.valueOf(id), MwVotecourse.class);
if (mwVotecourse.getDtStartDate().after(new Date()))// 调查的时间开始时间在当前时间后
{
// return new AjaxResponse(true, "调查已经过期!");
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('调查已经过期!')</script>");
out.print("<script>location.href='/Portal2012/mw/onlinesurvey/" + id + ".html'</script>");
out.close();
}
// 是否是正式开始
boolean isdovote = mwVotecourse.getDtStartDate().before(new Date());
int num4 = 0;
num2 = AddRes(isdovote, 0, 0, String.valueOf(sysId), 0, sysId, num4, id);
List<SubjectUnit> subdata = GetSubToKey(Integer.valueOf(sysId), 0, "");
for (SubjectUnit subjectUnit : subdata)
{
int num8 = 0;
int num5 = 0;
int num7 = 0;
List<MwVotekey> list = commonService.list("from MwVotekey where NSubId=? order by NOrderId,id desc", subjectUnit.getN_SubId());
for (MwVotekey mwVotekey : list)
{
String[] strArray2;
switch (mwVotekey.getNType())
{
case 1:
if (!String.valueOf(subjectUnit.getSubid()).isEmpty())
{
AddRes(isdovote, Integer.valueOf(mwVotekey.getId()), subjectUnit.getSubid(), String.valueOf(subjectUnit.getSubid()), num2, sysId, num4, id);
}
break;
case 2:
if ((subjectUnit.getSubid() != null) && (num8 == 0))
{
AddRes(isdovote, subjectUnit.getSubid(), subjectUnit.getSubid(), "2", num2, sysId, num4, id);
num8 = 1;
}
break;
case 3:
if ((subjectUnit.getSubid() != null) || (num7 != 0))
{
break;
}
// row["N_SubId"].ToString();
strArray2 = String.valueOf(subjectUnit.getSubid()).split(",");
if (strArray2.length != 0)
{
for (String string2 : strArray2)
{
AddRes(isdovote, Integer.valueOf(string2), subjectUnit.getSubid(), "3", num2, sysId, num4, id);
}
}
num7 = 1;
break;
case 4:
if ((subjectUnit.getSubid() != null) && (num5 == 0))
{
AddRes(isdovote, subjectUnit.getSubid(), subjectUnit.getSubid(), "4", num2, sysId, num4, id);
num5 = 1;
}
break;
case 5:
if (subjectUnit.getSubid() != null)
{
AddRes(isdovote, Integer.valueOf(mwVotekey.getId()), subjectUnit.getSubid(), String.valueOf(subjectUnit.getSubid()), num2, sysId, num4, id);
}
break;
}
}
}
String strA = mwVotecourse.getCReturnUrl();
String resulttemp = "";
String idresultFile = ExecuteContext.realPath() + "mw/onlinesurvey/result_" + id + ".htm";// 对应id的结果
String defaultresultlateFile = ExecuteContext.realPath() + "mw/onlinesurvey/result.htm";// 默认的结果
if (strA.isEmpty())
{
if (FileUtils.fileExists(idresultFile))
{
resulttemp = FileUtils.readFile(idresultFile);
resulttemp = resulttemp.replace("{voteid}", String.valueOf(id));
File file = new File(idresultFile);
if (file.exists())
{
file.delete();
}
FileUtils.writeFile(idresultFile, resulttemp);
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('投票成功!')</script>");
out.print("<script>location.href='" + ExecuteContext.contextPath() + "/mw/onlinesurvey/result_" + id + ".htm" + "'</script>");
out.close();
}
else
{
resulttemp = FileUtils.readFile(defaultresultlateFile);
resulttemp = resulttemp.replace("{voteid}", String.valueOf(id));
File file = new File(defaultresultlateFile);
if (file.exists())
{
file.delete();
}
FileUtils.writeFile(defaultresultlateFile, resulttemp);
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>alert('投票成功!')</script>");
out.print("<script>location.href='" + ExecuteContext.contextPath() + "/mw/onlinesurvey/result.htm" + "'</script>");
out.close();
}
}
else
{
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=utf-8");
out.print("<script>location.href='" + strA + "'</script>");
out.close();
}
}
private int AddRes(Boolean istrue, int KeyId, int SubId, String Reuslt, int TestID, int SysID, int N_LogicPageId, int VoteID)
{
int i = 0;
if (istrue)
{
MwVoteresult mwVoteresult = new MwVoteresult();
mwVoteresult.setNKeyId(KeyId);
mwVoteresult.setNSubId(SubId);
mwVoteresult.setCReuslt(Reuslt);
mwVoteresult.setNTestId(TestID);
mwVoteresult.setNSysId(SysID);
mwVoteresult.setNLogicPageId(N_LogicPageId);
mwVoteresult.setNVoteId(VoteID);
mwVoteresult.setDtDate(new Date());
mwVoteresult.setCIp(hostIP);
mwVoteresult.setIsTemp(0);// 正式表,对应C#中的MwVoteresult。用字段来区分
commonService.saveTX(mwVoteresult);// 保存
List<MwVoteresult> list = commonService.list("from MwVoteresult Order By id Desc limit 1");
i = Integer.valueOf(list.get(0).getId());
}
else
{
MwVoteresult mwVoteresult = new MwVoteresult();
mwVoteresult.setNKeyId(KeyId);
mwVoteresult.setNSubId(SubId);
mwVoteresult.setCReuslt(Reuslt);
mwVoteresult.setNTestId(TestID);
mwVoteresult.setNSysId(SysID);
mwVoteresult.setNLogicPageId(N_LogicPageId);
mwVoteresult.setNVoteId(VoteID);
mwVoteresult.setDtDate(new Date());
mwVoteresult.setCIp(hostIP);
mwVoteresult.setIsTemp(1);// 临时表,对应C#中的MwVoteresultTemp。用字段来区分
commonService.saveTX(mwVoteresult);// 保存
List<MwVoteresult> list = commonService.list("from MwVoteresult Order By id Desc limit 1");
i = Integer.valueOf(list.get(0).getId());
}
return i;
}
}
| 25,978 | 0.659557 | 0.652314 | 734 | 33.235695 | 38.661922 | 191 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.502725 | false | false | 15 |
eca6849b82113f4708c31235b66fe2fda4050022 | 25,821,343,397,366 | b1225d48b4a917849cdab707785a940f1c0af32f | /AbstractFactory/src/com/company/TvNewsFactory.java | 37826ced4da297f61ef24aa87a27e2150d4cc5db | []
| no_license | shurskyy/Patterns | https://github.com/shurskyy/Patterns | c5c2d8d69abd31e5d359f9afc80380cde3039b35 | 90cb179e79ca85da61cfc98a25f710ba1d1bfac2 | refs/heads/master | 2020-06-10T12:22:59.534000 | 2016-12-29T19:07:02 | 2016-12-29T19:07:02 | 75,962,661 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
/**
* Created by Serhiy_Hurskyy on 12/29/2016.
*/
public class TvNewsFactory
{
public static NewsFactory getFactory(String factory)
{
if (factory.equalsIgnoreCase("Zrada"))
{
return new ZradaNewsFactory();
}
else if (factory.equalsIgnoreCase("Peremoga"))
{
return new PeremogaNewsFactory();
}
return null;
}
}
| UTF-8 | Java | 427 | java | TvNewsFactory.java | Java | [
{
"context": "package com.company;\n\n/**\n * Created by Serhiy_Hurskyy on 12/29/2016.\n */\npublic class TvNewsFactory\n{\n ",
"end": 54,
"score": 0.9995458126068115,
"start": 40,
"tag": "NAME",
"value": "Serhiy_Hurskyy"
}
]
| null | []
| package com.company;
/**
* Created by Serhiy_Hurskyy on 12/29/2016.
*/
public class TvNewsFactory
{
public static NewsFactory getFactory(String factory)
{
if (factory.equalsIgnoreCase("Zrada"))
{
return new ZradaNewsFactory();
}
else if (factory.equalsIgnoreCase("Peremoga"))
{
return new PeremogaNewsFactory();
}
return null;
}
}
| 427 | 0.583138 | 0.564403 | 21 | 19.333334 | 19.305399 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | false | false | 15 |
b7437e6be1e9278a633a420984bc7f93869734e3 | 15,547,781,623,141 | d5a19e9cad63192a17ed65f94d8bb7fae12a1b89 | /编译原理项目实验三/ex2/src/exceptions/MissingOperatorException.java | ff81246fdae00f356c730d230f30abfd7f009eb1 | []
| no_license | 56clients/Experiments-on-Compiling-Principles | https://github.com/56clients/Experiments-on-Compiling-Principles | aa77a32459541df35dc5f92c351376b4442582ec | 78a0970612b11f37a2c5d4e881e37de46154ebc0 | refs/heads/master | 2020-06-13T16:11:39.880000 | 2019-07-01T16:24:26 | 2019-07-01T16:24:26 | 194,705,336 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package exceptions;
/**
* Missing operator.
*
* @author
* @author
* @version
**/
public class MissingOperatorException extends SyntacticException
{
public MissingOperatorException() {
this("Missing operator.");
}
public MissingOperatorException(String msg) {
super(msg);
}
} | UTF-8 | Java | 294 | java | MissingOperatorException.java | Java | []
| null | []
| package exceptions;
/**
* Missing operator.
*
* @author
* @author
* @version
**/
public class MissingOperatorException extends SyntacticException
{
public MissingOperatorException() {
this("Missing operator.");
}
public MissingOperatorException(String msg) {
super(msg);
}
} | 294 | 0.704082 | 0.704082 | 19 | 14.526316 | 17.233286 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 15 |
90bdb03b4e3ed510b44d417c13ecae4f68c59c59 | 6,725,918,799,833 | 106bf748fe4c57a7a557ec57d413cd9737f408d6 | /CalculatorController.java | 811c7821941a7573ba8bc202175cc500c9aea91b | []
| no_license | abditimer/Calculator | https://github.com/abditimer/Calculator | 221ebf0562005ffa95bcd8b88919018147f21700 | 17cd0c19da8752f64cedd4e16c6965dba25d1c9a | refs/heads/master | 2021-01-19T12:50:46.902000 | 2017-03-10T19:23:34 | 2017-03-10T19:23:34 | 82,342,667 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//test
public class CalculatorController {
//needs to link the view to the model
private CalculatorModel model;
private CalculatorView view;
public CalculatorController( CalculatorModel model, CalculatorView view) {
this.model = model;
this.view = view;
this.view.calculationListener(new CalculateListener());
}
//make another class
class CalculateListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
int fNumber, sNumber = 0;
try {
fNumber = view.getFNumber();
sNumber = view.getSNumber();
model.addition(fNumber, sNumber);
view.setSolution(model.getOutput());
} catch (NumberFormatException ex) {
view.displayErrorMessage("some shit went wrong yo");
}
}
}
}
| UTF-8 | Java | 872 | java | CalculatorController.java | Java | []
| null | []
| import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//test
public class CalculatorController {
//needs to link the view to the model
private CalculatorModel model;
private CalculatorView view;
public CalculatorController( CalculatorModel model, CalculatorView view) {
this.model = model;
this.view = view;
this.view.calculationListener(new CalculateListener());
}
//make another class
class CalculateListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
int fNumber, sNumber = 0;
try {
fNumber = view.getFNumber();
sNumber = view.getSNumber();
model.addition(fNumber, sNumber);
view.setSolution(model.getOutput());
} catch (NumberFormatException ex) {
view.displayErrorMessage("some shit went wrong yo");
}
}
}
}
| 872 | 0.701835 | 0.699541 | 32 | 25.25 | 19.808458 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.40625 | false | false | 15 |
7a03ff7880acad77db7056d0b78e350f58bb11d0 | 7,610,682,069,196 | d108da31ad34d1190434f634e45fcf17f52aa52e | /designPatternfactory/src/main/java/niushengqiang/factory/method/BenzFactory.java | bf1c79051a264e360f40b5cdd5ac8ada7d952ec3 | []
| no_license | niushengqiang/gupao2019 | https://github.com/niushengqiang/gupao2019 | 7cc0b67ca146d478a730e0e1610378ba405b87c7 | c0cae8a96793ab5e4382b5d93f71134f55691049 | refs/heads/master | 2022-07-31T22:24:57.496000 | 2020-04-19T13:49:55 | 2020-04-19T13:49:55 | 174,790,130 | 0 | 0 | null | false | 2022-07-13T15:30:34 | 2019-03-10T07:12:31 | 2020-04-19T13:50:41 | 2022-07-13T15:30:33 | 408 | 0 | 0 | 28 | Java | false | false | package niushengqiang.factory.method;
import niushengqiang.factory.product.Benz;
import niushengqiang.factory.product.Car;
public class BenzFactory implements CarFactory {
@Override
public Car getCar() {
return new Benz();
}
}
| UTF-8 | Java | 250 | java | BenzFactory.java | Java | []
| null | []
| package niushengqiang.factory.method;
import niushengqiang.factory.product.Benz;
import niushengqiang.factory.product.Car;
public class BenzFactory implements CarFactory {
@Override
public Car getCar() {
return new Benz();
}
}
| 250 | 0.736 | 0.736 | 12 | 19.833334 | 18.013113 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 15 |
491ef8c9b67df035bc305ee9b02ef08dbf147251 | 32,074,815,769,263 | 40860e966ccfe4a299be531a91560ef0c8b8aee2 | /src/main/java/com/github/davidmoten/aws/maven/S3FileDeployerMojo.java | a8ca246ca1ad23c8318d0033ce479dfa9a388562 | [
"Apache-2.0"
]
| permissive | jlsheehan/aws-maven-plugin | https://github.com/jlsheehan/aws-maven-plugin | ee3421194c7b4f001229361b449b29bdd9778916 | 9e550d382be4325c403a6666b076a9d7ce304c52 | refs/heads/master | 2020-07-07T13:26:05.731000 | 2019-08-20T12:47:37 | 2019-08-21T02:09:54 | 203,361,160 | 0 | 0 | Apache-2.0 | true | 2019-08-20T11:20:32 | 2019-08-20T11:20:32 | 2019-07-27T22:35:37 | 2019-07-27T22:35:35 | 112 | 0 | 0 | 0 | null | false | false | package com.github.davidmoten.aws.maven;
import java.io.File;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.crypto.SettingsDecrypter;
@Mojo(name = "deployFileS3")
public final class S3FileDeployerMojo extends AbstractMojo {
@Parameter(property = "awsAccessKey")
private String awsAccessKey;
@Parameter(property = "awsSecretAccessKey")
private String awsSecretAccessKey;
@Parameter(property = "serverId")
private String serverId;
@Parameter(property = "region")
private String region;
@Parameter(property = "bucketName")
private String bucketName;
@Parameter(property = "file", required = true)
private File file;
@Parameter(property = "objectName")
private String objectName;
@Parameter(property = "create", defaultValue = "false")
private boolean create;
@Parameter(property = "httpsProxyHost")
private String httpsProxyHost;
@Parameter(property = "httpsProxyPort")
private int httpsProxyPort;
@Parameter(property = "httpsProxyUsername")
private String httpsProxyUsername;
@Parameter(property = "httpsProxyPassword")
private String httpsProxyPassword;
@Parameter(property = "awsKmsKeyId")
private String awsKmsKeyId;
@Parameter(defaultValue = "${project}", required = true)
private MavenProject project;
@Parameter(defaultValue = "${settings}", readonly = true)
private Settings settings;
@Component
private SettingsDecrypter decrypter;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Proxy proxy = new Proxy(httpsProxyHost, httpsProxyPort, httpsProxyUsername, httpsProxyPassword);
S3FileDeployer deployer = new S3FileDeployer(getLog());
AwsKeyPair keyPair = Util.getAwsKeyPair(serverId, awsAccessKey, awsSecretAccessKey, settings, decrypter);
deployer.deploy(keyPair, region, file, bucketName, objectName, proxy, create, awsKmsKeyId);
}
}
| UTF-8 | Java | 2,363 | java | S3FileDeployerMojo.java | Java | [
{
"context": "package com.github.davidmoten.aws.maven;\n\nimport java.io.File;\n\nimport org.apac",
"end": 29,
"score": 0.9989075660705566,
"start": 19,
"tag": "USERNAME",
"value": "davidmoten"
}
]
| null | []
| package com.github.davidmoten.aws.maven;
import java.io.File;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.crypto.SettingsDecrypter;
@Mojo(name = "deployFileS3")
public final class S3FileDeployerMojo extends AbstractMojo {
@Parameter(property = "awsAccessKey")
private String awsAccessKey;
@Parameter(property = "awsSecretAccessKey")
private String awsSecretAccessKey;
@Parameter(property = "serverId")
private String serverId;
@Parameter(property = "region")
private String region;
@Parameter(property = "bucketName")
private String bucketName;
@Parameter(property = "file", required = true)
private File file;
@Parameter(property = "objectName")
private String objectName;
@Parameter(property = "create", defaultValue = "false")
private boolean create;
@Parameter(property = "httpsProxyHost")
private String httpsProxyHost;
@Parameter(property = "httpsProxyPort")
private int httpsProxyPort;
@Parameter(property = "httpsProxyUsername")
private String httpsProxyUsername;
@Parameter(property = "httpsProxyPassword")
private String httpsProxyPassword;
@Parameter(property = "awsKmsKeyId")
private String awsKmsKeyId;
@Parameter(defaultValue = "${project}", required = true)
private MavenProject project;
@Parameter(defaultValue = "${settings}", readonly = true)
private Settings settings;
@Component
private SettingsDecrypter decrypter;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Proxy proxy = new Proxy(httpsProxyHost, httpsProxyPort, httpsProxyUsername, httpsProxyPassword);
S3FileDeployer deployer = new S3FileDeployer(getLog());
AwsKeyPair keyPair = Util.getAwsKeyPair(serverId, awsAccessKey, awsSecretAccessKey, settings, decrypter);
deployer.deploy(keyPair, region, file, bucketName, objectName, proxy, create, awsKmsKeyId);
}
}
| 2,363 | 0.746509 | 0.744816 | 76 | 30.092106 | 26.540028 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657895 | false | false | 15 |
51cd427f5eca2360aabae573e335a79ac542cc7b | 32,074,815,769,422 | 302af4aa0bf08a66dde5fa95bc6e8992e4505c7d | /com.gumtree.android.beta/java/com/gumtree/android/userprofile/services/DefaultUserService$$Lambda$4.java | 1cb62c848bfc23a62cd1ba5b5486ff4f602e330b | []
| no_license | hakat0m/Chessboxing | https://github.com/hakat0m/Chessboxing | 0f5ce696a55a5b40f1d8fa226bbdc5673ef5dbc5 | 0a576dec5aaafa219c340a013726037d852b91a2 | refs/heads/master | 2021-01-19T08:51:23.932000 | 2017-04-09T06:48:44 | 2017-04-09T06:48:44 | 87,688,753 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gumtree.android.userprofile.services;
import java.lang.invoke.LambdaForm.Hidden;
import rx.functions.Action0;
final /* synthetic */ class DefaultUserService$$Lambda$4 implements Action0 {
private final DefaultUserService arg$1;
private DefaultUserService$$Lambda$4(DefaultUserService defaultUserService) {
this.arg$1 = defaultUserService;
}
public static Action0 lambdaFactory$(DefaultUserService defaultUserService) {
return new DefaultUserService$$Lambda$4(defaultUserService);
}
@Hidden
public void call() {
this.arg$1.lambda$update$1();
}
}
| UTF-8 | Java | 618 | java | DefaultUserService$$Lambda$4.java | Java | []
| null | []
| package com.gumtree.android.userprofile.services;
import java.lang.invoke.LambdaForm.Hidden;
import rx.functions.Action0;
final /* synthetic */ class DefaultUserService$$Lambda$4 implements Action0 {
private final DefaultUserService arg$1;
private DefaultUserService$$Lambda$4(DefaultUserService defaultUserService) {
this.arg$1 = defaultUserService;
}
public static Action0 lambdaFactory$(DefaultUserService defaultUserService) {
return new DefaultUserService$$Lambda$4(defaultUserService);
}
@Hidden
public void call() {
this.arg$1.lambda$update$1();
}
}
| 618 | 0.73301 | 0.716828 | 21 | 28.428572 | 28.654879 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 15 |
b9614cd621d0af391e3650086ff1c0656774e2c1 | 6,279,242,194,462 | 836c00988a88e337e67d6c00f47231e566ae1d03 | /src/junit/TestCloneUndo.java | 159038a1463cf667493d7fdc12ad52666df0bda2 | []
| no_license | antonpp11/TicTacToeAI | https://github.com/antonpp11/TicTacToeAI | 968943629607551aa9df0a4970136017d6f5f155 | d7c901dd0ae3fc6d846c27aba5b875fddff3e871 | refs/heads/master | 2023-07-19T23:06:42.092000 | 2023-07-10T22:39:01 | 2023-07-10T22:39:01 | 287,293,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.rules.TestName;
import org.junit.Rule;
import java.util.Arrays;
import static org.junit.Assert.*;
public class TestCloneUndo {
@Rule
public Timeout globalTimeout = Timeout.seconds(1); // 1 seconds max per method tested
@Rule
public TestName testName = new TestName();
@Before
public void printTestMethod() {
System.out.println("\t" + testName.getMethodName());
}
@Test
public void testcloneUndoPlayInvalid() {
TicTacToe game = new TicTacToe(2,2,2);
assertEquals(null, game.cloneUndoPlay(99));
}
@Test
public void testcloneUndoEmptySpot() {
TicTacToe game = new TicTacToe(2,2,2);
assertEquals(null, game.cloneUndoPlay(1));
}
@Test
public void testcloneUndoWrongPiece() {
TicTacToe game = new TicTacToe(2,2,2);
game.play(1);
game.play(2);
game.play(3);
assertEquals(GameState.XWIN, game.gameState);
assertEquals(null, game.cloneUndoPlay(2));
}
@Test
public void testcloneUndoLastMove() {
TicTacToe game = new TicTacToe(2,2,2);
game.play(1);
game.play(2);
game.play(3);
assertEquals(GameState.XWIN, game.gameState);
TicTacToe cloned = game.cloneUndoPlay(3);
assertEquals(GameState.PLAYING, cloned.gameState);
assertEquals(2, cloned.numRounds);
assertEquals(0, cloned.lastPlayedPosition);
assertEquals(CellValue.X, cloned.nextPlayer());
assertEquals(CellValue.X, game.board[0]);
assertEquals(CellValue.O, game.board[1]);
assertEquals(CellValue.X, game.board[2]);
assertEquals(CellValue.EMPTY, game.board[3]);
assertEquals(CellValue.X, cloned.board[0]);
assertEquals(CellValue.O, cloned.board[1]);
assertEquals(CellValue.EMPTY, cloned.board[2]);
assertEquals(CellValue.EMPTY, cloned.board[3]);
}
@Test
public void testcloneUndoAnyValidMove() {
TicTacToe game = new TicTacToe(2,2,2);
game.play(1);
game.play(2);
game.play(3);
assertEquals(GameState.XWIN, game.gameState);
TicTacToe cloned = game.cloneUndoPlay(1);
assertEquals(GameState.PLAYING, cloned.gameState);
assertEquals(2, cloned.numRounds);
assertEquals(0, cloned.lastPlayedPosition);
assertEquals(CellValue.X, cloned.nextPlayer());
assertEquals(CellValue.X, game.board[0]);
assertEquals(CellValue.O, game.board[1]);
assertEquals(CellValue.X, game.board[2]);
assertEquals(CellValue.EMPTY, game.board[3]);
assertEquals(CellValue.EMPTY, cloned.board[0]);
assertEquals(CellValue.O, cloned.board[1]);
assertEquals(CellValue.X, cloned.board[2]);
assertEquals(CellValue.EMPTY, cloned.board[3]);
}
} | UTF-8 | Java | 2,727 | java | TestCloneUndo.java | Java | []
| null | []
| import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.rules.TestName;
import org.junit.Rule;
import java.util.Arrays;
import static org.junit.Assert.*;
public class TestCloneUndo {
@Rule
public Timeout globalTimeout = Timeout.seconds(1); // 1 seconds max per method tested
@Rule
public TestName testName = new TestName();
@Before
public void printTestMethod() {
System.out.println("\t" + testName.getMethodName());
}
@Test
public void testcloneUndoPlayInvalid() {
TicTacToe game = new TicTacToe(2,2,2);
assertEquals(null, game.cloneUndoPlay(99));
}
@Test
public void testcloneUndoEmptySpot() {
TicTacToe game = new TicTacToe(2,2,2);
assertEquals(null, game.cloneUndoPlay(1));
}
@Test
public void testcloneUndoWrongPiece() {
TicTacToe game = new TicTacToe(2,2,2);
game.play(1);
game.play(2);
game.play(3);
assertEquals(GameState.XWIN, game.gameState);
assertEquals(null, game.cloneUndoPlay(2));
}
@Test
public void testcloneUndoLastMove() {
TicTacToe game = new TicTacToe(2,2,2);
game.play(1);
game.play(2);
game.play(3);
assertEquals(GameState.XWIN, game.gameState);
TicTacToe cloned = game.cloneUndoPlay(3);
assertEquals(GameState.PLAYING, cloned.gameState);
assertEquals(2, cloned.numRounds);
assertEquals(0, cloned.lastPlayedPosition);
assertEquals(CellValue.X, cloned.nextPlayer());
assertEquals(CellValue.X, game.board[0]);
assertEquals(CellValue.O, game.board[1]);
assertEquals(CellValue.X, game.board[2]);
assertEquals(CellValue.EMPTY, game.board[3]);
assertEquals(CellValue.X, cloned.board[0]);
assertEquals(CellValue.O, cloned.board[1]);
assertEquals(CellValue.EMPTY, cloned.board[2]);
assertEquals(CellValue.EMPTY, cloned.board[3]);
}
@Test
public void testcloneUndoAnyValidMove() {
TicTacToe game = new TicTacToe(2,2,2);
game.play(1);
game.play(2);
game.play(3);
assertEquals(GameState.XWIN, game.gameState);
TicTacToe cloned = game.cloneUndoPlay(1);
assertEquals(GameState.PLAYING, cloned.gameState);
assertEquals(2, cloned.numRounds);
assertEquals(0, cloned.lastPlayedPosition);
assertEquals(CellValue.X, cloned.nextPlayer());
assertEquals(CellValue.X, game.board[0]);
assertEquals(CellValue.O, game.board[1]);
assertEquals(CellValue.X, game.board[2]);
assertEquals(CellValue.EMPTY, game.board[3]);
assertEquals(CellValue.EMPTY, cloned.board[0]);
assertEquals(CellValue.O, cloned.board[1]);
assertEquals(CellValue.X, cloned.board[2]);
assertEquals(CellValue.EMPTY, cloned.board[3]);
}
} | 2,727 | 0.70187 | 0.682802 | 102 | 25.745098 | 21.116709 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.95098 | false | false | 15 |
3640c6ea31470961427cf8191853120c9f4a5901 | 28,647,431,892,557 | 53639da6952556e4c5f5cf5de49594244d72ba42 | /src/main/java/com/fuyouj/aspect/ServiceTimeCalculatorAspect.java | 75610b73150be40b751341e25d7c281e7f206de7 | []
| no_license | carpediem2/simpleframework | https://github.com/carpediem2/simpleframework | 9dcf95be63de0f5a60e073161df0bacb556f00ab | 0f2daf534ed3ef52b18a71da1df6a8d329820244 | refs/heads/master | 2023-04-09T13:20:48.009000 | 2020-06-23T02:35:43 | 2020-06-23T02:35:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fuyouj.aspect;
import com.framework.aop.annotation.Aspect;
import com.framework.aop.annotation.Order;
import com.framework.aop.aspect.DefaultAspect;
import com.framework.core.annotation.Controller;
import com.framework.core.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Method;
/**
* @Desc
* @Author FuYouJ
* @date 2020/6/1 14:09
*/
/**
* 切面类
*/
@Slf4j
//@Aspect(Service.class)
//@Aspect(pointCut = "within(com.fuyouj.controller.superadmin.*)")
@Order(10)
public class ServiceTimeCalculatorAspect implements DefaultAspect {
private long timeStampCache;
@Override
public void before(Class<?> targetClass, Method method, Object[] args) throws Throwable {
log.info("service开始计时,执行的类是[{}],执行的方法是[{}],参数是[{}]",
targetClass.getName(),method.getName(),args);
timeStampCache = System.currentTimeMillis();
}
@Override
public Object afterReturning(Class<?> targetClass, Method method, Object[] args, Object returnValue) throws Throwable {
timeStampCache = System.currentTimeMillis() - timeStampCache;
log.info("service结束计时,执行的类是[{}],执行的方法是[{}],参数是[{}],执行的时间是[{}] ms",
targetClass.getName(),method.getName(),args,timeStampCache);
return returnValue;
}
@Override
public void afterThrowing(Class<?> targetClass, Method method, Object[] args, Throwable e) throws Throwable {
}
} | UTF-8 | Java | 1,529 | java | ServiceTimeCalculatorAspect.java | Java | [
{
"context": "java.lang.reflect.Method;\n\n/**\n * @Desc\n * @Author FuYouJ\n * @date 2020/6/1 14:09\n */\n\n/**\n * 切面类\n */\n@Slf4",
"end": 356,
"score": 0.9783385396003723,
"start": 350,
"tag": "USERNAME",
"value": "FuYouJ"
}
]
| null | []
| package com.fuyouj.aspect;
import com.framework.aop.annotation.Aspect;
import com.framework.aop.annotation.Order;
import com.framework.aop.aspect.DefaultAspect;
import com.framework.core.annotation.Controller;
import com.framework.core.annotation.Service;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Method;
/**
* @Desc
* @Author FuYouJ
* @date 2020/6/1 14:09
*/
/**
* 切面类
*/
@Slf4j
//@Aspect(Service.class)
//@Aspect(pointCut = "within(com.fuyouj.controller.superadmin.*)")
@Order(10)
public class ServiceTimeCalculatorAspect implements DefaultAspect {
private long timeStampCache;
@Override
public void before(Class<?> targetClass, Method method, Object[] args) throws Throwable {
log.info("service开始计时,执行的类是[{}],执行的方法是[{}],参数是[{}]",
targetClass.getName(),method.getName(),args);
timeStampCache = System.currentTimeMillis();
}
@Override
public Object afterReturning(Class<?> targetClass, Method method, Object[] args, Object returnValue) throws Throwable {
timeStampCache = System.currentTimeMillis() - timeStampCache;
log.info("service结束计时,执行的类是[{}],执行的方法是[{}],参数是[{}],执行的时间是[{}] ms",
targetClass.getName(),method.getName(),args,timeStampCache);
return returnValue;
}
@Override
public void afterThrowing(Class<?> targetClass, Method method, Object[] args, Throwable e) throws Throwable {
}
} | 1,529 | 0.700348 | 0.689895 | 46 | 30.217392 | 31.740053 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false | 15 |
21454480a8356abd8d80eca9ba8f6c13fa0b0728 | 25,795,573,613,335 | 2b323f37747081946551b3618f07a31b6227a0dc | /src/main/java/com/cowerling/pmn/web/LoginController.java | 0a496d6947323aa541b2a1c63f6dfb5587c3e683 | []
| no_license | Cowerling/PMNResultManage | https://github.com/Cowerling/PMNResultManage | c62a0f1913726953136b31e0949d8f9cf10e0150 | 5f01665bd6f05a37c2340753229a528f70fc4844 | refs/heads/master | 2021-06-26T22:06:37.752000 | 2019-04-14T13:48:38 | 2019-04-14T13:48:38 | 137,566,787 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cowerling.pmn.web;
import com.cowerling.pmn.web.message.ErrorMessage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/login")
public class LoginController {
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String login(@RequestParam(value = "error", required = false) String error, Model model) {
if(error != null) {
model.addAttribute("error", ErrorMessage.LOGIN_FAILED);
}
return "login";
}
}
| UTF-8 | Java | 738 | java | LoginController.java | Java | []
| null | []
| package com.cowerling.pmn.web;
import com.cowerling.pmn.web.message.ErrorMessage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/login")
public class LoginController {
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String login(@RequestParam(value = "error", required = false) String error, Model model) {
if(error != null) {
model.addAttribute("error", ErrorMessage.LOGIN_FAILED);
}
return "login";
}
}
| 738 | 0.749322 | 0.749322 | 20 | 35.900002 | 27.593296 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 15 |
a432d3ef0a01767950590204031d69e9b5157671 | 34,849,364,655,182 | a58a4ab81a25a38da000d0c5e8c326ef4683650d | /cloning/fluidity-cloning/src/test/java/com/innometa/fluidity/cloning/CustomActivationGroup2.java | 567e7a8b7381e87e39ef2eec870bc684ca01aaec | []
| no_license | vijayvani/fluidity-cloning | https://github.com/vijayvani/fluidity-cloning | d8c37c0e4c60d0b177904f213ac033f99973df1a | 606957124ea779b8184b7e5ba8683c3fb60ae181 | refs/heads/master | 2020-05-16T08:54:23.296000 | 2014-12-26T10:35:31 | 2014-12-26T10:35:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.innometa.fluidity.cloning;
interface CustomActivationGroup2{} | UTF-8 | Java | 76 | java | CustomActivationGroup2.java | Java | []
| null | []
| package com.innometa.fluidity.cloning;
interface CustomActivationGroup2{} | 76 | 0.842105 | 0.828947 | 3 | 24 | 17.048948 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 15 |
58d6960e3ef3fad616fa82725fb2b11cab08ee04 | 901,943,196,724 | 9402426e6568fe5ca3572536749a2bed14025548 | /task2/src/Runner.java | d9e59c9d81245c076b9b687e13d1d9d011dac3ee | []
| no_license | maxim-siniakov/javaCourse | https://github.com/maxim-siniakov/javaCourse | f1cd7ecb08ecb0705e4ecabe0919798b5a559db5 | d9ed869d16bab9fd24622b57a7292faa95ba8030 | refs/heads/master | 2021-01-10T07:27:05.101000 | 2016-03-14T11:28:39 | 2016-03-14T11:28:39 | 52,734,854 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by max on 28.02.16.
*/
import java.util.DoubleSummaryStatistics;
import java.util.Scanner;
public class Runner {
public static void main(String[] args) {
String e;
int n = 0;
double a = 0;
Scanner sc = new Scanner(System.in);
System.out.println("please insert number N:");
n = sc.nextInt();
System.out.println("please insert epsil");
e = sc.next();
double epsil = Double.valueOf(e);
double minValue = 0;
int min = 0;
for (int i = 1; i < n; i++) {
a = 1.0 / ((i + 1) * (i + 1));
if (min == 0 & a < epsil) {
min = i;
System.out.println(a);
} else {
System.out.println(a);
}
}
System.out.println("minimal number of element of sequense: " + min);
}
} | UTF-8 | Java | 882 | java | Runner.java | Java | [
{
"context": "/**\n * Created by max on 28.02.16.\n */\nimport java.util.DoubleSummarySt",
"end": 21,
"score": 0.9560368657112122,
"start": 18,
"tag": "NAME",
"value": "max"
}
]
| null | []
| /**
* Created by max on 28.02.16.
*/
import java.util.DoubleSummaryStatistics;
import java.util.Scanner;
public class Runner {
public static void main(String[] args) {
String e;
int n = 0;
double a = 0;
Scanner sc = new Scanner(System.in);
System.out.println("please insert number N:");
n = sc.nextInt();
System.out.println("please insert epsil");
e = sc.next();
double epsil = Double.valueOf(e);
double minValue = 0;
int min = 0;
for (int i = 1; i < n; i++) {
a = 1.0 / ((i + 1) * (i + 1));
if (min == 0 & a < epsil) {
min = i;
System.out.println(a);
} else {
System.out.println(a);
}
}
System.out.println("minimal number of element of sequense: " + min);
}
} | 882 | 0.484127 | 0.465986 | 33 | 25.757576 | 18.099104 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606061 | false | false | 15 |
59f11a2b7340dde00ccbb7b52233632d66ba4f8d | 867,583,417,540 | 2e9f7c041986f3b82b892baa0e1bd6189b80d9d4 | /src/org/tekkotsu/policies/AppEditLayoutPolicy.java | 64c5558de5a319a6ef3eb95d8c23c2d7cfa40558 | []
| no_license | toledoalbert/ComposerUIAPI | https://github.com/toledoalbert/ComposerUIAPI | 56d48623680faf5e756edfdc890a6df6266279ee | b358f72e5c377a78c1e14583ab3f939493588922 | refs/heads/master | 2016-09-06T21:50:31.028000 | 2013-09-26T20:50:04 | 2013-09-26T20:50:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.tekkotsu.policies;
import org.eclipse.gef.EditPart;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.XYLayoutEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.tekkotsu.api.NodeInstance;
import org.tekkotsu.api.SetupMachine;
import org.tekkotsu.commands.AbstractLayoutCommand;
import org.tekkotsu.commands.NodeClassChangeLayoutCommand;
import org.tekkotsu.commands.NodeInstanceChangeLayoutCommand;
import org.tekkotsu.commands.NodeInstanceCreateCommand;
import org.tekkotsu.commands.SetupMachineChangeLayoutCommand;
import org.tekkotsu.gef.NodeClassPart;
import org.tekkotsu.gef.NodeInstanceFigure;
import org.tekkotsu.gef.NodeInstancePart;
import org.tekkotsu.gef.SetupMachinePart;
public class AppEditLayoutPolicy extends XYLayoutEditPolicy{
@Override
protected Command createChangeConstraintCommand(EditPart child, Object constraint) {
AbstractLayoutCommand command = null;
if(child instanceof NodeClassPart){
command = new NodeClassChangeLayoutCommand();
}else if (child instanceof SetupMachinePart) {
command = new SetupMachineChangeLayoutCommand();
/*else if (child instanceof SubConnectionEditPart){
command = new MoveBendpointCommand();*/
} else if (child instanceof NodeInstancePart) {
command = new NodeInstanceChangeLayoutCommand();
}
//Set the model to the model of the right editpart
command.setModel(child.getModel());
//Set the constraint of the model
command.setConstraint((Rectangle)constraint);
return command;
}
@Override
protected Command getCreateCommand(CreateRequest request) {
if (request.getType() == REQ_CREATE && getHost() instanceof SetupMachinePart) {
//Create the nodeinstance creation command
NodeInstanceCreateCommand cmd = new NodeInstanceCreateCommand();
//Get the host model and the new object
SetupMachine set = (SetupMachine) getHost().getModel();
NodeInstance nod = (NodeInstance) request.getNewObject();
//Graphical objects
cmd.setSetupMachine(set);
cmd.setNodeInstance(nod);
Rectangle constraint = (Rectangle)getConstraintFor(request);
constraint.x = (constraint.x < 0) ? 0 : constraint.x;
constraint.y = (constraint.y < 0) ? 0 : constraint.y;
constraint.width = (constraint.width <= 0) ?
NodeInstanceFigure.NODEINSTANCE_FIGURE_DEFWIDTH : constraint.width;
constraint.height = (constraint.height <= 0) ?
NodeInstanceFigure.NODEINSTANCE_FIGURE_DEFHEIGHT : constraint.height;
cmd.setLayout(constraint);
//Real objects
//composer.ClassView.getNodeClass().getSetupMachine().addNode(cmd.ge);
System.out.println("create something");
return cmd;
}
return null;
}
}
| UTF-8 | Java | 2,850 | java | AppEditLayoutPolicy.java | Java | []
| null | []
| package org.tekkotsu.policies;
import org.eclipse.gef.EditPart;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.XYLayoutEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.tekkotsu.api.NodeInstance;
import org.tekkotsu.api.SetupMachine;
import org.tekkotsu.commands.AbstractLayoutCommand;
import org.tekkotsu.commands.NodeClassChangeLayoutCommand;
import org.tekkotsu.commands.NodeInstanceChangeLayoutCommand;
import org.tekkotsu.commands.NodeInstanceCreateCommand;
import org.tekkotsu.commands.SetupMachineChangeLayoutCommand;
import org.tekkotsu.gef.NodeClassPart;
import org.tekkotsu.gef.NodeInstanceFigure;
import org.tekkotsu.gef.NodeInstancePart;
import org.tekkotsu.gef.SetupMachinePart;
public class AppEditLayoutPolicy extends XYLayoutEditPolicy{
@Override
protected Command createChangeConstraintCommand(EditPart child, Object constraint) {
AbstractLayoutCommand command = null;
if(child instanceof NodeClassPart){
command = new NodeClassChangeLayoutCommand();
}else if (child instanceof SetupMachinePart) {
command = new SetupMachineChangeLayoutCommand();
/*else if (child instanceof SubConnectionEditPart){
command = new MoveBendpointCommand();*/
} else if (child instanceof NodeInstancePart) {
command = new NodeInstanceChangeLayoutCommand();
}
//Set the model to the model of the right editpart
command.setModel(child.getModel());
//Set the constraint of the model
command.setConstraint((Rectangle)constraint);
return command;
}
@Override
protected Command getCreateCommand(CreateRequest request) {
if (request.getType() == REQ_CREATE && getHost() instanceof SetupMachinePart) {
//Create the nodeinstance creation command
NodeInstanceCreateCommand cmd = new NodeInstanceCreateCommand();
//Get the host model and the new object
SetupMachine set = (SetupMachine) getHost().getModel();
NodeInstance nod = (NodeInstance) request.getNewObject();
//Graphical objects
cmd.setSetupMachine(set);
cmd.setNodeInstance(nod);
Rectangle constraint = (Rectangle)getConstraintFor(request);
constraint.x = (constraint.x < 0) ? 0 : constraint.x;
constraint.y = (constraint.y < 0) ? 0 : constraint.y;
constraint.width = (constraint.width <= 0) ?
NodeInstanceFigure.NODEINSTANCE_FIGURE_DEFWIDTH : constraint.width;
constraint.height = (constraint.height <= 0) ?
NodeInstanceFigure.NODEINSTANCE_FIGURE_DEFHEIGHT : constraint.height;
cmd.setLayout(constraint);
//Real objects
//composer.ClassView.getNodeClass().getSetupMachine().addNode(cmd.ge);
System.out.println("create something");
return cmd;
}
return null;
}
}
| 2,850 | 0.754386 | 0.75193 | 100 | 27.5 | 24.913651 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.16 | false | false | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.