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
495018ebaa7714c478f6bf33321cb8a63c504d9a
944,892,806,469
a4f570823c542713a4cfa5d9058132e15bc695c3
/datastructures/src/main/java/queues/LinkedListBasedQueue.java
5c45b056c5f1a36c4305faa0e31309889898a2a7
[]
no_license
raul1991/DesignPatterns
https://github.com/raul1991/DesignPatterns
1982cf66ef0e9e917546370870b058c096033b86
f6e6a576b39d92312d9bf6272e0b0c31448e67ea
refs/heads/master
2021-01-10T22:30:27.204000
2020-04-26T14:52:25
2020-04-26T14:52:25
70,399,736
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package queues; public class LinkedListBasedQueue<R> { private Node<R> front; private Node<R> rear; private int size; /** * Adds an item at the rear. * @param data the item to be added */ public void enqueue(R data) { Node<R> newNode = new Node<>(data); newNode.data = data; newNode.next = null; if (isEmpty()) { front = rear = newNode; } else { rear.next = newNode; rear = newNode; } ++size; } public boolean isEmpty() { return size == 0; } /** * Removes from the front. * @return R the item removed */ public R dequeue() { if (isEmpty()) throw new IllegalStateException("Queue is empty already."); R data = front.data; front = front.next; --size; return data; } public int size() { return size; } public R front() { return front.data; } public void clear() { if (isEmpty()) throw new IllegalStateException("Empty queue exception"); int pos = -1; Node<R> ptr = front; while (++pos < size) { ptr = ptr.next; front.data = null; front.next = null; front = ptr; } size = 0; } private class Node<E> { private R data; private Node<E> next; private Node(R data) { this.data = data; } } }
UTF-8
Java
1,501
java
LinkedListBasedQueue.java
Java
[]
null
[]
package queues; public class LinkedListBasedQueue<R> { private Node<R> front; private Node<R> rear; private int size; /** * Adds an item at the rear. * @param data the item to be added */ public void enqueue(R data) { Node<R> newNode = new Node<>(data); newNode.data = data; newNode.next = null; if (isEmpty()) { front = rear = newNode; } else { rear.next = newNode; rear = newNode; } ++size; } public boolean isEmpty() { return size == 0; } /** * Removes from the front. * @return R the item removed */ public R dequeue() { if (isEmpty()) throw new IllegalStateException("Queue is empty already."); R data = front.data; front = front.next; --size; return data; } public int size() { return size; } public R front() { return front.data; } public void clear() { if (isEmpty()) throw new IllegalStateException("Empty queue exception"); int pos = -1; Node<R> ptr = front; while (++pos < size) { ptr = ptr.next; front.data = null; front.next = null; front = ptr; } size = 0; } private class Node<E> { private R data; private Node<E> next; private Node(R data) { this.data = data; } } }
1,501
0.486342
0.484344
71
20.140844
15.814323
82
false
false
0
0
0
0
0
0
0.422535
false
false
7
4ed1003311f62f2aec4d50607c6d39accb25620c
11,192,684,779,467
34e48b5109329fc0e6004a3c9df04415da7fbe4e
/main/src/com/alipay/siteprobe/core/model/rpc/AuthProcessorRsp.java
feac6635f83515d0c542d97cb8a44bd738e9bf3d
[]
no_license
RyanTech/myali
https://github.com/RyanTech/myali
29d3aede436938c94433149d5e9bf2869ec788fe
a3744bef7673cb7d612b047c0754abe8778b6242
refs/heads/master
2018-02-24T15:52:04.945000
2014-06-30T02:39:01
2014-06-30T02:39:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alipay.siteprobe.core.model.rpc; import java.io.Serializable; public class AuthProcessorRsp extends RpcBaseResult implements Serializable { public String failedMsg; public String gotoUrl; public String needUrl; public String otherAccessUrl; public String successMsg; } /* Location: /Users/don/DeSources/alipay/backup/zhifubaoqianbao_52/classes-dex2jar.jar * Qualified Name: com.alipay.siteprobe.core.model.rpc.AuthProcessorRsp * JD-Core Version: 0.6.2 */
UTF-8
Java
501
java
AuthProcessorRsp.java
Java
[]
null
[]
package com.alipay.siteprobe.core.model.rpc; import java.io.Serializable; public class AuthProcessorRsp extends RpcBaseResult implements Serializable { public String failedMsg; public String gotoUrl; public String needUrl; public String otherAccessUrl; public String successMsg; } /* Location: /Users/don/DeSources/alipay/backup/zhifubaoqianbao_52/classes-dex2jar.jar * Qualified Name: com.alipay.siteprobe.core.model.rpc.AuthProcessorRsp * JD-Core Version: 0.6.2 */
501
0.764471
0.752495
18
26.888889
25.912006
96
false
false
0
0
0
0
0
0
0.388889
false
false
7
b3598c62e3a75d8ffa73bf722d57385d88c12ed1
25,288,767,447,028
d21f2e6bdcdac6526449b0aa5d959a8a9ae706e3
/flinkcdc-mysql2es/flinkcdc-mysql2es-datastream/src/main/java/com/cny/cdc/domain/companys/entity/Company.java
0b5821cca903c2dbc900f68ee4fc3e456fbc760d
[]
no_license
menyin/gupaovip
https://github.com/menyin/gupaovip
f353ef0587f92adfab14caa56a1a8886d0296fc0
5ff52875eabb0ea9646d13c74d83437d10ce65c1
refs/heads/master
2023-08-31T20:47:57.159000
2023-08-09T03:18:17
2023-08-09T03:18:17
157,330,297
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cny.cdc.domain.companys.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.io.Serializable; /** * @Description: TODO * @author: geduo * @date: 2023年03月17日 16:00 */ @Data @NoArgsConstructor public class Company implements Serializable { /** * id */ private String id; /** * json */ private Json json; /** * 注册时间 */ private String regDate; /** * 在一页中的序号 */ private Integer pageIndex; /** * 页码 */ private String page; }
UTF-8
Java
799
java
Company.java
Java
[ { "context": "rializable;\n\n/**\n * @Description: TODO\n * @author: geduo\n * @date: 2023年03月17日 16:00\n */\n@Data\n@NoArgsCons", "end": 388, "score": 0.9996528625488281, "start": 383, "tag": "USERNAME", "value": "geduo" } ]
null
[]
package com.cny.cdc.domain.companys.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.io.Serializable; /** * @Description: TODO * @author: geduo * @date: 2023年03月17日 16:00 */ @Data @NoArgsConstructor public class Company implements Serializable { /** * id */ private String id; /** * json */ private Json json; /** * 注册时间 */ private String regDate; /** * 在一页中的序号 */ private Integer pageIndex; /** * 页码 */ private String page; }
799
0.662321
0.646675
44
16.431818
16.698391
68
false
false
0
0
0
0
0
0
0.295455
false
false
7
f2098b1c9617059492c09d20f789730342e7fafc
695,784,720,526
6cb6d33d73464e5b4421a9a07dac48663fab7e5a
/src/main/java/be/devriendt/advent/s2015/Day7Computer.java
0b036cfd344fd248fa3eb8bfd2a691c9ab75e9fd
[]
no_license
ddevrien/adventcode
https://github.com/ddevrien/adventcode
3f905490a66ad692661e1cc25eb5ae0b74a62731
08734e9fad5b04139001731fee9025c2ff369770
refs/heads/master
2022-12-23T00:03:45.473000
2022-12-20T17:18:24
2022-12-20T17:18:24
47,456,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.devriendt.advent.s2015; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Dennis on 14/12/2015. */ public class Day7Computer { private static final String ASSIGMENT = " -> "; private static final String AND = "AND"; private static final String OR = "OR"; private static final String LSHIFT = "LSHIFT"; private static final String RSHIFT = "RSHIFT"; private static final String NOT = "NOT"; private static final Pattern PATTERN = Pattern.compile("(\\w+) ?(\\w+)? ?(\\w+)?$"); public static int getWireSignalFromInstructions(String wireId, String resourcePath) throws URISyntaxException, IOException { return instructionsToWireSignal(wireId, Files.readAllLines(Paths.get(Day7Computer.class.getResource(resourcePath).toURI()))); } public static int instructionsToWireSignal(String wireId, List<String> instructions) { Map<String, String> assignmentMap = toAssignmentMap(instructions); return eval(wireId, assignmentMap); } private static int eval(String wireId, Map<String, String> assignmentMap) { if (isNumeric(wireId)) { // numeric assignment return Integer.parseInt(wireId); } int signal; String expression = assignmentMap.get(wireId); Matcher m = PATTERN.matcher(expression); m.find(); if (m.group(2) == null) { // wire assignment signal = eval(m.group(1), assignmentMap); } else if (m.group(2).equals(AND)) { signal = eval(m.group(1), assignmentMap) & eval(m.group(3), assignmentMap); } else if (m.group(2).equals(OR)) { signal = eval(m.group(1), assignmentMap) | eval(m.group(3), assignmentMap); } else if (m.group(2).equals(LSHIFT)) { signal = eval(m.group(1), assignmentMap) << Integer.parseInt(m.group(3)); } else if (m.group(2).equals(RSHIFT)) { signal = eval(m.group(1), assignmentMap) >> Integer.parseInt(m.group(3)); } else if (m.group(1).equals(NOT)) { signal = ~eval(m.group(2), assignmentMap) & 0xffff; } else { throw new IllegalArgumentException("Dunno"); } assignmentMap.put(wireId, String.valueOf(signal)); return signal; } private static Map<String,String> toAssignmentMap(List<String> instructions) { Map<String, String> assignmentMap = new HashMap<>(); for (String instruction: instructions) { String[] parts = instruction.split(ASSIGMENT); assignmentMap.put(parts[1], parts[0]); } return assignmentMap; } private static boolean isNumeric(String str) { return str.matches("\\d+"); } }
UTF-8
Java
2,949
java
Day7Computer.java
Java
[ { "context": "import java.util.regex.Pattern;\n\n/**\n * Created by Dennis on 14/12/2015.\n */\npublic class Day7Computer {\n\n ", "end": 316, "score": 0.9996729493141174, "start": 310, "tag": "NAME", "value": "Dennis" } ]
null
[]
package be.devriendt.advent.s2015; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Dennis on 14/12/2015. */ public class Day7Computer { private static final String ASSIGMENT = " -> "; private static final String AND = "AND"; private static final String OR = "OR"; private static final String LSHIFT = "LSHIFT"; private static final String RSHIFT = "RSHIFT"; private static final String NOT = "NOT"; private static final Pattern PATTERN = Pattern.compile("(\\w+) ?(\\w+)? ?(\\w+)?$"); public static int getWireSignalFromInstructions(String wireId, String resourcePath) throws URISyntaxException, IOException { return instructionsToWireSignal(wireId, Files.readAllLines(Paths.get(Day7Computer.class.getResource(resourcePath).toURI()))); } public static int instructionsToWireSignal(String wireId, List<String> instructions) { Map<String, String> assignmentMap = toAssignmentMap(instructions); return eval(wireId, assignmentMap); } private static int eval(String wireId, Map<String, String> assignmentMap) { if (isNumeric(wireId)) { // numeric assignment return Integer.parseInt(wireId); } int signal; String expression = assignmentMap.get(wireId); Matcher m = PATTERN.matcher(expression); m.find(); if (m.group(2) == null) { // wire assignment signal = eval(m.group(1), assignmentMap); } else if (m.group(2).equals(AND)) { signal = eval(m.group(1), assignmentMap) & eval(m.group(3), assignmentMap); } else if (m.group(2).equals(OR)) { signal = eval(m.group(1), assignmentMap) | eval(m.group(3), assignmentMap); } else if (m.group(2).equals(LSHIFT)) { signal = eval(m.group(1), assignmentMap) << Integer.parseInt(m.group(3)); } else if (m.group(2).equals(RSHIFT)) { signal = eval(m.group(1), assignmentMap) >> Integer.parseInt(m.group(3)); } else if (m.group(1).equals(NOT)) { signal = ~eval(m.group(2), assignmentMap) & 0xffff; } else { throw new IllegalArgumentException("Dunno"); } assignmentMap.put(wireId, String.valueOf(signal)); return signal; } private static Map<String,String> toAssignmentMap(List<String> instructions) { Map<String, String> assignmentMap = new HashMap<>(); for (String instruction: instructions) { String[] parts = instruction.split(ASSIGMENT); assignmentMap.put(parts[1], parts[0]); } return assignmentMap; } private static boolean isNumeric(String str) { return str.matches("\\d+"); } }
2,949
0.640556
0.629366
80
35.862499
29.402697
128
false
false
0
0
0
0
0
0
0.75
false
false
7
841805da9a3a9beacfedbfa5de7f7597f5bd1a63
17,265,768,541,649
0b7c8ad5dfbc9623b5921aa87566d349c3aa6720
/src/com/domain/AccionesGlobales.java
1c4e95858686b55c33843e830603a742b8a02d00
[]
no_license
EdgarOlveraFlores/Act_PolimorfismoHerenciaInterfaces
https://github.com/EdgarOlveraFlores/Act_PolimorfismoHerenciaInterfaces
01cb4fb0bd56b50aca42b522b2e9f18a9b4be4d8
0a952f73bd1eec1c7991cd672af86d21cb339387
refs/heads/master
2023-04-15T01:32:22.296000
2021-05-04T19:52:34
2021-05-04T19:52:34
364,370,562
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Interfaz SHAPE package com.domain; /** * * @author olver */ public interface AccionesGlobales { void area(); void perimetro(); }
UTF-8
Java
145
java
AccionesGlobales.java
Java
[ { "context": "rfaz SHAPE\n\npackage com.domain;\n\n/**\n *\n * @author olver\n */\npublic interface AccionesGlobales {\n void ", "end": 63, "score": 0.9987389445304871, "start": 58, "tag": "USERNAME", "value": "olver" } ]
null
[]
//Interfaz SHAPE package com.domain; /** * * @author olver */ public interface AccionesGlobales { void area(); void perimetro(); }
145
0.634483
0.634483
12
11
10.669271
35
false
false
0
0
0
0
0
0
0.25
false
false
7
d38d72270649d50b0275b15f2b10820aca0c06a1
15,298,673,521,828
f18b4b6aa10170ccce981fb543bada2cc38054b7
/WeatherWidget/src/main/java/com/lmjssjj/weatherwidget/common/GLRenderer.java
4b14b59e6e8fd8c4a50c96fee6cf9af9adad9ac1
[]
no_license
Ya-Wan/WeatherDemo
https://github.com/Ya-Wan/WeatherDemo
19c2190de3b9c1e8285bf0718dade0cf3839a739
85e45529ac248a731db89abcd5fb2eab1c327866
refs/heads/master
2021-08-07T14:46:53.896000
2017-11-08T11:08:43
2017-11-08T11:08:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lmjssjj.weatherwidget.common; import android.content.Context; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import com.lmjssjj.weatherwidget.R; import com.lmjssjj.weatherwidget.model.CurrentWeather; import com.lmjssjj.weatherwidget.shader.TextureShaderProgram; import com.lmjssjj.weatherwidget.utils.FontTextureUtil; import com.lmjssjj.weatherwidget.utils.MatrixState; import com.lmjssjj.weatherwidget.utils.TextureHelper; import com.lmjssjj.weatherwidget.utils.TimeAndDateUtil; import com.lmjssjj.weatherwidget.weather.commomtexture.DateTexture; import com.lmjssjj.weatherwidget.weather.commomtexture.TimeTexture; import com.lmjssjj.weatherwidget.weather.commomtexture.WeatherTexture; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by junjie.shi on 2017/11/2. */ public abstract class GLRenderer implements GLSurfaceView.Renderer,TimeAndDateUtil.TimeChangedCallback { public Context mContext; public TextureShaderProgram mTextureShaderProgram; public DateTexture mDateTexture; public TimeTexture mTimeTexture; public WeatherTexture mWeatherTexture; private TimeAndDateUtil mTimeAndDateUtil; private GLView glView; private CurrentWeather currentWeather; public GLRenderer(Context context){ this.mContext = context; } @Override public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { GLES20.glClearColor(0f, 0f, 0f, 0f); mTextureShaderProgram = new TextureShaderProgram(mContext); MatrixState.setInitStack(); mTimeAndDateUtil = new TimeAndDateUtil(mContext,this); mDateTexture = new DateTexture(mTimeAndDateUtil.getDateBitmap()); mTimeTexture = new TimeTexture(mTimeAndDateUtil.getTimeBitmap()); mWeatherTexture = new WeatherTexture(FontTextureUtil.createWeatherBitmap(mContext, currentWeather)); onCreated(); } @Override public void onSurfaceChanged(GL10 gl10, int width, int height) { GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; // 调用此方法计算产生透视投影矩阵 // MatrixState.setProjectFrustum(-1,1, -1, 1, 1, 5); // MatrixState.setProjectOrtho(-1,1, -1, 1, 20, 100); MatrixState.perspectiveM(45,ratio,1,5); // 调用此方法产生摄像机9参数位置矩阵 MatrixState.setCamera(0f, 0f, 3f, 0f, 0f, 0f, 0f, 1.0f, 0.0f); } @Override public void onDrawFrame(GL10 gl10) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); onDrawFrame(); TextureHelper.updateTexture(mDateTexture.mTextureId,mTimeAndDateUtil.getDateBitmap()); mDateTexture.bindData(mTextureShaderProgram); mDateTexture.draw(); TextureHelper.updateTexture(mTimeTexture.mTextureId,mTimeAndDateUtil.getTimeBitmap()); mTimeTexture.bindData(mTextureShaderProgram); mTimeTexture.draw(); TextureHelper.updateTexture(mWeatherTexture.mTextureId,FontTextureUtil.createWeatherBitmap(mContext,currentWeather)); mWeatherTexture.bindData(mTextureShaderProgram); mWeatherTexture.draw(); GLES20.glDisable(GLES20.GL_BLEND); } @Override public void timeChanged() { glView.requestRender(); } public abstract void onCreated(); public abstract void onDrawFrame(); public abstract void swing(float angle,int x,int y,int z); public void touchSwing(float angleX,float angleY){ mDateTexture.touchSwing(); mTimeTexture.touchSwing(); mWeatherTexture.touchSwing(); } public void setGlView(GLView glView) { this.glView = glView; } public void destroy() { mTimeAndDateUtil.unregisterReceiver(); } public void setCurrentWeather(CurrentWeather currentWeather) { this.currentWeather = currentWeather; } }
UTF-8
Java
4,083
java
GLRenderer.java
Java
[ { "context": "oedition.khronos.opengles.GL10;\n\n/**\n * Created by junjie.shi on 2017/11/2.\n */\n\npublic abstract class GLRender", "end": 849, "score": 0.9958950281143188, "start": 839, "tag": "USERNAME", "value": "junjie.shi" } ]
null
[]
package com.lmjssjj.weatherwidget.common; import android.content.Context; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import com.lmjssjj.weatherwidget.R; import com.lmjssjj.weatherwidget.model.CurrentWeather; import com.lmjssjj.weatherwidget.shader.TextureShaderProgram; import com.lmjssjj.weatherwidget.utils.FontTextureUtil; import com.lmjssjj.weatherwidget.utils.MatrixState; import com.lmjssjj.weatherwidget.utils.TextureHelper; import com.lmjssjj.weatherwidget.utils.TimeAndDateUtil; import com.lmjssjj.weatherwidget.weather.commomtexture.DateTexture; import com.lmjssjj.weatherwidget.weather.commomtexture.TimeTexture; import com.lmjssjj.weatherwidget.weather.commomtexture.WeatherTexture; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by junjie.shi on 2017/11/2. */ public abstract class GLRenderer implements GLSurfaceView.Renderer,TimeAndDateUtil.TimeChangedCallback { public Context mContext; public TextureShaderProgram mTextureShaderProgram; public DateTexture mDateTexture; public TimeTexture mTimeTexture; public WeatherTexture mWeatherTexture; private TimeAndDateUtil mTimeAndDateUtil; private GLView glView; private CurrentWeather currentWeather; public GLRenderer(Context context){ this.mContext = context; } @Override public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { GLES20.glClearColor(0f, 0f, 0f, 0f); mTextureShaderProgram = new TextureShaderProgram(mContext); MatrixState.setInitStack(); mTimeAndDateUtil = new TimeAndDateUtil(mContext,this); mDateTexture = new DateTexture(mTimeAndDateUtil.getDateBitmap()); mTimeTexture = new TimeTexture(mTimeAndDateUtil.getTimeBitmap()); mWeatherTexture = new WeatherTexture(FontTextureUtil.createWeatherBitmap(mContext, currentWeather)); onCreated(); } @Override public void onSurfaceChanged(GL10 gl10, int width, int height) { GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; // 调用此方法计算产生透视投影矩阵 // MatrixState.setProjectFrustum(-1,1, -1, 1, 1, 5); // MatrixState.setProjectOrtho(-1,1, -1, 1, 20, 100); MatrixState.perspectiveM(45,ratio,1,5); // 调用此方法产生摄像机9参数位置矩阵 MatrixState.setCamera(0f, 0f, 3f, 0f, 0f, 0f, 0f, 1.0f, 0.0f); } @Override public void onDrawFrame(GL10 gl10) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); onDrawFrame(); TextureHelper.updateTexture(mDateTexture.mTextureId,mTimeAndDateUtil.getDateBitmap()); mDateTexture.bindData(mTextureShaderProgram); mDateTexture.draw(); TextureHelper.updateTexture(mTimeTexture.mTextureId,mTimeAndDateUtil.getTimeBitmap()); mTimeTexture.bindData(mTextureShaderProgram); mTimeTexture.draw(); TextureHelper.updateTexture(mWeatherTexture.mTextureId,FontTextureUtil.createWeatherBitmap(mContext,currentWeather)); mWeatherTexture.bindData(mTextureShaderProgram); mWeatherTexture.draw(); GLES20.glDisable(GLES20.GL_BLEND); } @Override public void timeChanged() { glView.requestRender(); } public abstract void onCreated(); public abstract void onDrawFrame(); public abstract void swing(float angle,int x,int y,int z); public void touchSwing(float angleX,float angleY){ mDateTexture.touchSwing(); mTimeTexture.touchSwing(); mWeatherTexture.touchSwing(); } public void setGlView(GLView glView) { this.glView = glView; } public void destroy() { mTimeAndDateUtil.unregisterReceiver(); } public void setCurrentWeather(CurrentWeather currentWeather) { this.currentWeather = currentWeather; } }
4,083
0.729669
0.708779
116
33.663792
28.206427
125
false
false
0
0
0
0
0
0
0.913793
false
false
7
48faf9d4e73d14f27439a090ba946aa13b65f8b3
10,204,842,306,019
d689c3259400e0159324d5ca191d32619d527c0c
/app/src/main/java/com/mycompany/vplan/view/IDeskView.java
160921f2a44b08ef1a641fe26aff5a8f66c8613b
[]
no_license
lihongmindev/V_Plan
https://github.com/lihongmindev/V_Plan
419cf2ad93729e6453a308d36be06cfe60225403
813282a71253ffe720aae0b96ad827bdf66d0c0e
refs/heads/master
2020-06-06T04:24:36.092000
2019-07-10T13:27:22
2019-07-10T13:27:22
192,636,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mycompany.vplan.view; import com.mycompany.vplan.bean.CardList; import java.util.List; public interface IDeskView { void showDeskCard(List<CardList> cardLists); }
UTF-8
Java
182
java
IDeskView.java
Java
[]
null
[]
package com.mycompany.vplan.view; import com.mycompany.vplan.bean.CardList; import java.util.List; public interface IDeskView { void showDeskCard(List<CardList> cardLists); }
182
0.78022
0.78022
9
19.222221
18.31076
48
false
false
0
0
0
0
0
0
0.444444
false
false
7
c99cc2d16fea3c2dea1ca880abbcd9709bb9566b
9,036,611,203,886
35029f02d7573415d6fc558cfeeb19c7bfa1e3cc
/gs-accessing-data-jpa-complete/src/main/java/hello/service/CustomerService1997.java
b0f3c52f651be742e165b92a67159051a8be7013
[]
no_license
MirekSz/spring-boot-slow-startup
https://github.com/MirekSz/spring-boot-slow-startup
e06fe9d4f3831ee1e79cf3735f6ceb8c50340cbe
3b1e9e4ebd4a95218b142b7eb397d0eaa309e771
refs/heads/master
2021-06-25T22:50:21.329000
2017-02-19T19:08:24
2017-02-19T19:08:24
59,591,530
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package hello.service; import org.springframework.stereotype.Service; @Service public class CustomerService1997 { }
UTF-8
Java
119
java
CustomerService1997.java
Java
[]
null
[]
package hello.service; import org.springframework.stereotype.Service; @Service public class CustomerService1997 { }
119
0.815126
0.781513
8
13.875
16.885181
46
false
false
0
0
0
0
0
0
0.25
false
false
7
cb447ba06f55cd6d1c7a6ffd9e3e8e53832ad4ad
9,036,611,203,909
9cc921b30b7b84f32368bcb5e2506bf8cdf35dc9
/src/main/java/ac/artemis/anticheat/api/check/CheckInfo.java
4d3d0ade5de1e3d2b7dc81801c8409ec45f00e4d
[ "MIT", "Apache-2.0" ]
permissive
artemisac/artemis-java-api
https://github.com/artemisac/artemis-java-api
58e2a1ff9428198aae7fc9bc085f630083047486
c4280719fdd9cc7350da1e9c09281cf4e0fd0d60
refs/heads/master
2023-06-29T16:52:58.006000
2021-08-05T23:39:43
2021-08-05T23:39:43
356,000,605
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ac.artemis.anticheat.api.check; import ac.artemis.anticheat.api.check.type.Stage; import ac.artemis.anticheat.api.check.type.Type; public interface CheckInfo { /** * Type of the Check * Eg: KILLAURA */ Type getType(); /** * Variable attached of the check * Eg: A, Friction, MotionXZ */ String getVar(); /** * Category variable * eg: KillAura visual */ String getVisualCategory(); /** * Category variable * eg: KillAura visual */ String getVisualName(); /** * Whether the verbose should decrease over time */ boolean isNoDrop(); /** * Stage of the check. * Eg: EXPERIMENTAL, RELEASE * The following are available: * EXPERIMENTING: Will output logs to experimental verbose * @see Stage#EXPERIMENTING * TESTING: Will output logs to experimental verbose * @see Stage#TESTING * FALSING: Will output logs to experimental verbose * @see Stage#FALSING * PRE_RELEASE: Will output logs to verbose but won't stack. Alerts only * @see Stage#PRE_RELEASE * RELEASE: Will output logs and will stack alerts for potential violations * @see Stage#RELEASE */ Stage getStage(); /** * Maximum amount of verboses before a violation. This value is hardcoded */ int getMaxVb(); int getDelayBetweenAlerts(); /** * Maximum amount of violations before the execution of a ban. This value is configurable * @see ConfigManager#getChecks() */ int getMaxVl(); /** * Configurable option whether the check is enabled or not. */ boolean isEnabled(); /** * Configurable option whether the check can ban or not. */ boolean isBannable(); /** * Configurable option whether the check setbacks or not. */ boolean isSetback(); /** * Hardcoded option which requires the need of NMS * @deprecated Since the use of NMS collisions in the handlers */ @Deprecated boolean isCompatibleNMS(); /** * Type of the Check * Eg: KILLAURA */ void setType(Type type); /** * Variable attached of the check * Eg: A, Friction, MotionXZ */ void setVar(String var); /** * Category variable * eg: KillAura visual */ void setVisualCategory(String visualCategory); /** * Category variable * eg: KillAura visual */ void setVisualName(String visualName); /** * Whether the verbose should decrease over time */ void setNoDrop(boolean noDrop); /** * Stage of the check. * Eg: EXPERIMENTAL, RELEASE * The following are available: * EXPERIMENTING: Will output logs to experimental verbose * @see Stage#EXPERIMENTING * TESTING: Will output logs to experimental verbose * @see Stage#TESTING * FALSING: Will output logs to experimental verbose * @see Stage#FALSING * PRE_RELEASE: Will output logs to verbose but won't stack. Alerts only * @see Stage#PRE_RELEASE * RELEASE: Will output logs and will stack alerts for potential violations * @see Stage#RELEASE */ void setStage(Stage stage); /** * Maximum amount of verboses before a violation. This value is hardcoded */ void setMaxVb(int maxVb); void setDelayBetweenAlerts(int delayBetweenAlerts); /** * Maximum amount of violations before the execution of a ban. This value is configurable * @see ConfigManager#setChecks() */ void setMaxVl(int maxVl); /** * Configurable option whether the check is enabled or not. */ void setEnabled(boolean enabled); /** * Configurable option whether the check can ban or not. */ void setBannable(boolean bannable); /** * Configurable option whether the check setbacks or not. */ void setSetback(boolean setback); /** * Saves the check configuration to files */ void save(); }
UTF-8
Java
4,041
java
CheckInfo.java
Java
[]
null
[]
package ac.artemis.anticheat.api.check; import ac.artemis.anticheat.api.check.type.Stage; import ac.artemis.anticheat.api.check.type.Type; public interface CheckInfo { /** * Type of the Check * Eg: KILLAURA */ Type getType(); /** * Variable attached of the check * Eg: A, Friction, MotionXZ */ String getVar(); /** * Category variable * eg: KillAura visual */ String getVisualCategory(); /** * Category variable * eg: KillAura visual */ String getVisualName(); /** * Whether the verbose should decrease over time */ boolean isNoDrop(); /** * Stage of the check. * Eg: EXPERIMENTAL, RELEASE * The following are available: * EXPERIMENTING: Will output logs to experimental verbose * @see Stage#EXPERIMENTING * TESTING: Will output logs to experimental verbose * @see Stage#TESTING * FALSING: Will output logs to experimental verbose * @see Stage#FALSING * PRE_RELEASE: Will output logs to verbose but won't stack. Alerts only * @see Stage#PRE_RELEASE * RELEASE: Will output logs and will stack alerts for potential violations * @see Stage#RELEASE */ Stage getStage(); /** * Maximum amount of verboses before a violation. This value is hardcoded */ int getMaxVb(); int getDelayBetweenAlerts(); /** * Maximum amount of violations before the execution of a ban. This value is configurable * @see ConfigManager#getChecks() */ int getMaxVl(); /** * Configurable option whether the check is enabled or not. */ boolean isEnabled(); /** * Configurable option whether the check can ban or not. */ boolean isBannable(); /** * Configurable option whether the check setbacks or not. */ boolean isSetback(); /** * Hardcoded option which requires the need of NMS * @deprecated Since the use of NMS collisions in the handlers */ @Deprecated boolean isCompatibleNMS(); /** * Type of the Check * Eg: KILLAURA */ void setType(Type type); /** * Variable attached of the check * Eg: A, Friction, MotionXZ */ void setVar(String var); /** * Category variable * eg: KillAura visual */ void setVisualCategory(String visualCategory); /** * Category variable * eg: KillAura visual */ void setVisualName(String visualName); /** * Whether the verbose should decrease over time */ void setNoDrop(boolean noDrop); /** * Stage of the check. * Eg: EXPERIMENTAL, RELEASE * The following are available: * EXPERIMENTING: Will output logs to experimental verbose * @see Stage#EXPERIMENTING * TESTING: Will output logs to experimental verbose * @see Stage#TESTING * FALSING: Will output logs to experimental verbose * @see Stage#FALSING * PRE_RELEASE: Will output logs to verbose but won't stack. Alerts only * @see Stage#PRE_RELEASE * RELEASE: Will output logs and will stack alerts for potential violations * @see Stage#RELEASE */ void setStage(Stage stage); /** * Maximum amount of verboses before a violation. This value is hardcoded */ void setMaxVb(int maxVb); void setDelayBetweenAlerts(int delayBetweenAlerts); /** * Maximum amount of violations before the execution of a ban. This value is configurable * @see ConfigManager#setChecks() */ void setMaxVl(int maxVl); /** * Configurable option whether the check is enabled or not. */ void setEnabled(boolean enabled); /** * Configurable option whether the check can ban or not. */ void setBannable(boolean bannable); /** * Configurable option whether the check setbacks or not. */ void setSetback(boolean setback); /** * Saves the check configuration to files */ void save(); }
4,041
0.627073
0.627073
166
23.343374
22.297743
93
false
false
0
0
0
0
0
0
0.210843
false
false
7
d2dddc5bea0cfb8670eafea94253783e78724364
4,449,586,136,622
5ba14c8de364f1d54b6f2d91c4fc270a61ed4a20
/org.easycloud.platform.visualpage/src/main/java/org/easycloud/platform/visualpage/ui/view/BaseRender.java
d35b1cf231b2ffd005f737d4862f26d3d9fba2db
[]
no_license
xwh123807/easycloud
https://github.com/xwh123807/easycloud
00b6ecdb65370eb9d8a6399fc8866a5dac16ee88
e25c4e61f2d84aa690ca571b3f807ca92c86e321
refs/heads/master
2021-01-13T04:48:22.287000
2017-07-21T11:09:00
2017-07-21T11:09:00
78,643,970
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.easycloud.platform.visualpage.ui.view; import org.easycloud.platform.metadata.service.EntityMetaData; import org.easycloud.platform.metadata.service.ServiceUtil; import org.easycloud.platform.visualpage.ui.ViewType; public abstract class BaseRender { private ViewType viewType = ViewType.VIEW; public BaseRender(final ViewType viewType) { this.viewType = viewType; } public ViewType getViewType() { return viewType; } /** * 获取实体元模型 * * @param entityName * @return */ public EntityMetaData getEntityMataData(final String entityName) { return ServiceUtil.getEntityMetaDataService().getEntityMetaData(entityName); } public String html() { switch (getViewType()) { case PRINT: return htmlForPrint(); default: return htmlForView(); } } public String htmlForView() { return ""; } public String htmlForPrint() { return htmlForView(); } }
UTF-8
Java
914
java
BaseRender.java
Java
[]
null
[]
package org.easycloud.platform.visualpage.ui.view; import org.easycloud.platform.metadata.service.EntityMetaData; import org.easycloud.platform.metadata.service.ServiceUtil; import org.easycloud.platform.visualpage.ui.ViewType; public abstract class BaseRender { private ViewType viewType = ViewType.VIEW; public BaseRender(final ViewType viewType) { this.viewType = viewType; } public ViewType getViewType() { return viewType; } /** * 获取实体元模型 * * @param entityName * @return */ public EntityMetaData getEntityMataData(final String entityName) { return ServiceUtil.getEntityMetaDataService().getEntityMetaData(entityName); } public String html() { switch (getViewType()) { case PRINT: return htmlForPrint(); default: return htmlForView(); } } public String htmlForView() { return ""; } public String htmlForPrint() { return htmlForView(); } }
914
0.737778
0.737778
44
19.454546
21.12458
78
false
false
0
0
0
0
0
0
1.25
false
false
7
7bc3d882c12f854dc6dc8b17940bd3d06fa06040
6,433,861,025,979
718434c43e641aaa39c1cfdc2f9e2f4382fe05ce
/src/main/java/com/spring/boot/project/demo/dto/review/ParsedReviewDto.java
abf32ab563b143666b0df309af051436ddf4c092
[]
no_license
MaksymVakuliuk/spring-boot-project
https://github.com/MaksymVakuliuk/spring-boot-project
280043b9360c1c126728024adcd1ac637f8f6877
1f846730fc7ae089e1cbd5208e35f16b714df172
refs/heads/master
2023-01-31T08:35:24.365000
2020-12-16T17:10:25
2020-12-16T17:10:25
277,787,987
0
0
null
false
2020-12-16T17:10:26
2020-07-07T10:36:31
2020-12-16T09:39:13
2020-12-16T17:10:26
229
0
0
0
Java
false
false
package com.spring.boot.project.demo.dto.review; import com.spring.boot.project.demo.dto.user.UserDto; import java.time.LocalDateTime; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ParsedReviewDto { private UserDto userDto; private String productId; private int helpfulnessNumerator; private int helpfulnessDenominator; private int score; private LocalDateTime time; private String summary; private String text; }
UTF-8
Java
493
java
ParsedReviewDto.java
Java
[]
null
[]
package com.spring.boot.project.demo.dto.review; import com.spring.boot.project.demo.dto.user.UserDto; import java.time.LocalDateTime; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ParsedReviewDto { private UserDto userDto; private String productId; private int helpfulnessNumerator; private int helpfulnessDenominator; private int score; private LocalDateTime time; private String summary; private String text; }
493
0.778905
0.778905
19
24.947369
14.777201
53
false
false
0
0
0
0
0
0
0.684211
false
false
7
0a336a058c80df69e00b620e9cf497e86ba75475
2,439,541,438,333
db655bd3c0d8e8a8ab67745b132c299e1f0fe870
/app/src/main/java/com/example/administrator/daggermvp/utils/ActivityManager.java
0ac88532968041f3987704b0cd3edff28a4762f9
[]
no_license
yuwenqiao/DaggerMvp
https://github.com/yuwenqiao/DaggerMvp
e544ad8da8dddb5e735ee90e0e4731739d6bb3d8
cf67ac4153e0309164bb9975badd051ff1579261
refs/heads/master
2020-04-07T12:00:43.243000
2019-04-19T09:06:33
2019-04-19T09:06:33
158,350,888
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.daggermvp.utils; import android.app.Activity; import android.util.Log; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Timer; import javax.inject.Inject; import javax.inject.Singleton; /** * activity 管理器 */ @Singleton public class ActivityManager { private List<Activity> mActivityList; @Inject public ActivityManager (){ } /** * 返回所有的存活的activity集合 */ public List<Activity> getActivityList(){ if(mActivityList==null){ mActivityList=new LinkedList<>(); } return mActivityList; } /** * 添加activity到集合 */ public void addActivity (Activity activity){ Log.i("dagger","manager---"+activity.getClass().getName()); List<Activity> activities=getActivityList(); if(!activities.contains(activity)){ activities.add(activity); } } /** * 移除指定activity * */ public void removeActivity(Activity activity){ List<Activity> activities=getActivityList(); if (activities.contains(activity)) { activities.remove(activity); } } /** * 返回目前处于栈顶的activity * */ public Activity getTopActivity (){ if(mActivityList==null||mActivityList.size()==0){ return null; } return mActivityList.get(mActivityList.size()-1); } /** * 关闭除了指定activity以外的所有activity */ public void finishAll(Activity activity) { Iterator<Activity> iterator = getActivityList().iterator(); while (iterator.hasNext()) { Activity next = iterator.next(); if (next.getClass().getName().equals(activity.getClass().getName())) continue; iterator.remove(); next.finish(); } } /** * 关闭除了指定activity以外的所有activity */ public void finishAll(Class<?> cls) { Iterator<Activity> iterator = getActivityList().iterator(); while (iterator.hasNext()) { Activity next = iterator.next(); if (next.getClass().equals(cls)) continue; iterator.remove(); next.finish(); } } /** * 结束所有的activity */ public void finishAll() { Iterator<Activity> iterator = getActivityList().iterator(); while (iterator.hasNext()) { Activity nextAcy = iterator.next(); iterator.remove(); nextAcy.finish(); } } /** * 退出应用程序 */ public void appExit() { try { finishAll(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
2,978
java
ActivityManager.java
Java
[]
null
[]
package com.example.administrator.daggermvp.utils; import android.app.Activity; import android.util.Log; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Timer; import javax.inject.Inject; import javax.inject.Singleton; /** * activity 管理器 */ @Singleton public class ActivityManager { private List<Activity> mActivityList; @Inject public ActivityManager (){ } /** * 返回所有的存活的activity集合 */ public List<Activity> getActivityList(){ if(mActivityList==null){ mActivityList=new LinkedList<>(); } return mActivityList; } /** * 添加activity到集合 */ public void addActivity (Activity activity){ Log.i("dagger","manager---"+activity.getClass().getName()); List<Activity> activities=getActivityList(); if(!activities.contains(activity)){ activities.add(activity); } } /** * 移除指定activity * */ public void removeActivity(Activity activity){ List<Activity> activities=getActivityList(); if (activities.contains(activity)) { activities.remove(activity); } } /** * 返回目前处于栈顶的activity * */ public Activity getTopActivity (){ if(mActivityList==null||mActivityList.size()==0){ return null; } return mActivityList.get(mActivityList.size()-1); } /** * 关闭除了指定activity以外的所有activity */ public void finishAll(Activity activity) { Iterator<Activity> iterator = getActivityList().iterator(); while (iterator.hasNext()) { Activity next = iterator.next(); if (next.getClass().getName().equals(activity.getClass().getName())) continue; iterator.remove(); next.finish(); } } /** * 关闭除了指定activity以外的所有activity */ public void finishAll(Class<?> cls) { Iterator<Activity> iterator = getActivityList().iterator(); while (iterator.hasNext()) { Activity next = iterator.next(); if (next.getClass().equals(cls)) continue; iterator.remove(); next.finish(); } } /** * 结束所有的activity */ public void finishAll() { Iterator<Activity> iterator = getActivityList().iterator(); while (iterator.hasNext()) { Activity nextAcy = iterator.next(); iterator.remove(); nextAcy.finish(); } } /** * 退出应用程序 */ public void appExit() { try { finishAll(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } }
2,978
0.562105
0.561053
125
21.799999
19.358513
80
false
false
0
0
0
0
0
0
0.32
false
false
7
0d0cc7388f3b1fd659f9609e01681abee1045161
13,632,226,245,469
90e24488f803572b58bc8a5e3875252719d0eaf1
/blacktooth04-javablackjack-3d20f3d92c23/blacktooth04-javablackjack-3d20f3d92c23/BlackJack/src/blackjack/Player.java
0f33bb6afd9ea3ef5c774a8198eaa79bff25d8fc
[]
no_license
Blacktooth04/blackjack
https://github.com/Blacktooth04/blackjack
2fc5ff3b8a026d9904a5c120238971d08c3b7119
b6c7f87107a725f4e6b74051e9a648563e4026e1
refs/heads/master
2020-12-20T20:57:37.386000
2020-01-25T18:04:03
2020-01-25T18:04:03
236,208,137
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Russell Lilljedahl * 28 July 2018 * Blackjack */ package blackjack; import java.util.ArrayList; import java.util.List; /** * * @author russell3233 */ public class Player extends PlayerInheriter implements NPCInterface { public Player() { hand = new ArrayList<>(); deck = new Deck(); } public String getStartingHand(List<Card> newDeck) { return (getNextCard(newDeck, hand) + ", " + getNextCard(newDeck, hand)); } //TODO // Implement an autoplay @Override public void AI(List<Card> newDeck) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
UTF-8
Java
762
java
Player.java
Java
[ { "context": "/**\r\n * Russell Lilljedahl\r\n * 28 July 2018\r\n * Blackjack\r\n*/\r\npackage black", "end": 26, "score": 0.9998915791511536, "start": 8, "tag": "NAME", "value": "Russell Lilljedahl" }, { "context": "st;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author russell3233\r\n */\r\npublic class Player extends PlayerInheriter", "end": 171, "score": 0.9996060729026794, "start": 160, "tag": "USERNAME", "value": "russell3233" } ]
null
[]
/** * <NAME> * 28 July 2018 * Blackjack */ package blackjack; import java.util.ArrayList; import java.util.List; /** * * @author russell3233 */ public class Player extends PlayerInheriter implements NPCInterface { public Player() { hand = new ArrayList<>(); deck = new Deck(); } public String getStartingHand(List<Card> newDeck) { return (getNextCard(newDeck, hand) + ", " + getNextCard(newDeck, hand)); } //TODO // Implement an autoplay @Override public void AI(List<Card> newDeck) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
750
0.606299
0.593176
33
21.09091
28.023111
135
false
false
0
0
0
0
0
0
0.363636
false
false
7
712eb9cf44b9680f055c254c90a6fff9ca32630d
3,307,124,848,717
844a77d393bfa18d067196b25f48bd58c574ae9f
/src/com/company/F10.java
9fd66a8c340a6798bac8c1e9d3fd339c135b23d1
[]
no_license
hu-5010/java-01
https://github.com/hu-5010/java-01
7566ccc44841976d6d2d9d5f829dd7b75fe52fa7
7580ab9aa21d5a3bd58c8f61a0218b635ce4b5dd
refs/heads/master
2022-12-30T01:23:25.042000
2020-10-20T01:40:43
2020-10-20T01:40:43
305,559,124
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.zip.DeflaterOutputStream; public class F10 { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 100; i++) { if(i%7 ==0 || i%10 == 7 || i/10 == 7){ continue; } System.out.println("不等于7的数字有:"+i); sum += i; } System.out.println(sum); } }
UTF-8
Java
418
java
F10.java
Java
[]
null
[]
package com.company; import java.util.zip.DeflaterOutputStream; public class F10 { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 100; i++) { if(i%7 ==0 || i%10 == 7 || i/10 == 7){ continue; } System.out.println("不等于7的数字有:"+i); sum += i; } System.out.println(sum); } }
418
0.462871
0.423267
18
21.444445
16.879383
50
false
false
0
0
0
0
0
0
0.722222
false
false
7
824fcf4668a62ad86f1876ec10197ca84f085586
23,639,500,037,763
dd8cf406948b8271b108506703edb0f6ed601f5d
/src/main/java/com/temp/schedule/ServiceUnit.java
d907eeb248b117fbdf0638de5fca09edf50969e4
[]
no_license
Temp-Control-System/Temp-Control-Backend
https://github.com/Temp-Control-System/Temp-Control-Backend
f68b839291c6d8f4c597ce0113eb2e5e6494fb1b
0faeca24deaf4fbc55bbfdacb8fcbfb6345d6841
refs/heads/master
2021-03-06T10:19:48.365000
2020-06-26T11:52:58
2020-06-26T11:52:58
246,194,594
0
2
null
false
2020-06-25T03:57:58
2020-03-10T02:59:14
2020-06-21T08:45:09
2020-06-25T03:57:57
98
0
1
0
Java
false
false
package com.temp.schedule; import com.temp.SystemConfigure; import com.temp.domain.RoomStatus; import com.temp.domain.ServiceRecord; import com.temp.enums.*; import com.temp.enums.Mode; import com.temp.enums.SUStatus; import com.temp.enums.Wind; import java.util.Date; public class ServiceUnit{ // ID,与房间ID对应 private static int curId = 0; // 唤醒边缘 final private static float margin = SystemConfigure.margin; // 目标温度 private float startTemperature; // 本次服务累计消费 private int curServiceCost; // 本次服务持续时间 private int lastTime; // 本次服务开始时刻 private Date serviceStartTime; // 等待时间(在等待态才有意义) private long waitingTime; // 房间状态 private RoomStatus roomStatus; // 本次服务是否取得用户目标 private int achievedTargetNum; public ServiceUnit (){ roomStatus = new RoomStatus(); roomStatus.setRoomId(curId++); roomStatus.setTemperature(RoomConfigure.getInitRoomTemperature(roomStatus.getRoomId())); roomStatus.setTargetTemperature(SystemConfigure.defaultTargetTemperature); roomStatus.setStatus(SUStatus.OFF); roomStatus.setMode(Mode.REFRIGERATION); roomStatus.setWind(SystemConfigure.DefaultWind); } public int getCurServiceCost() { return curServiceCost; } public void setCurServiceCost(int curServiceCost) { this.curServiceCost = curServiceCost; } public RoomStatus getRoomStatus() { return roomStatus; } public long getWaitingTime() { return waitingTime; } public void setWaitingTime(long waitingTime) { this.waitingTime = waitingTime; } public int getLastTime() { return lastTime; } public void setLastTime(int lastTime) { this.lastTime = lastTime; } public void resetService(){ startTemperature = getTemperature(); serviceStartTime = new Date(); curServiceCost = 0; lastTime = 0; } public void setTargetTemperature(float targetTemperature) { roomStatus.setTargetTemperature(targetTemperature); } public float getTargetTemperature() { return roomStatus.getTargetTemperature(); } public int getTotalCost() { return roomStatus.getTotalCost(); } public void setTotalCost(int totalCost) { roomStatus.setTotalCost(totalCost); } public Mode getMode() { return roomStatus.getMode(); } public void setMode(Mode mode) { roomStatus.setMode(mode); } public float getTemperature() { return roomStatus.getTemperature(); } public void setTemperature(float temperature) { roomStatus.setTemperature(temperature); } public SUStatus getStatus() { return roomStatus.getStatus(); } public void setStatus(SUStatus status) { roomStatus.setStatus(status); } public Wind getWind() { return roomStatus.getWind(); } public void setWind(Wind wind) { roomStatus.setWind(wind); } public int getAchievedTargetNum() { return achievedTargetNum; } public void setAchievedTargetNum(int achievedTargetNum) { this.achievedTargetNum = achievedTargetNum; } public boolean isAchievedTarget(){ if(getMode()==Mode.HEATING){ return getTemperature() > getTargetTemperature(); }else{ return getTemperature() < getTargetTemperature(); } } public boolean isWake(){ if(getMode()==Mode.HEATING){ return getTemperature() < getTargetTemperature() - margin; }else{ return getTemperature() > getTargetTemperature() + margin; } } private ServiceRecord getServiceRecord(){ ServiceRecord sr = new ServiceRecord(roomStatus.getRoomId(), getWind(), serviceStartTime, curServiceCost, lastTime, getMode(), getTemperature(), startTemperature, getTargetTemperature(), getAchievedTargetNum()==1); return sr; } public ServiceRecord stopService(){ ServiceRecord sr = getServiceRecord(); setStatus(SUStatus.WAITING); curServiceCost = 0; lastTime = 0; return sr; } }
UTF-8
Java
4,476
java
ServiceUnit.java
Java
[]
null
[]
package com.temp.schedule; import com.temp.SystemConfigure; import com.temp.domain.RoomStatus; import com.temp.domain.ServiceRecord; import com.temp.enums.*; import com.temp.enums.Mode; import com.temp.enums.SUStatus; import com.temp.enums.Wind; import java.util.Date; public class ServiceUnit{ // ID,与房间ID对应 private static int curId = 0; // 唤醒边缘 final private static float margin = SystemConfigure.margin; // 目标温度 private float startTemperature; // 本次服务累计消费 private int curServiceCost; // 本次服务持续时间 private int lastTime; // 本次服务开始时刻 private Date serviceStartTime; // 等待时间(在等待态才有意义) private long waitingTime; // 房间状态 private RoomStatus roomStatus; // 本次服务是否取得用户目标 private int achievedTargetNum; public ServiceUnit (){ roomStatus = new RoomStatus(); roomStatus.setRoomId(curId++); roomStatus.setTemperature(RoomConfigure.getInitRoomTemperature(roomStatus.getRoomId())); roomStatus.setTargetTemperature(SystemConfigure.defaultTargetTemperature); roomStatus.setStatus(SUStatus.OFF); roomStatus.setMode(Mode.REFRIGERATION); roomStatus.setWind(SystemConfigure.DefaultWind); } public int getCurServiceCost() { return curServiceCost; } public void setCurServiceCost(int curServiceCost) { this.curServiceCost = curServiceCost; } public RoomStatus getRoomStatus() { return roomStatus; } public long getWaitingTime() { return waitingTime; } public void setWaitingTime(long waitingTime) { this.waitingTime = waitingTime; } public int getLastTime() { return lastTime; } public void setLastTime(int lastTime) { this.lastTime = lastTime; } public void resetService(){ startTemperature = getTemperature(); serviceStartTime = new Date(); curServiceCost = 0; lastTime = 0; } public void setTargetTemperature(float targetTemperature) { roomStatus.setTargetTemperature(targetTemperature); } public float getTargetTemperature() { return roomStatus.getTargetTemperature(); } public int getTotalCost() { return roomStatus.getTotalCost(); } public void setTotalCost(int totalCost) { roomStatus.setTotalCost(totalCost); } public Mode getMode() { return roomStatus.getMode(); } public void setMode(Mode mode) { roomStatus.setMode(mode); } public float getTemperature() { return roomStatus.getTemperature(); } public void setTemperature(float temperature) { roomStatus.setTemperature(temperature); } public SUStatus getStatus() { return roomStatus.getStatus(); } public void setStatus(SUStatus status) { roomStatus.setStatus(status); } public Wind getWind() { return roomStatus.getWind(); } public void setWind(Wind wind) { roomStatus.setWind(wind); } public int getAchievedTargetNum() { return achievedTargetNum; } public void setAchievedTargetNum(int achievedTargetNum) { this.achievedTargetNum = achievedTargetNum; } public boolean isAchievedTarget(){ if(getMode()==Mode.HEATING){ return getTemperature() > getTargetTemperature(); }else{ return getTemperature() < getTargetTemperature(); } } public boolean isWake(){ if(getMode()==Mode.HEATING){ return getTemperature() < getTargetTemperature() - margin; }else{ return getTemperature() > getTargetTemperature() + margin; } } private ServiceRecord getServiceRecord(){ ServiceRecord sr = new ServiceRecord(roomStatus.getRoomId(), getWind(), serviceStartTime, curServiceCost, lastTime, getMode(), getTemperature(), startTemperature, getTargetTemperature(), getAchievedTargetNum()==1); return sr; } public ServiceRecord stopService(){ ServiceRecord sr = getServiceRecord(); setStatus(SUStatus.WAITING); curServiceCost = 0; lastTime = 0; return sr; } }
4,476
0.635421
0.63404
169
24.692308
19.963873
96
false
false
0
0
0
0
0
0
0.420118
false
false
7
a9efda0227160ebbf01431c0e515e6d981ada18c
14,843,406,992,459
176390c6a6c21f717ca9b4811af3683b1ef9b03a
/library/src/main/java/com/echsylon/kraken/request/DepositStatusesRequestBuilder.java
47c50916a9d7ad2e2076836ef1a5114c17c32c9a
[ "Apache-2.0" ]
permissive
echsylon/kraken
https://github.com/echsylon/kraken
e68d5c6ad0944a457d7874b4a5cb11ace7c1a12d
36545294d18e1327d2fca5f19e47b30fe59d4500
refs/heads/master
2021-01-16T19:25:45.424000
2018-02-04T16:17:30
2018-02-04T16:17:30
100,164,476
3
1
Apache-2.0
false
2018-01-25T12:20:07
2017-08-13T08:43:48
2017-12-17T20:06:07
2018-01-25T12:20:07
203
2
1
1
Java
false
null
package com.echsylon.kraken.request; import com.echsylon.kraken.dto.DepositStatus; import com.echsylon.kraken.internal.CallCounter; /** * This class can build a request that retrieves information about recent * deposit statuses for an asset. See API documentation on supported asset * formats. * <p> * For further technical details see Kraken API documentation at: * https://www.kraken.com/help/api */ @SuppressWarnings("WeakerAccess") public class DepositStatusesRequestBuilder extends RequestBuilder<DepositStatus[], DepositStatusesRequestBuilder> { /** * Creates a new request builder. * * @param callCounter The request call counter. May be null. * @param baseUrl The base url of the request. * @param key The user API key. * @param secret The corresponding secret. */ public DepositStatusesRequestBuilder(final CallCounter callCounter, final String baseUrl, final String key, final byte[] secret) { super(1, callCounter, key, secret, baseUrl, "POST", "/0/private/DepositStatus", DepositStatus[].class); } /** * Sets the one time password to use when performing the request. * * @param oneTimePassword The password. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useOneTimePassword(final String oneTimePassword) { data.put("otp", oneTimePassword); return this; } /** * Sets the asset class request property. * * @param assetClass The type of the asset to fetch info on. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useAssetClass(final String assetClass) { data.put("aclass", assetClass); return this; } /** * Sets the assets request property. * * @param asset The asset to get info on. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useAsset(final String asset) { data.put("asset", asset); return this; } /** * Sets the method request property. * * @param method The deposit method name. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useMethod(final String method) { data.put("method", method); return this; } }
UTF-8
Java
2,631
java
DepositStatusesRequestBuilder.java
Java
[]
null
[]
package com.echsylon.kraken.request; import com.echsylon.kraken.dto.DepositStatus; import com.echsylon.kraken.internal.CallCounter; /** * This class can build a request that retrieves information about recent * deposit statuses for an asset. See API documentation on supported asset * formats. * <p> * For further technical details see Kraken API documentation at: * https://www.kraken.com/help/api */ @SuppressWarnings("WeakerAccess") public class DepositStatusesRequestBuilder extends RequestBuilder<DepositStatus[], DepositStatusesRequestBuilder> { /** * Creates a new request builder. * * @param callCounter The request call counter. May be null. * @param baseUrl The base url of the request. * @param key The user API key. * @param secret The corresponding secret. */ public DepositStatusesRequestBuilder(final CallCounter callCounter, final String baseUrl, final String key, final byte[] secret) { super(1, callCounter, key, secret, baseUrl, "POST", "/0/private/DepositStatus", DepositStatus[].class); } /** * Sets the one time password to use when performing the request. * * @param oneTimePassword The password. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useOneTimePassword(final String oneTimePassword) { data.put("otp", oneTimePassword); return this; } /** * Sets the asset class request property. * * @param assetClass The type of the asset to fetch info on. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useAssetClass(final String assetClass) { data.put("aclass", assetClass); return this; } /** * Sets the assets request property. * * @param asset The asset to get info on. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useAsset(final String asset) { data.put("asset", asset); return this; } /** * Sets the method request property. * * @param method The deposit method name. * @return This request builder instance allowing method call chaining. */ public DepositStatusesRequestBuilder useMethod(final String method) { data.put("method", method); return this; } }
2,631
0.642721
0.641961
80
31.887501
28.794962
115
false
false
0
0
0
0
0
0
0.3375
false
false
7
465b6e206c7d75bd4614960e47c73ae52be61924
16,621,523,451,198
10ca167d2bb46a7033b8931624b10003ea370a34
/src/main/java/com/alexbzmn/MoveZeroes.java
f9cfe69d6872f5a7264f3e002abe8767d40581c4
[]
no_license
alexbzmn/Contest
https://github.com/alexbzmn/Contest
8c0fe9e6b2454aa336945824649a8245afa5544d
9bcbc32f83617c1ac61c4b4f1b679974069caf69
refs/heads/master
2022-02-05T23:10:11.503000
2022-01-30T22:30:53
2022-01-30T22:30:53
96,047,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alexbzmn; public class MoveZeroes { public void moveZeroes(int[] nums) { if (nums.length < 2) { return; } int i = 0; int z = 0; int n = 0; while (i < nums.length) { n = Math.max(n, i); while (nums[z] != 0 && z < nums.length - 1) { z++; } while (nums[n] == 0 && n < nums.length - 1) { n++; } if (nums[n] != 0 && nums[z] == 0 && n > z) { swap(z, n, nums); } i++; } } private void swap(int a, int b, int[] nums) { int buf = nums[a]; nums[a] = nums[b]; nums[b] = buf; } }
UTF-8
Java
556
java
MoveZeroes.java
Java
[]
null
[]
package com.alexbzmn; public class MoveZeroes { public void moveZeroes(int[] nums) { if (nums.length < 2) { return; } int i = 0; int z = 0; int n = 0; while (i < nums.length) { n = Math.max(n, i); while (nums[z] != 0 && z < nums.length - 1) { z++; } while (nums[n] == 0 && n < nums.length - 1) { n++; } if (nums[n] != 0 && nums[z] == 0 && n > z) { swap(z, n, nums); } i++; } } private void swap(int a, int b, int[] nums) { int buf = nums[a]; nums[a] = nums[b]; nums[b] = buf; } }
556
0.467626
0.44964
42
12.238095
14.758064
48
false
false
0
0
0
0
0
0
1.928571
false
false
7
abca4853d67577a32eacf9cb47a11ca881eba949
17,231,408,809,044
f993a5089047da4efce0773879eb13c9e2be6834
/EventProcessor/src/main/java/decorps/eventprocessor/vendors/dsi/programparameters/Oscillator1Shape.java
b84cfd743c05b237793aebb81b5521cf25399de6
[]
no_license
ldecorps/EventProcessor
https://github.com/ldecorps/EventProcessor
3ab8e8b965c3a38015a47539bb20f79483d4df3c
083a23d85eb25c9601f34b77c0b2bed282bad312
refs/heads/master
2021-03-12T20:02:48.244000
2014-03-07T22:14:40
2014-03-07T22:14:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package decorps.eventprocessor.vendors.dsi.programparameters; public class Oscillator1Shape extends ProgramParameter implements FourTo103Range, Centered { public Oscillator1Shape(int number, byte b) { super(number, b); } @Override public byte getLayerANRPNNumber() { return 2; } }
UTF-8
Java
296
java
Oscillator1Shape.java
Java
[]
null
[]
package decorps.eventprocessor.vendors.dsi.programparameters; public class Oscillator1Shape extends ProgramParameter implements FourTo103Range, Centered { public Oscillator1Shape(int number, byte b) { super(number, b); } @Override public byte getLayerANRPNNumber() { return 2; } }
296
0.773649
0.753378
15
18.733334
22.31432
65
true
false
0
0
0
0
0
0
1.133333
false
false
7
6f06a8f9afc278c2283cc444facfe37cf14575e7
21,406,117,019,406
8123cb08de438cf5a5434375a6aabf04aa583490
/MaxSubarraySum.java
93e720d09ec9f1a7a9c2b934e9976326061945bf
[]
no_license
JohnCanessa/MaxSubarraySum
https://github.com/JohnCanessa/MaxSubarraySum
a91b7ef9a3f26c48ef5235753af08586a51b9921
f49262ba82bb677fc8c7b7e37d8a5645bd617dce
refs/heads/main
2023-01-21T05:12:35.995000
2020-12-01T00:24:43
2020-12-01T00:24:43
317,372,449
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /** * */ public class MaxSubarraySum { /** * Brute force approach. * O(n^3) */ static int bruteForce(int[] nums) { // **** sanity check(s) **** if (nums == null) return 0; if (nums.length == 1) return nums[0]; // **** initialization **** int maxSum = 0; // **** from start ... O(n) ***** for (int s = 0; s < nums.length; s++) { // **** ... to end ... O(n) **** for (int e = s; e < nums.length; e++) { // **** compute sum O(n) **** int sum = 0; for (int i = s; i <= e; i++) { sum += nums[i]; } // **** update max sum **** maxSum = Math.max(maxSum, sum); } } // **** return max sum **** return maxSum; } /** * Optimized approach. * O(n^2) */ static int optimized(int[] nums) { // **** sanity check(s) **** if (nums == null) return 0; if (nums.length == 1) return nums[0]; // **** initialization **** int maxSum = 0; // **** from start ... O(n) ***** for (int s = 0; s < nums.length; s++) { // **** ... to end ... O(n) **** int sum = 0; for (int e = s; e < nums.length; e++) { // **** update sum **** sum += nums[e]; // **** update max sum **** maxSum = Math.max(maxSum, sum); } } // **** return max sum **** return maxSum; } /** * Using Kadane's algorithm. * O(n) */ static int kadanes(int[] nums) { // **** sanity check(s) **** if (nums == null) return 0; if (nums.length == 1) return nums[0]; // **** initialization **** int bestSum = Integer.MIN_VALUE; int currSum = nums[0]; // **** traverse nums O(n) **** for (int i = 1; i < nums.length; i++) { // **** increment or restart sum **** currSum = Math.max(currSum + nums[i], nums[i]); // **** update best sum if needed (remember best sum) **** bestSum = Math.max(bestSum, currSum); } // **** return best sum **** return bestSum; } /** * Test scaffolding. * * @throws IOException */ public static void main(String[] args) throws IOException { // **** open stream **** BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // **** read array **** String[] numStrs = br.readLine().trim().split(","); // **** close stream **** br.close(); // **** populate nums array **** int[] nums = new int[numStrs.length]; for (int i = 0; i < numStrs.length; i++) { nums[i] = Integer.parseInt(numStrs[i]); } // ???? display array ???? System.out.println("main <<< nums: " + Arrays.toString(nums)); // **** find and display the max sum of a subarray **** System.out.println("main <<< bruteForce: " + bruteForce(nums)); // **** find and display the max sum of a subarray **** System.out.println("main <<< optimized: " + optimized(nums)); // **** find and display the max sum of a subarray **** System.out.println("main <<< kadanes: " + kadanes(nums)); } }
UTF-8
Java
3,831
java
MaxSubarraySum.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /** * */ public class MaxSubarraySum { /** * Brute force approach. * O(n^3) */ static int bruteForce(int[] nums) { // **** sanity check(s) **** if (nums == null) return 0; if (nums.length == 1) return nums[0]; // **** initialization **** int maxSum = 0; // **** from start ... O(n) ***** for (int s = 0; s < nums.length; s++) { // **** ... to end ... O(n) **** for (int e = s; e < nums.length; e++) { // **** compute sum O(n) **** int sum = 0; for (int i = s; i <= e; i++) { sum += nums[i]; } // **** update max sum **** maxSum = Math.max(maxSum, sum); } } // **** return max sum **** return maxSum; } /** * Optimized approach. * O(n^2) */ static int optimized(int[] nums) { // **** sanity check(s) **** if (nums == null) return 0; if (nums.length == 1) return nums[0]; // **** initialization **** int maxSum = 0; // **** from start ... O(n) ***** for (int s = 0; s < nums.length; s++) { // **** ... to end ... O(n) **** int sum = 0; for (int e = s; e < nums.length; e++) { // **** update sum **** sum += nums[e]; // **** update max sum **** maxSum = Math.max(maxSum, sum); } } // **** return max sum **** return maxSum; } /** * Using Kadane's algorithm. * O(n) */ static int kadanes(int[] nums) { // **** sanity check(s) **** if (nums == null) return 0; if (nums.length == 1) return nums[0]; // **** initialization **** int bestSum = Integer.MIN_VALUE; int currSum = nums[0]; // **** traverse nums O(n) **** for (int i = 1; i < nums.length; i++) { // **** increment or restart sum **** currSum = Math.max(currSum + nums[i], nums[i]); // **** update best sum if needed (remember best sum) **** bestSum = Math.max(bestSum, currSum); } // **** return best sum **** return bestSum; } /** * Test scaffolding. * * @throws IOException */ public static void main(String[] args) throws IOException { // **** open stream **** BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // **** read array **** String[] numStrs = br.readLine().trim().split(","); // **** close stream **** br.close(); // **** populate nums array **** int[] nums = new int[numStrs.length]; for (int i = 0; i < numStrs.length; i++) { nums[i] = Integer.parseInt(numStrs[i]); } // ???? display array ???? System.out.println("main <<< nums: " + Arrays.toString(nums)); // **** find and display the max sum of a subarray **** System.out.println("main <<< bruteForce: " + bruteForce(nums)); // **** find and display the max sum of a subarray **** System.out.println("main <<< optimized: " + optimized(nums)); // **** find and display the max sum of a subarray **** System.out.println("main <<< kadanes: " + kadanes(nums)); } }
3,831
0.41112
0.405899
153
23.052288
20.899633
81
false
false
0
0
0
0
0
0
0.346405
false
false
7
b129ab62f19bd4acc85e88dff701b8b51c52f7d7
10,453,950,415,856
fb5840fa42a9e1125f1f4bd858b7495c36e773df
/src/main/java/ru/lovkov/service/TaskService.java
93c0aec757487720c421a9f725760595e85961bd
[]
no_license
kubreg/todolist
https://github.com/kubreg/todolist
742aadb6fdda4c385ff98612f72315d6f320a757
d079d5a9e15c401c37d31ab40be1b1aaac7d8ed9
refs/heads/master
2021-01-10T07:57:28.678000
2016-02-22T18:03:12
2016-02-22T18:03:12
52,290,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.lovkov.service; import ru.lovkov.entity.Task; import java.util.List; /** * Created by kubreg on 20.02.2016. */ public interface TaskService { int createTask(Task task); Task updateTask(Task task); void deleteTask(int id); List<Task> getAllTasks(); Task getTask(int id); void completeTask(int id); void incompleteTask(int id); }
UTF-8
Java
372
java
TaskService.java
Java
[ { "context": "y.Task;\n\nimport java.util.List;\n\n/**\n * Created by kubreg on 20.02.2016.\n */\npublic interface TaskService {", "end": 107, "score": 0.9992845058441162, "start": 101, "tag": "USERNAME", "value": "kubreg" } ]
null
[]
package ru.lovkov.service; import ru.lovkov.entity.Task; import java.util.List; /** * Created by kubreg on 20.02.2016. */ public interface TaskService { int createTask(Task task); Task updateTask(Task task); void deleteTask(int id); List<Task> getAllTasks(); Task getTask(int id); void completeTask(int id); void incompleteTask(int id); }
372
0.688172
0.666667
18
19.666666
13.370781
35
false
false
0
0
0
0
0
0
0.555556
false
false
7
b088862452f5fc46d3ceffb606ba03e8a1b0323f
7,318,624,299,208
e1e8777fa0cc444a546237520b926c07aff1ded6
/src/main/java/com/see/controllers/ContactController.java
76251d24cb4d415975ddfed0074a8887d97fc7c3
[]
no_license
fekfek/environment
https://github.com/fekfek/environment
c6baad0937f32a050f28c0d5661a57889fea6a39
00895ec86870006ecab9fa9f019c9da168189de8
refs/heads/master
2022-12-22T10:28:53.589000
2020-10-07T15:47:59
2020-10-07T15:47:59
184,640,290
0
0
null
false
2022-12-16T08:51:50
2019-05-02T19:34:03
2020-10-07T15:54:32
2022-12-16T08:51:47
55,766
0
0
6
Java
false
false
package com.see.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.see.model.Contact; import com.see.service.ContactService; @Controller public class ContactController { @Autowired private ContactService contservice; @RequestMapping(value={"/contact"} , method=RequestMethod.GET) public String contact() { return "contact"; } @PostMapping("/registerContact") public String register(@Validated Contact contact, BindingResult result) { if(result.hasErrors()) { return "redirect:/contact"; } else { contservice.addContact(contact); return "contactRegistered"; } } @GetMapping("/showcontacts") public String showContacts(Model model) { List<Contact> contacts = contservice.showContacts(); model.addAttribute("contacts" , contacts); return "showContacts"; } }
UTF-8
Java
1,307
java
ContactController.java
Java
[]
null
[]
package com.see.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.see.model.Contact; import com.see.service.ContactService; @Controller public class ContactController { @Autowired private ContactService contservice; @RequestMapping(value={"/contact"} , method=RequestMethod.GET) public String contact() { return "contact"; } @PostMapping("/registerContact") public String register(@Validated Contact contact, BindingResult result) { if(result.hasErrors()) { return "redirect:/contact"; } else { contservice.addContact(contact); return "contactRegistered"; } } @GetMapping("/showcontacts") public String showContacts(Model model) { List<Contact> contacts = contservice.showContacts(); model.addAttribute("contacts" , contacts); return "showContacts"; } }
1,307
0.788064
0.788064
47
26.80851
22.609203
75
false
false
0
0
0
0
0
0
1.361702
false
false
7
2ba782819a35f416820e2e3a3dfd870c2b68f972
20,005,957,684,534
7d6737c3799b0b85c72907f95886b6b132812a17
/src/cn/shgx/array/TwoSum.java
a0bd6e282360cfc3431a77baeb34c431d3500b84
[]
no_license
guangxush/JavaAlgorithms
https://github.com/guangxush/JavaAlgorithms
60e05522a5d94a5d4c91884035a91c3d26b0247e
c7230a528e028fe3b0584a7de132471d2201661c
refs/heads/master
2022-03-18T18:35:39.678000
2019-10-11T11:44:36
2019-10-11T11:44:36
110,700,460
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.shgx.array; //数组中是否存在两个数的和为sum import cn.shgx.hashtable.HashTable; import cn.shgx.sort.QuickSort; public class TwoSum { /** * 暴力解法 O(n^2) * @param array * @param sum */ public static void find1(int[] array, int sum) { for(int i=0;i<array.length;i++) { for(int j=0;j<array.length;j++) { //当两个数不是同一个值,而且和=sum时输出下标 if(i!=j&&array[i]==sum-array[j]) { System.out.println(String.format("i:%d,j:%d", i,j)); return; } } } } /** * 散列表实现O(n) * @param array * @param sum */ public static void find2(int[] array,int sum) { HashTable hashTable = new HashTable(); //首先填充散列表 for(int i=0;i<array.length;i++) { hashTable.put(array[i], i); } //依次判断对应的值是否存在于散列表中 for(int i=0;i<array.length;i++) { int index = hashTable.get(sum-array[i]); if(index!=-1&&index!=i) { System.out.println(String.format("i:%d,j:%d", index,i)); return; } } } /** * 排序双数组法 * @param array * @param sum */ public static void find3(int[] array,int sum) { //先快速排序 QuickSort sort = new QuickSort(array); sort.sort(); //初始化相对数组 int[] array2 = new int[array.length]; for(int i=0;i<array.length;i++) { array2[i] = sum-array[i]; } int i = 0; int j = array2.length-1; //i不能>j否则要重新判断 while(i<j) { if(array[i]==array2[j]) { System.out.println(String.format("i:%d,j:%d", i,j)); return; }else if(array[i]<array2[j]) { while(i<j&&array[i]<array2[j]) { i++; } }else { while(i<j&&array[i]>array2[j]) { j--; } } } } public static void find4(int[] array,int sum) { //先快速排序 QuickSort sort = new QuickSort(array); sort.sort(); int i = 0; int j = array.length-1; while(i<j) { int sumTemp = array[i]+array[j]; if(sumTemp==sum) { System.out.println(String.format("i:%d,j:%d", i,j)); return; }else if(sumTemp>sum) { j--; }else if(sumTemp<sum) { i++; } } } }
UTF-8
Java
2,117
java
TwoSum.java
Java
[]
null
[]
package cn.shgx.array; //数组中是否存在两个数的和为sum import cn.shgx.hashtable.HashTable; import cn.shgx.sort.QuickSort; public class TwoSum { /** * 暴力解法 O(n^2) * @param array * @param sum */ public static void find1(int[] array, int sum) { for(int i=0;i<array.length;i++) { for(int j=0;j<array.length;j++) { //当两个数不是同一个值,而且和=sum时输出下标 if(i!=j&&array[i]==sum-array[j]) { System.out.println(String.format("i:%d,j:%d", i,j)); return; } } } } /** * 散列表实现O(n) * @param array * @param sum */ public static void find2(int[] array,int sum) { HashTable hashTable = new HashTable(); //首先填充散列表 for(int i=0;i<array.length;i++) { hashTable.put(array[i], i); } //依次判断对应的值是否存在于散列表中 for(int i=0;i<array.length;i++) { int index = hashTable.get(sum-array[i]); if(index!=-1&&index!=i) { System.out.println(String.format("i:%d,j:%d", index,i)); return; } } } /** * 排序双数组法 * @param array * @param sum */ public static void find3(int[] array,int sum) { //先快速排序 QuickSort sort = new QuickSort(array); sort.sort(); //初始化相对数组 int[] array2 = new int[array.length]; for(int i=0;i<array.length;i++) { array2[i] = sum-array[i]; } int i = 0; int j = array2.length-1; //i不能>j否则要重新判断 while(i<j) { if(array[i]==array2[j]) { System.out.println(String.format("i:%d,j:%d", i,j)); return; }else if(array[i]<array2[j]) { while(i<j&&array[i]<array2[j]) { i++; } }else { while(i<j&&array[i]>array2[j]) { j--; } } } } public static void find4(int[] array,int sum) { //先快速排序 QuickSort sort = new QuickSort(array); sort.sort(); int i = 0; int j = array.length-1; while(i<j) { int sumTemp = array[i]+array[j]; if(sumTemp==sum) { System.out.println(String.format("i:%d,j:%d", i,j)); return; }else if(sumTemp>sum) { j--; }else if(sumTemp<sum) { i++; } } } }
2,117
0.569943
0.558502
94
19.457447
15.763994
60
false
false
0
0
0
0
0
0
2.819149
false
false
7
d3cf89d5bf819a5642d673c59bd3cb6bcc48fd18
20,005,957,687,671
2216c201333d7547edb5af1a230104749e03cb98
/src/ntu/csie/oop13spring/POONamePool.java
707b04a7c2a453c5242e5ea39cff0380cbc08b37
[]
no_license
b99902017/oop_hw4
https://github.com/b99902017/oop_hw4
a00490726c82dfca1042b1f686a86c0b1c48985c
b5398b8c1cb8abc80de0310368e3a59d76564be6
refs/heads/master
2021-01-20T12:41:22.213000
2013-05-17T15:50:36
2013-05-17T15:50:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ntu.csie.oop13spring; import java.io.*; import java.util.*; public final class POONamePool { private static String[] names = makeNameList(); private static int[] check = makeCheck(); protected static int[] makeCheck() { int[] tmp = new int[names.length]; for (int i = 0; i < tmp.length; i++) tmp[i] = 0; return tmp; } protected static String[] makeNameList() { ArrayList<String> tmp = new ArrayList<String>(0); File file = new File("name.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNext() == true) { String name = scanner.next(); tmp.add(name); } scanner.close(); } catch (FileNotFoundException e) { System.out.println(e); e.printStackTrace(); } String[] str = new String[0]; return tmp.toArray(str); } public static String getName() { int res; do { res = POORandom.getInt(names.length); } while (check[res] != 0); check[res] = 1; return names[res]; } }
UTF-8
Java
960
java
POONamePool.java
Java
[]
null
[]
package ntu.csie.oop13spring; import java.io.*; import java.util.*; public final class POONamePool { private static String[] names = makeNameList(); private static int[] check = makeCheck(); protected static int[] makeCheck() { int[] tmp = new int[names.length]; for (int i = 0; i < tmp.length; i++) tmp[i] = 0; return tmp; } protected static String[] makeNameList() { ArrayList<String> tmp = new ArrayList<String>(0); File file = new File("name.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNext() == true) { String name = scanner.next(); tmp.add(name); } scanner.close(); } catch (FileNotFoundException e) { System.out.println(e); e.printStackTrace(); } String[] str = new String[0]; return tmp.toArray(str); } public static String getName() { int res; do { res = POORandom.getInt(names.length); } while (check[res] != 0); check[res] = 1; return names[res]; } }
960
0.638542
0.630208
41
22.414635
15.04623
51
false
false
0
0
0
0
0
0
2.365854
false
false
7
bbbac2496a76cc097b24a4d78eae6513b5aceaa6
39,702,677,703,324
5296a560949e9f3c898324aa51a2b0aaa8272570
/marananManagement/src/main/java/com/marananmanagement/NewsLetterList.java
5ab916e902b4012cca1fb6117e0513bd26a7f02b
[]
no_license
Dummyurl/maranan_management
https://github.com/Dummyurl/maranan_management
f6a9eb33709cd2a821bbd15ef655e844cd4f7661
bb225541e0bda72e3bd6ef0d6fa58fdd8b0b67a2
refs/heads/master
2020-04-10T21:22:06.462000
2017-01-20T07:46:47
2017-01-20T07:47:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.marananmanagement; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.ProgressBar; import com.marananmanagement.adapter.NewsLetterListAdapter; import com.marananmanagement.swipetodismiss.BaseSwipeListViewListener; import com.marananmanagement.swipetodismiss.SwipeListView; import com.marananmanagement.util.Config; import com.marananmanagement.util.ConnectionDetector; import com.marananmanagement.util.GetterSetter; import com.marananmanagement.util.Utilities; public class NewsLetterList extends Activity implements OnClickListener{ private static NewsLetterList mContext; private SwipeListView lv_radio_lectures; private ImageButton img_pencil_icon; public static int REQUEST_CODE_NEWSLETTER_UPLOAD = 200; private NewsLetterListAdapter adapter; private ConnectionDetector cd; private Boolean isInternetPresent = false; private ProgressBar pDialog; private ArrayList<GetterSetter> listNewsLetter; private int count = 0; @SuppressWarnings("unused") private int pos; private String date = ""; // RadioPrograms Instance public static NewsLetterList getInstance() { return mContext; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale); // Handle UnCaughtException Exception Handler // Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler( // this)); setContentView(R.layout.radio_lecture_list); mContext = NewsLetterList.this; cd = new ConnectionDetector(getApplicationContext()); isInternetPresent = cd.isConnectingToInternet(); initializeView(); } // initialize View Here... private void initializeView() { pDialog = (ProgressBar) findViewById(R.id.progressBar); pDialog.setVisibility(View.GONE); lv_radio_lectures = (SwipeListView) findViewById(R.id.lv_radio_lectures); lv_radio_lectures.setSwipeMode(SwipeListView.SWIPE_MODE_RIGHT); lv_radio_lectures.setOffsetRight(convertDpToPixel(80f)); lv_radio_lectures.setAnimationTime(500); lv_radio_lectures.setSwipeOpenOnLongPress(false); img_pencil_icon = (ImageButton) findViewById(R.id.img_pencil_icon); img_pencil_icon.setOnClickListener(this); lv_radio_lectures.setSwipeListViewListener(new BaseSwipeListViewListener() { @Override public void onOpened(int position, boolean toRight) { pos = position; } @Override public void onClosed(int position, boolean fromRight) { pos = position; } @Override public void onListChanged() { } @Override public void onMove(int position, float x) { } @Override public void onStartOpen(int position, int action, boolean right) { pos = position; } @Override public void onStartClose(int position, boolean right) { pos = position; } @Override public void onClickFrontView(int position) { lv_radio_lectures.closeAnimate(position); Intent newsIntent = new Intent(NewsLetterList.this, NewsLetterUpload.class); newsIntent.putExtra("id", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getId()); newsIntent.putExtra("title", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getTitle()); newsIntent.putExtra("image", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getImage()); newsIntent.putExtra("pdf", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getRadio_programs()); newsIntent.putExtra("time", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getTime()); newsIntent.putExtra("date", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getDate()); startActivityForResult(newsIntent, REQUEST_CODE_NEWSLETTER_UPLOAD); } @Override public void onClickBackView(int position) { lv_radio_lectures.closeAnimate(position); } @Override public void onDismiss(int[] reverseSortedPositions) { } }); if (isInternetPresent) { date = getIntent().getStringExtra("date"); setdate(date); if (!date.equals("")) { new GetAllNewsLetter().execute(getDate()); }else{ new GetAllNewsLetter().execute(getDate()); } } else { Utilities.showAlertDialog(NewsLetterList.this, "Internet Connection Error", "Please connect to working Internet connection", false); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.img_pencil_icon: Intent newsIntent = new Intent(NewsLetterList.this, NewsLetterUpload.class); startActivityForResult(newsIntent, REQUEST_CODE_NEWSLETTER_UPLOAD); break; default: break; } } // OnActivity Result To Get Result From Radio ProgramUpload Activity and // Refresh Here With New values... @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == REQUEST_CODE_NEWSLETTER_UPLOAD) { if (isInternetPresent) { if (!getDate().equals("")) { new GetAllNewsLetter().execute(getDate()); }else{ new GetAllNewsLetter().execute(getDate()); } } else { Utilities.showAlertDialog(NewsLetterList.this, "Internet Connection Error", "Please connect to working Internet connection", false); } } } } // Get All Dedications for Administrator who control all the data over // server public class GetAllNewsLetter extends AsyncTask<String, Void, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog.setVisibility(View.VISIBLE); } @Override protected JSONObject doInBackground(String... params) { JSONObject jObj = null; String url = ""; HttpParams params2 = new BasicHttpParams(); params2.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient mHttpClient = new DefaultHttpClient(params2); if (!params[0].equals("")) { url = Config.ROOT_SERVER_CLIENT + Config.GET_NEWSLETTERS_BY_YEAR; }else{ url = Config.ROOT_SERVER_CLIENT + Config.GET_NEWSLETTERS; } listNewsLetter = new ArrayList<GetterSetter>(); HttpPost httppost = new HttpPost(url); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { multipartEntity.addPart("date", new StringBody(params[0])); httppost.setEntity(multipartEntity); HttpResponse response = mHttpClient.execute(httppost); HttpEntity r_entity = response.getEntity(); String strResponse = EntityUtils.toString(r_entity); try { JSONObject json = new JSONObject(strResponse); JSONArray jArry = json.getJSONArray("value"); for (int i = 0; i < jArry.length(); i++) { JSONObject jsonObj = jArry.getJSONObject(i); GetterSetter getset = new GetterSetter(); getset.setId(jsonObj.getString("id")); if (!jsonObj.getString("title").toString().equals("")) { getset.setTitle((jsonObj.getString("title"))); } else { getset.setTitle(""); } if (!jsonObj.getString("image").toString().equals("")) { getset.setImage(jsonObj.getString("image")); } else { getset.setImage(""); } if (!jsonObj.getString("pdf").toString().equals("")) { getset.setPdf(jsonObj.getString("pdf")); } else { getset.setPdf(""); } if (!jsonObj.getString("pdf_pages").toString().equals("")) { getset.setPdf_pages(jsonObj.getString("pdf_pages")); } else { getset.setPdf_pages(""); } if (!jsonObj.getString("image_thumb").toString().equals("")) { getset.setImage_thumb(jsonObj.getString("image_thumb")); } else { getset.setImage_thumb(""); } if (!jsonObj.getString("time").toString().equals("")) { getset.setTime(jsonObj.getString("time")); } else { getset.setTime(""); } if (!jsonObj.getString("date").toString().equals("")) { getset.setDate(jsonObj.getString("date")); } else { getset.setDate(""); } if (!jsonObj.getString("publish_status").toString().equals("")) { getset.setPublish_status(jsonObj.getString("publish_status")); } else { getset.setPublish_status(""); } if (!jsonObj.getString("publish_notification").toString().equals("")) { getset.setPublish_notification(jsonObj.getString("publish_notification")); } else { getset.setPublish_notification(""); } if (!jsonObj.getString("publish_status").toString().equals("")) { if (jsonObj.getString("publish_status").equals("true")) { count++; getset.setCount(count); getset.setImgCheckUncheckRes(R.drawable.tick_icon); }else{ getset.setImgCheckUncheckRes(R.drawable.tick_gray); } } if (!jsonObj.getString("publish_notification").toString().equals("")) { if (jsonObj.getString("publish_notification").equals("true")) { getset.setImgBroadCastRes(R.drawable.broadcast_sms); }else{ getset.setImgBroadCastRes(R.drawable.broadcast_sms_gray); } } getset.setImgCancelRes(R.drawable.cross_gray); listNewsLetter.add(getset); } } catch (JSONException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jObj; } @Override protected void onPostExecute(JSONObject result) { super.onPostExecute(result); pDialog.setVisibility(View.GONE); if(listNewsLetter != null) if (listNewsLetter.size() > 0) { count = 0; adapter = new NewsLetterListAdapter(NewsLetterList.this, listNewsLetter); lv_radio_lectures.setAdapter(adapter); adapter.notifyDataSetChanged(); } else { Utilities.showToast(NewsLetterList.this, "NewsLetters Not Found"); } } } // Declare Delete Program... class DeleteNewsLetter extends AsyncTask<String, Void, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected JSONObject doInBackground(String... params) { JSONObject jObj = null; HttpParams params2 = new BasicHttpParams(); params2.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient mHttpClient = new DefaultHttpClient(params2); String url = Config.ROOT_SERVER_CLIENT + Config.DELETE_NEWSLETTER; HttpPost httppost = new HttpPost(url); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { multipartEntity.addPart("id", new StringBody(params[0])); httppost.setEntity(multipartEntity); HttpResponse response = mHttpClient.execute(httppost); HttpEntity r_entity = response.getEntity(); String strResponse = EntityUtils.toString(r_entity); jObj = new JSONObject(strResponse); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return jObj; } @Override protected void onPostExecute(JSONObject result) { super.onPostExecute(result); } } public int convertDpToPixel(float dp) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float px = dp * (metrics.densityDpi / 160f); return (int) px; } // Call DeleteProgram Class here in the adapter... public void getClassDelete(int position) { new DeleteNewsLetter().execute(NewsLetterListAdapter.getInstance().getArrayList().get(position).getId()); } // Get Swipe List View public SwipeListView getSwipeList() { return lv_radio_lectures; } // Get Adapter To Refresh List View When Delete Item... public void getRefreshAdapter(){ adapter.notifyDataSetChanged(); } // onBackPress @Override public void onBackPressed() { Intent mintent = new Intent(); setResult(RESULT_OK, mintent); finish(); overridePendingTransition(R.anim.activity_open_scale, R.anim.activity_close_translate); super.onBackPressed(); } public String getDate(){ return date; } public void setdate(String date){ this.date= date; } }
UTF-8
Java
14,346
java
NewsLetterList.java
Java
[]
null
[]
package com.marananmanagement; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.ProgressBar; import com.marananmanagement.adapter.NewsLetterListAdapter; import com.marananmanagement.swipetodismiss.BaseSwipeListViewListener; import com.marananmanagement.swipetodismiss.SwipeListView; import com.marananmanagement.util.Config; import com.marananmanagement.util.ConnectionDetector; import com.marananmanagement.util.GetterSetter; import com.marananmanagement.util.Utilities; public class NewsLetterList extends Activity implements OnClickListener{ private static NewsLetterList mContext; private SwipeListView lv_radio_lectures; private ImageButton img_pencil_icon; public static int REQUEST_CODE_NEWSLETTER_UPLOAD = 200; private NewsLetterListAdapter adapter; private ConnectionDetector cd; private Boolean isInternetPresent = false; private ProgressBar pDialog; private ArrayList<GetterSetter> listNewsLetter; private int count = 0; @SuppressWarnings("unused") private int pos; private String date = ""; // RadioPrograms Instance public static NewsLetterList getInstance() { return mContext; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale); // Handle UnCaughtException Exception Handler // Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler( // this)); setContentView(R.layout.radio_lecture_list); mContext = NewsLetterList.this; cd = new ConnectionDetector(getApplicationContext()); isInternetPresent = cd.isConnectingToInternet(); initializeView(); } // initialize View Here... private void initializeView() { pDialog = (ProgressBar) findViewById(R.id.progressBar); pDialog.setVisibility(View.GONE); lv_radio_lectures = (SwipeListView) findViewById(R.id.lv_radio_lectures); lv_radio_lectures.setSwipeMode(SwipeListView.SWIPE_MODE_RIGHT); lv_radio_lectures.setOffsetRight(convertDpToPixel(80f)); lv_radio_lectures.setAnimationTime(500); lv_radio_lectures.setSwipeOpenOnLongPress(false); img_pencil_icon = (ImageButton) findViewById(R.id.img_pencil_icon); img_pencil_icon.setOnClickListener(this); lv_radio_lectures.setSwipeListViewListener(new BaseSwipeListViewListener() { @Override public void onOpened(int position, boolean toRight) { pos = position; } @Override public void onClosed(int position, boolean fromRight) { pos = position; } @Override public void onListChanged() { } @Override public void onMove(int position, float x) { } @Override public void onStartOpen(int position, int action, boolean right) { pos = position; } @Override public void onStartClose(int position, boolean right) { pos = position; } @Override public void onClickFrontView(int position) { lv_radio_lectures.closeAnimate(position); Intent newsIntent = new Intent(NewsLetterList.this, NewsLetterUpload.class); newsIntent.putExtra("id", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getId()); newsIntent.putExtra("title", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getTitle()); newsIntent.putExtra("image", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getImage()); newsIntent.putExtra("pdf", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getRadio_programs()); newsIntent.putExtra("time", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getTime()); newsIntent.putExtra("date", NewsLetterListAdapter.getInstance().getNewArrayListNewsLetter().get(position).getDate()); startActivityForResult(newsIntent, REQUEST_CODE_NEWSLETTER_UPLOAD); } @Override public void onClickBackView(int position) { lv_radio_lectures.closeAnimate(position); } @Override public void onDismiss(int[] reverseSortedPositions) { } }); if (isInternetPresent) { date = getIntent().getStringExtra("date"); setdate(date); if (!date.equals("")) { new GetAllNewsLetter().execute(getDate()); }else{ new GetAllNewsLetter().execute(getDate()); } } else { Utilities.showAlertDialog(NewsLetterList.this, "Internet Connection Error", "Please connect to working Internet connection", false); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.img_pencil_icon: Intent newsIntent = new Intent(NewsLetterList.this, NewsLetterUpload.class); startActivityForResult(newsIntent, REQUEST_CODE_NEWSLETTER_UPLOAD); break; default: break; } } // OnActivity Result To Get Result From Radio ProgramUpload Activity and // Refresh Here With New values... @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == REQUEST_CODE_NEWSLETTER_UPLOAD) { if (isInternetPresent) { if (!getDate().equals("")) { new GetAllNewsLetter().execute(getDate()); }else{ new GetAllNewsLetter().execute(getDate()); } } else { Utilities.showAlertDialog(NewsLetterList.this, "Internet Connection Error", "Please connect to working Internet connection", false); } } } } // Get All Dedications for Administrator who control all the data over // server public class GetAllNewsLetter extends AsyncTask<String, Void, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog.setVisibility(View.VISIBLE); } @Override protected JSONObject doInBackground(String... params) { JSONObject jObj = null; String url = ""; HttpParams params2 = new BasicHttpParams(); params2.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient mHttpClient = new DefaultHttpClient(params2); if (!params[0].equals("")) { url = Config.ROOT_SERVER_CLIENT + Config.GET_NEWSLETTERS_BY_YEAR; }else{ url = Config.ROOT_SERVER_CLIENT + Config.GET_NEWSLETTERS; } listNewsLetter = new ArrayList<GetterSetter>(); HttpPost httppost = new HttpPost(url); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { multipartEntity.addPart("date", new StringBody(params[0])); httppost.setEntity(multipartEntity); HttpResponse response = mHttpClient.execute(httppost); HttpEntity r_entity = response.getEntity(); String strResponse = EntityUtils.toString(r_entity); try { JSONObject json = new JSONObject(strResponse); JSONArray jArry = json.getJSONArray("value"); for (int i = 0; i < jArry.length(); i++) { JSONObject jsonObj = jArry.getJSONObject(i); GetterSetter getset = new GetterSetter(); getset.setId(jsonObj.getString("id")); if (!jsonObj.getString("title").toString().equals("")) { getset.setTitle((jsonObj.getString("title"))); } else { getset.setTitle(""); } if (!jsonObj.getString("image").toString().equals("")) { getset.setImage(jsonObj.getString("image")); } else { getset.setImage(""); } if (!jsonObj.getString("pdf").toString().equals("")) { getset.setPdf(jsonObj.getString("pdf")); } else { getset.setPdf(""); } if (!jsonObj.getString("pdf_pages").toString().equals("")) { getset.setPdf_pages(jsonObj.getString("pdf_pages")); } else { getset.setPdf_pages(""); } if (!jsonObj.getString("image_thumb").toString().equals("")) { getset.setImage_thumb(jsonObj.getString("image_thumb")); } else { getset.setImage_thumb(""); } if (!jsonObj.getString("time").toString().equals("")) { getset.setTime(jsonObj.getString("time")); } else { getset.setTime(""); } if (!jsonObj.getString("date").toString().equals("")) { getset.setDate(jsonObj.getString("date")); } else { getset.setDate(""); } if (!jsonObj.getString("publish_status").toString().equals("")) { getset.setPublish_status(jsonObj.getString("publish_status")); } else { getset.setPublish_status(""); } if (!jsonObj.getString("publish_notification").toString().equals("")) { getset.setPublish_notification(jsonObj.getString("publish_notification")); } else { getset.setPublish_notification(""); } if (!jsonObj.getString("publish_status").toString().equals("")) { if (jsonObj.getString("publish_status").equals("true")) { count++; getset.setCount(count); getset.setImgCheckUncheckRes(R.drawable.tick_icon); }else{ getset.setImgCheckUncheckRes(R.drawable.tick_gray); } } if (!jsonObj.getString("publish_notification").toString().equals("")) { if (jsonObj.getString("publish_notification").equals("true")) { getset.setImgBroadCastRes(R.drawable.broadcast_sms); }else{ getset.setImgBroadCastRes(R.drawable.broadcast_sms_gray); } } getset.setImgCancelRes(R.drawable.cross_gray); listNewsLetter.add(getset); } } catch (JSONException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jObj; } @Override protected void onPostExecute(JSONObject result) { super.onPostExecute(result); pDialog.setVisibility(View.GONE); if(listNewsLetter != null) if (listNewsLetter.size() > 0) { count = 0; adapter = new NewsLetterListAdapter(NewsLetterList.this, listNewsLetter); lv_radio_lectures.setAdapter(adapter); adapter.notifyDataSetChanged(); } else { Utilities.showToast(NewsLetterList.this, "NewsLetters Not Found"); } } } // Declare Delete Program... class DeleteNewsLetter extends AsyncTask<String, Void, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected JSONObject doInBackground(String... params) { JSONObject jObj = null; HttpParams params2 = new BasicHttpParams(); params2.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient mHttpClient = new DefaultHttpClient(params2); String url = Config.ROOT_SERVER_CLIENT + Config.DELETE_NEWSLETTER; HttpPost httppost = new HttpPost(url); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { multipartEntity.addPart("id", new StringBody(params[0])); httppost.setEntity(multipartEntity); HttpResponse response = mHttpClient.execute(httppost); HttpEntity r_entity = response.getEntity(); String strResponse = EntityUtils.toString(r_entity); jObj = new JSONObject(strResponse); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return jObj; } @Override protected void onPostExecute(JSONObject result) { super.onPostExecute(result); } } public int convertDpToPixel(float dp) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float px = dp * (metrics.densityDpi / 160f); return (int) px; } // Call DeleteProgram Class here in the adapter... public void getClassDelete(int position) { new DeleteNewsLetter().execute(NewsLetterListAdapter.getInstance().getArrayList().get(position).getId()); } // Get Swipe List View public SwipeListView getSwipeList() { return lv_radio_lectures; } // Get Adapter To Refresh List View When Delete Item... public void getRefreshAdapter(){ adapter.notifyDataSetChanged(); } // onBackPress @Override public void onBackPressed() { Intent mintent = new Intent(); setResult(RESULT_OK, mintent); finish(); overridePendingTransition(R.anim.activity_open_scale, R.anim.activity_close_translate); super.onBackPressed(); } public String getDate(){ return date; } public void setdate(String date){ this.date= date; } }
14,346
0.683396
0.681444
447
30.09396
26.103394
132
false
false
0
0
0
0
0
0
3.512304
false
false
7
e16c2cf77d465f8538f5a1e8b6d722bbbb97d386
39,101,382,282,608
c474b03758be154e43758220e47b3403eb7fc1fc
/apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/tinder/match/views/C12110l.java
5d6beaa44d93a94693b12994216972df6aea19ac
[]
no_license
EstebanDalelR/tinderAnalysis
https://github.com/EstebanDalelR/tinderAnalysis
f80fe1f43b3b9dba283b5db1781189a0dd592c24
941e2c634c40e5dbf5585c6876ef33f2a578b65c
refs/heads/master
2020-04-04T09:03:32.659000
2018-11-23T20:41:28
2018-11-23T20:41:28
155,805,042
0
0
null
false
2018-11-18T16:02:45
2018-11-02T02:44:34
2018-11-18T15:58:25
2018-11-18T16:02:44
353,670
0
0
0
null
false
null
package com.tinder.match.views; import com.tinder.match.presenter.C9872m; import dagger.MembersInjector; import javax.inject.Provider; /* renamed from: com.tinder.match.views.l */ public final class C12110l implements MembersInjector<MatchesSearchView> { /* renamed from: a */ private final Provider<C9872m> f39286a; public /* synthetic */ void injectMembers(Object obj) { m48248a((MatchesSearchView) obj); } /* renamed from: a */ public void m48248a(MatchesSearchView matchesSearchView) { C12110l.m48247a(matchesSearchView, (C9872m) this.f39286a.get()); } /* renamed from: a */ public static void m48247a(MatchesSearchView matchesSearchView, C9872m c9872m) { matchesSearchView.f39265a = c9872m; } }
UTF-8
Java
769
java
C12110l.java
Java
[]
null
[]
package com.tinder.match.views; import com.tinder.match.presenter.C9872m; import dagger.MembersInjector; import javax.inject.Provider; /* renamed from: com.tinder.match.views.l */ public final class C12110l implements MembersInjector<MatchesSearchView> { /* renamed from: a */ private final Provider<C9872m> f39286a; public /* synthetic */ void injectMembers(Object obj) { m48248a((MatchesSearchView) obj); } /* renamed from: a */ public void m48248a(MatchesSearchView matchesSearchView) { C12110l.m48247a(matchesSearchView, (C9872m) this.f39286a.get()); } /* renamed from: a */ public static void m48247a(MatchesSearchView matchesSearchView, C9872m c9872m) { matchesSearchView.f39265a = c9872m; } }
769
0.711313
0.621587
25
29.76
25.728241
84
false
false
0
0
0
0
0
0
0.4
false
false
7
fd4f328841a6541184daac88c30c9ce2d2ba4b5f
36,163,624,680,381
4141a0a0541dd76e80e0ee5a8093e4139c9a14d7
/app/src/main/java/bbq/com/app/SelectDateActivity.java
946409c8b905c5a237178e3c3170f9affce38c2d
[]
no_license
GAurav0812/bbq-crm-app
https://github.com/GAurav0812/bbq-crm-app
60573dae00b42aaf31f9b4b3f0b48b3ac21dbf10
cfd3a0f8e30daea7f1f6a3582de8a86b983f9ba9
refs/heads/master
2021-01-19T21:45:31.599000
2017-06-20T11:55:34
2017-06-20T11:55:34
88,704,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bbq.com.app; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SelectDateActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_date); } }
UTF-8
Java
337
java
SelectDateActivity.java
Java
[]
null
[]
package bbq.com.app; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SelectDateActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_date); } }
337
0.756677
0.753709
13
24.923077
22.922819
59
false
false
0
0
0
0
0
0
0.384615
false
false
7
c978219c244b821385eb0a950c0197d155232939
39,161,511,822,973
7cfc86ad2dbe7fbd510d5386b516b932104b8016
/src/main/java/qb/sudoku/presentation/AdminController.java
26fafcc1cd41d0ffbc2721daa4df7afa2c7f27de
[]
no_license
JakubWagner1019/sudoku-spring-server
https://github.com/JakubWagner1019/sudoku-spring-server
e8462d254f7912b48e9e3178c6eaa9ad0805000c
20d7942ee8a06cc0915542897cdfb2fb188542a1
refs/heads/master
2023-05-04T00:30:31.747000
2021-05-23T13:42:12
2021-05-23T13:42:12
356,858,998
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package qb.sudoku.presentation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import qb.sudoku.dto.SudokuGridDto; import qb.sudoku.models.SudokuGrid; import qb.sudoku.models.SudokuGridFactory; import qb.sudoku.models.SudokuSignature; import qb.sudoku.service.SudokuService; import java.util.List; @Controller @RequestMapping("/admin") public class AdminController { private final SudokuService sudokuService; private final SudokuGridFactory sudokuGridFactory; Logger logger = LoggerFactory.getLogger(AdminController.class); public AdminController(SudokuService sudokuService, SudokuGridFactory sudokuGridFactory) { this.sudokuService = sudokuService; this.sudokuGridFactory = sudokuGridFactory; } @GetMapping public String getAdminPage(Model model) { List<SudokuSignature> sudokuSignatures = sudokuService.getSudokuSignatures(); model.addAttribute("name", "Admin"); model.addAttribute("sudokuList", sudokuSignatures); return Views.ADMIN; } @GetMapping("/sudoku/create") public String getCreatePage(Model model) { SudokuGridDto gridDto = new SudokuGridDto(9); model.addAttribute("form", gridDto); return Views.CREATE_SUDOKU; } @PostMapping("/sudoku/create") public String doCreate(@ModelAttribute("form") SudokuGridDto sudokuGridDto) { logger.info("DTO {}", sudokuGridDto); SudokuGrid solved = sudokuGridFactory.getSolvedGrid(sudokuGridDto); SudokuGrid unsolved = sudokuGridFactory.getUnsolvedGrid(sudokuGridDto); logger.info("Unsolved {}", unsolved); logger.info("Solved {}", solved); sudokuService.addSudoku(sudokuGridDto.getName(), unsolved, solved); return "redirect:/admin"; } @GetMapping("/sudoku/edit/{id}") public String getEditPage(Model model, @PathVariable long id) { SudokuGrid sudokuGrid = sudokuService.getUnsolvedSudokuById(id); model.addAttribute("sudoku", sudokuGrid); return Views.EDIT_SUDOKU; } @GetMapping("/sudoku/delete/{id}") public String getDeletePage(Model model, @PathVariable long id) { SudokuGrid sudokuGrid = sudokuService.getUnsolvedSudokuById(id); model.addAttribute("sudoku", sudokuGrid); return Views.DELETE_SUDOKU; } }
UTF-8
Java
2,724
java
AdminController.java
Java
[]
null
[]
package qb.sudoku.presentation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import qb.sudoku.dto.SudokuGridDto; import qb.sudoku.models.SudokuGrid; import qb.sudoku.models.SudokuGridFactory; import qb.sudoku.models.SudokuSignature; import qb.sudoku.service.SudokuService; import java.util.List; @Controller @RequestMapping("/admin") public class AdminController { private final SudokuService sudokuService; private final SudokuGridFactory sudokuGridFactory; Logger logger = LoggerFactory.getLogger(AdminController.class); public AdminController(SudokuService sudokuService, SudokuGridFactory sudokuGridFactory) { this.sudokuService = sudokuService; this.sudokuGridFactory = sudokuGridFactory; } @GetMapping public String getAdminPage(Model model) { List<SudokuSignature> sudokuSignatures = sudokuService.getSudokuSignatures(); model.addAttribute("name", "Admin"); model.addAttribute("sudokuList", sudokuSignatures); return Views.ADMIN; } @GetMapping("/sudoku/create") public String getCreatePage(Model model) { SudokuGridDto gridDto = new SudokuGridDto(9); model.addAttribute("form", gridDto); return Views.CREATE_SUDOKU; } @PostMapping("/sudoku/create") public String doCreate(@ModelAttribute("form") SudokuGridDto sudokuGridDto) { logger.info("DTO {}", sudokuGridDto); SudokuGrid solved = sudokuGridFactory.getSolvedGrid(sudokuGridDto); SudokuGrid unsolved = sudokuGridFactory.getUnsolvedGrid(sudokuGridDto); logger.info("Unsolved {}", unsolved); logger.info("Solved {}", solved); sudokuService.addSudoku(sudokuGridDto.getName(), unsolved, solved); return "redirect:/admin"; } @GetMapping("/sudoku/edit/{id}") public String getEditPage(Model model, @PathVariable long id) { SudokuGrid sudokuGrid = sudokuService.getUnsolvedSudokuById(id); model.addAttribute("sudoku", sudokuGrid); return Views.EDIT_SUDOKU; } @GetMapping("/sudoku/delete/{id}") public String getDeletePage(Model model, @PathVariable long id) { SudokuGrid sudokuGrid = sudokuService.getUnsolvedSudokuById(id); model.addAttribute("sudoku", sudokuGrid); return Views.DELETE_SUDOKU; } }
2,724
0.73862
0.737518
73
36.315067
25.313852
94
false
false
0
0
0
0
0
0
0.739726
false
false
7
863ce50a70f7be1d60369755184a5a91b0c39496
9,165,460,275,078
1538507552d50ddb2e44fa1dee19435a9065cd09
/linguisum-core/src/main/java/pl/edu/pwr/szlagor/masterthesis/linguisticsummary/source/business/service/devicestate/DeviceStateSourceService.java
c4e81b6e02ff7f7f4df118ac2dad1d1dd9ba84f1
[]
no_license
pawel-szlagor/linguisum
https://github.com/pawel-szlagor/linguisum
243cd97aef5167af7e1536d73c6aa9e424a3be28
2273054cad9b5cbcd3218a0f1a0f222fd5c54c56
refs/heads/master
2021-01-11T18:52:49.869000
2017-03-27T18:45:10
2017-03-27T18:45:10
79,646,137
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.edu.pwr.szlagor.masterthesis.linguisticsummary.source.business.service.devicestate; import pl.edu.pwr.szlagor.masterthesis.linguisticsummary.source.business.model.DeviceStateSourceDto; import pl.edu.pwr.szlagor.masterthesis.linguisticsummary.source.business.service.CommonByDateService; /** * Created by Pawel on 2017-02-01. */ public interface DeviceStateSourceService extends CommonByDateService<DeviceStateSourceDto, Long> { }
UTF-8
Java
445
java
DeviceStateSourceService.java
Java
[ { "context": "ss.service.CommonByDateService;\n\n/**\n * Created by Pawel on 2017-02-01.\n */\npublic interface DeviceStateSo", "end": 323, "score": 0.9979262351989746, "start": 318, "tag": "NAME", "value": "Pawel" } ]
null
[]
package pl.edu.pwr.szlagor.masterthesis.linguisticsummary.source.business.service.devicestate; import pl.edu.pwr.szlagor.masterthesis.linguisticsummary.source.business.model.DeviceStateSourceDto; import pl.edu.pwr.szlagor.masterthesis.linguisticsummary.source.business.service.CommonByDateService; /** * Created by Pawel on 2017-02-01. */ public interface DeviceStateSourceService extends CommonByDateService<DeviceStateSourceDto, Long> { }
445
0.842697
0.824719
10
43.5
45.924393
101
false
false
0
0
0
0
0
0
0.4
false
false
7
fc3e279bc075301f7edeaa43713733f293de469d
2,637,109,962,560
e867ac0a74e88f0df07213fa5c074de53e38fa40
/系列1-Spring源码解析及手写Spring/第6节课/spring-anno/src/main/java/com/enjoy/cap9/bean/Sun.java
6c0d25a107bc3e8aedc11fa05827f71faaaf615b
[ "Apache-2.0" ]
permissive
walesu/corresponding-auxiliary-data
https://github.com/walesu/corresponding-auxiliary-data
0fb08ca33b1b8b58e11203af6c0e39c7e4a6ce79
b0b7b6bb8e258181a17b8f1ab349492d5c3250e7
refs/heads/main
2022-08-30T00:56:43.652000
2022-08-15T09:42:13
2022-08-15T09:42:13
421,372,692
55
61
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.enjoy.cap9.bean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Sun { private Moon moon; public Sun(@Autowired Moon moon){ this.moon = moon; System.out.println("..Constructor................"); } public Moon getMoon() { return moon; } public void setMoon(Moon moon) { this.moon = moon; } @Override public String toString() { return "Sun [moon=" + moon + "]"; } }
UTF-8
Java
492
java
Sun.java
Java
[]
null
[]
package com.enjoy.cap9.bean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Sun { private Moon moon; public Sun(@Autowired Moon moon){ this.moon = moon; System.out.println("..Constructor................"); } public Moon getMoon() { return moon; } public void setMoon(Moon moon) { this.moon = moon; } @Override public String toString() { return "Sun [moon=" + moon + "]"; } }
492
0.676829
0.674797
27
17.222221
17.676796
62
false
false
0
0
0
0
0
0
1.148148
false
false
7
558338b904ea587194abad91e60ee4769c203c03
10,900,627,019,485
d61e855b537e35fa827d1a35ee63cedab1a5d530
/src/main/java/com/project1/rest/webservices/resfulwebservices/palindrome/StringPalindrome.java
9cb5493e0c6bbfe4f536e5618f28941d97d0026e
[]
no_license
azamakhan/longest_palindrome_api
https://github.com/azamakhan/longest_palindrome_api
60a031bd24665fbc4bee20a83bd2e737f6b972c9
c001ce64121c9be7e21b2bf596e65e1f337b7254
refs/heads/master
2022-12-03T11:16:45.758000
2020-08-26T18:01:36
2020-08-26T18:01:36
290,564,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.project1.rest.webservices.resfulwebservices.palindrome; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class StringPalindrome { @Id private String str; private String palindrome; public StringPalindrome() { } public StringPalindrome (String str, String palindrome) { //this.id = id; this.str = str; this.palindrome = palindrome; } @Column(name = "palindrome", nullable = false) public String getStr() { return str; } public void setStr(String str) { this.str = str; } @Column(name = "string", nullable = false) public String getPalindrome() { return palindrome; } public void setPalindrome(String palindrome) { this.palindrome = palindrome; } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // @Override public String toString() { return String.format("String: %s, Palindrome: %s", str, palindrome); } }
UTF-8
Java
1,033
java
StringPalindrome.java
Java
[]
null
[]
package com.project1.rest.webservices.resfulwebservices.palindrome; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class StringPalindrome { @Id private String str; private String palindrome; public StringPalindrome() { } public StringPalindrome (String str, String palindrome) { //this.id = id; this.str = str; this.palindrome = palindrome; } @Column(name = "palindrome", nullable = false) public String getStr() { return str; } public void setStr(String str) { this.str = str; } @Column(name = "string", nullable = false) public String getPalindrome() { return palindrome; } public void setPalindrome(String palindrome) { this.palindrome = palindrome; } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // @Override public String toString() { return String.format("String: %s, Palindrome: %s", str, palindrome); } }
1,033
0.693127
0.692159
58
16.810345
18.06259
70
false
false
0
0
0
0
0
0
1.362069
false
false
7
e6bfcf7eeeccff4a2fa565e038135636d88e49cf
12,154,757,463,609
e43a6e21c11565d26651016c080bbe5188dcc5ca
/src/gaurav/Delete.java
b98b7edf3fbda97d558e5bbdcf7f8570d19c8c95
[]
no_license
GM123d/lgeproject
https://github.com/GM123d/lgeproject
d7936a18a96169333765a4ff6092e75348573dd2
eba807eec07c25c50f1b11964246209850387ba4
refs/heads/master
2020-05-23T15:06:32.340000
2019-05-25T09:08:02
2019-05-25T09:08:02
186,819,355
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gaurav; import java.sql.*; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Delete */ public class Delete extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ResultSet rs = null; PreparedStatement p = null, pm = null, pmm = null; Connection con = null; String[] itemId = request.getParameterValues("itemId"); int itemIdKey = Integer.parseInt(itemId[0]); int primaryKey = 0; try { Class.forName("org.h2.Driver"); con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa", ""); p = con.prepareStatement("Select * from inventory where item_id=?"); pm = con.prepareStatement("Select * from inventory where id=?"); pmm = con.prepareStatement("delete from inventory where item_id=?"); p.setInt(1, itemIdKey); rs = p.executeQuery(); while (rs.next()) { primaryKey = rs.getInt("id"); } pm.setInt(1, primaryKey); rs = pm.executeQuery(); while (rs.next()) { int j = 0; for (int i = 0; i < itemId.length; i++) { if (Integer.parseInt(itemId[i]) == rs.getInt("Item_id")) { j++; } } if (j == 0) { pmm.setInt(1, rs.getInt("Item_id")); pmm.executeUpdate(); } } RequestDispatcher d = request.getRequestDispatcher("Edit"); d.forward(request, response); } catch (Exception e) { System.out.println(e); } finally { try { if (p != null) { p.close(); } if (con != null) { con.close(); } if (pmm != null) { pmm.close(); } if (pm != null) { pm.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
UTF-8
Java
1,941
java
Delete.java
Java
[]
null
[]
package gaurav; import java.sql.*; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Delete */ public class Delete extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ResultSet rs = null; PreparedStatement p = null, pm = null, pmm = null; Connection con = null; String[] itemId = request.getParameterValues("itemId"); int itemIdKey = Integer.parseInt(itemId[0]); int primaryKey = 0; try { Class.forName("org.h2.Driver"); con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa", ""); p = con.prepareStatement("Select * from inventory where item_id=?"); pm = con.prepareStatement("Select * from inventory where id=?"); pmm = con.prepareStatement("delete from inventory where item_id=?"); p.setInt(1, itemIdKey); rs = p.executeQuery(); while (rs.next()) { primaryKey = rs.getInt("id"); } pm.setInt(1, primaryKey); rs = pm.executeQuery(); while (rs.next()) { int j = 0; for (int i = 0; i < itemId.length; i++) { if (Integer.parseInt(itemId[i]) == rs.getInt("Item_id")) { j++; } } if (j == 0) { pmm.setInt(1, rs.getInt("Item_id")); pmm.executeUpdate(); } } RequestDispatcher d = request.getRequestDispatcher("Edit"); d.forward(request, response); } catch (Exception e) { System.out.println(e); } finally { try { if (p != null) { p.close(); } if (con != null) { con.close(); } if (pmm != null) { pmm.close(); } if (pm != null) { pm.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
1,941
0.627512
0.62236
97
19.010309
20.929678
81
false
false
0
0
0
0
0
0
2.43299
false
false
7
463aa535b5d59557f1c4c7f4c77ce2d29fc90777
27,917,287,485,693
6fbf02844804bd66d80d0a2ae77b5aff9fab91b9
/src/refactoring/Menu.java
977c4b773e6eb5414662463edd9733e1d8a8ce0a
[]
no_license
jbul/refactoringAssignment
https://github.com/jbul/refactoringAssignment
8fbbaa147a16fc12e8908461e43a082edc97b002
a48afb36fd97f57aabf3c339ba78550c638883e0
refs/heads/master
2021-02-06T23:41:17.091000
2020-03-08T21:56:30
2020-03-08T21:56:30
243,957,240
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package refactoring; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.SwingConstants; import refactoring.constants.ButtonConstants; import refactoring.constants.Constants; import refactoring.constants.MessageConstants; import refactoring.listeners.admin.AccountButtonListener; import refactoring.listeners.admin.BankChargesButtonListener; import refactoring.listeners.admin.DeleteAccountListener; import refactoring.listeners.admin.DeleteCustomerListener; import refactoring.listeners.admin.EditCustomerButtonListener; import refactoring.listeners.admin.InterestButtonListener; import refactoring.listeners.admin.NavigationListener; import refactoring.listeners.admin.SummaryButtonListener; import refactoring.listeners.customer.LodgementButtonListener; import refactoring.listeners.customer.StatementListener; import refactoring.listeners.customer.WithdrawButtonListener; import refactoring.listeners.general.ReturnButtonListener; import refactoring.service.CustomerService; public class Menu extends JFrame { public int position = 0; public String password; public Customer customer = null; public CustomerAccount customerAccount; public JFrame frame, adminFrame; public JLabel firstNameLabel, surnameLabel, pPPSLabel, dOBLabel; public JTextField firstNameTextField, surnameTextField, pPSTextField, dOBTextField; public JLabel customerIDLabel, passwordLabel; public JTextField customerIDTextField, passwordTextField; public Container content; public Customer cust; JPanel panel2; JButton addButton; String PPS, firstName, surname, DOB, CustomerID; private CustomerService customerService = CustomerService.getInstance(); public static void main(String[] args) { Menu driver = new Menu(); driver.menuStart(); } public CustomerService getCustomerService() { return customerService; } public void menuStart() { /* * The menuStart method asks the user if they are a new customer, an existing * customer or an admin. It will then start the create customer process if they * are a new customer, or will ask them to log in if they are an existing * customer or admin. */ frame = new JFrame("User Type"); frame.setSize(400, 300); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); JPanel userTypePanel = new JPanel(); final ButtonGroup userType = new ButtonGroup(); // TODO Method to add button addToPanel(userTypePanel, userType, "Existing Customer", "Customer"); addToPanel(userTypePanel, userType, Constants.ADMIN, Constants.ADMIN); addToPanel(userTypePanel, userType, Constants.NEW_CUSTOMER, Constants.NEW_CUSTOMER); JPanel continuePanel = new JPanel(); JButton continueButton = new JButton("Continue"); continuePanel.add(continueButton); Container content = frame.getContentPane(); content.setLayout(new GridLayout(2, 1)); content.add(userTypePanel); content.add(continuePanel); continueButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String user = userType.getSelection().getActionCommand(); // if user selects NEW CUSTOMER switch (user) { case Constants.NEW_CUSTOMER: newCustomerSwitch(); break; // if user select ADMIN case Constants.ADMIN: adminSwitch(); break; // if user selects CUSTOMER case "Customer": customerSwitch(); break; } } private void customerSwitch() { boolean loop = true, loop2 = true; boolean cont = false; Customer customer = null; // Loop to find username while (loop) { Object customerID = JOptionPane.showInputDialog(frame, "Enter Customer ID:"); customer = customerService.getCustomer(customerID); // TODO Replace found by customer null or not if (customer == null) { int reply = JOptionPane.showConfirmDialog(null, null, MessageConstants.USER_NOT_FOUND, JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { loop = true; } else if (reply == JOptionPane.NO_OPTION) { frame.dispose(); loop = false; loop2 = false; menuStart(); } } else { loop = false; } } // Loop to check password while (loop2) { Object customerPassword = JOptionPane.showInputDialog(frame, "Enter Customer Password;"); if (!customer.getPassword().equals(customerPassword))// check if customer password is correct { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect password. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { loop2 = true; } else if (reply == JOptionPane.NO_OPTION) { frame.dispose(); loop2 = false; menuStart(); } } else { loop2 = false; cont = true; } } if (cont) { frame.dispose(); loop = false; customer(customer); } } private void adminSwitch() { boolean loop = true, loop2 = true; boolean cont = false; while (loop) { Object adminUsername = JOptionPane.showInputDialog(frame, "Enter Administrator Username:"); if (!adminUsername.equals("admin"))// search admin list for admin with matching admin username { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect Username. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { loop = true; } else if (reply == JOptionPane.NO_OPTION) { adminFrame.dispose(); loop = false; loop2 = false; menuStart(); } } else { loop = false; } } while (loop2) { Object adminPassword = JOptionPane.showInputDialog(frame, "Enter Administrator Password;"); if (!adminPassword.equals("admin11"))// search admin list for admin with matching admin password { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect Password. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { } else if (reply == JOptionPane.NO_OPTION) { adminFrame.dispose(); loop2 = false; menuStart(); } } else { loop2 = false; cont = true; } } if (cont) { // TODO is null at this stage if (adminFrame != null) { adminFrame.dispose(); } loop = false; admin(); } } private void newCustomerSwitch() { frame.dispose(); adminFrame = new JFrame("Create New Customer"); adminFrame.setSize(400, 300); adminFrame.setLocation(200, 200); adminFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); Container content = adminFrame.getContentPane(); content.setLayout(new BorderLayout()); firstNameLabel = new JLabel("First Name:", SwingConstants.RIGHT); surnameLabel = new JLabel("Surname:", SwingConstants.RIGHT); pPPSLabel = new JLabel("PPS Number:", SwingConstants.RIGHT); dOBLabel = new JLabel("Date of birth", SwingConstants.RIGHT); firstNameTextField = new JTextField(20); surnameTextField = new JTextField(20); pPSTextField = new JTextField(20); dOBTextField = new JTextField(20); JPanel panel = new JPanel(new GridLayout(6, 2)); panel.add(firstNameLabel); panel.add(firstNameTextField); panel.add(surnameLabel); panel.add(surnameTextField); panel.add(pPPSLabel); panel.add(pPSTextField); panel.add(dOBLabel); panel.add(dOBTextField); panel2 = new JPanel(); addButton = new JButton("Add"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PPS = pPSTextField.getText(); firstName = firstNameTextField.getText(); surname = surnameTextField.getText(); DOB = dOBTextField.getText(); password = ""; CustomerID = "ID" + PPS; addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adminFrame.dispose(); boolean loop = true; while (loop) { password = JOptionPane.showInputDialog(frame, "Enter 7 character Password;"); if (password.length() != 7)// Making sure password is 7 characters { JOptionPane.showMessageDialog(null, null, "Password must be 7 charatcers long", JOptionPane.OK_OPTION); } else { loop = false; } } ArrayList<CustomerAccount> accounts = new ArrayList<CustomerAccount>(); Customer customer = new Customer(PPS, surname, firstName, DOB, CustomerID, password, accounts); getCustomerService().addCustomer(customer); JOptionPane.showMessageDialog(frame, "CustomerID = " + CustomerID + "\n Password = " + password, "Customer created.", JOptionPane.INFORMATION_MESSAGE); menuStart(); frame.dispose(); } }); } }); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adminFrame.dispose(); menuStart(); } }); panel2.add(addButton); panel2.add(cancel); content.add(panel, BorderLayout.CENTER); content.add(panel2, BorderLayout.SOUTH); adminFrame.setVisible(true); } }); frame.setVisible(true); } private void addToPanel(JPanel userTypePanel, final ButtonGroup userType, String buttonTitle, String actionName) { JRadioButton radioButton = new JRadioButton(buttonTitle); userTypePanel.add(radioButton); radioButton.setActionCommand(actionName); userType.add(radioButton); } public void admin() { dispose(); frame = new JFrame("Administrator Menu"); frame.setSize(400, 400); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); frame.setVisible(true); // TODO Same code everywhere, candidate for refactoring List<JPanel> panels = new ArrayList<>(); panels.add(generatePanel("Delete Customer", new DeleteCustomerListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Delete Account", new DeleteAccountListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Apply Bank Charges", new BankChargesButtonListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Apply Interest", new InterestButtonListener(this), null, FlowLayout.LEFT)); panels.add( generatePanel("Edit existing Customer", new EditCustomerButtonListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Navigate Customer Collection", new NavigationListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Display Summary Of All Accounts", new SummaryButtonListener(this), null, FlowLayout.LEFT)); panels.add( generatePanel("Add an Account to a Customer", new AccountButtonListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Exit Admin Menu", new ReturnButtonListener(this), null, FlowLayout.RIGHT)); // End refactoring panels addPanels(new GridLayout(10, 1), panels, "Please select an option"); } private JPanel generatePanel(String title, ActionListener listener, Dimension size, int align) { JPanel returnPanel = new JPanel(new FlowLayout(align)); JButton returnButton = new JButton(title); returnPanel.add(returnButton); returnButton.addActionListener(listener); if (size != null) { returnPanel.setPreferredSize(size); } return returnPanel; } public void customer(Customer e1) { frame = new JFrame("Customer Menu"); // TODO Looks like a bug... // e1 = e; cust = e1; frame.setSize(400, 300); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); frame.setVisible(true); // To be used in actionListeners Menu context = this; if (cust.getAccounts().size() == 0) { JOptionPane.showMessageDialog(frame, "This customer does not have any accounts yet. \n An admin must create an account for this customer \n for them to be able to use customer functionality. ", Constants.OOPS, JOptionPane.INFORMATION_MESSAGE); frame.dispose(); menuStart(); } else { JPanel buttonPanel = new JPanel(); JPanel boxPanel = new JPanel(); JPanel labelPanel = new JPanel(); JLabel label = new JLabel("Select Account:"); labelPanel.add(label); JButton returnButton = new JButton(ButtonConstants.RETURN); buttonPanel.add(returnButton); JButton continueButton = new JButton("Continue"); buttonPanel.add(continueButton); JComboBox<String> box = new JComboBox<String>(); for (int i = 0; i < cust.getAccounts().size(); i++) { box.addItem(cust.getAccounts().get(i).getNumber()); } // TODO Fix bug if continue is clicked without choosing anything. Account should // be set to the first from list of accounts. if (customerAccount != null) { box.setSelectedItem(customerAccount); } else { customerAccount = cust.getAccounts().get(0); } box.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < cust.getAccounts().size(); i++) { if (cust.getAccounts().get(i).getNumber() == box.getSelectedItem()) { customerAccount = cust.getAccounts().get(i); } } } }); boxPanel.add(box); content = frame.getContentPane(); content.setLayout(new GridLayout(3, 1)); content.add(labelPanel); content.add(boxPanel); content.add(buttonPanel); returnButton.addActionListener(new ReturnButtonListener(this)); continueButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { frame.dispose(); frame = new JFrame("Customer Menu"); frame.setSize(400, 300); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); frame.setVisible(true); List<JPanel> panels = new ArrayList<>(); panels.add(generatePanel("Display Bank Statement", new StatementListener(context), new Dimension(250, 20), FlowLayout.LEFT)); panels.add(generatePanel("Lodge money into account", new LodgementButtonListener(context), new Dimension(250, 20), FlowLayout.LEFT)); panels.add(generatePanel("Withdraw money from account", new WithdrawButtonListener(context), new Dimension(250, 20), FlowLayout.LEFT)); panels.add(generatePanel("Exit CustomerMenu", new ReturnButtonListener(context), null, FlowLayout.RIGHT)); addPanels(new GridLayout(5, 1), panels, "Please select an option"); } }); } } private void addPanels(GridLayout layout, List<JPanel> panels, String title) { JLabel label1 = new JLabel(title); content = frame.getContentPane(); content.setLayout(layout); content.add(label1); for (JPanel jp : panels) { content.add(jp); } } /** * A method that tests if a string is numeric * * @param str * @return */ public static boolean isNumeric(String str) { try { Double.parseDouble(str); } catch (NumberFormatException nfe) { return false; } return true; } }
UTF-8
Java
16,025
java
Menu.java
Java
[ { "context": "\n\n\tJPanel panel2;\n\tJButton addButton;\n\tString PPS, firstName, surname, DOB, CustomerID;\n\n\tprivate CustomerServ", "end": 2140, "score": 0.9826934337615967, "start": 2131, "tag": "NAME", "value": "firstName" }, { "context": "anel2;\n\tJButton addButton;\n\tString PPS, firstName, surname, DOB, CustomerID;\n\n\tprivate CustomerService custo", "end": 2149, "score": 0.8799281716346741, "start": 2142, "tag": "NAME", "value": "surname" }, { "context": "tor Username:\");\n\n\t\t\t\t\tif (!adminUsername.equals(\"admin\"))// search admin list for admin with matching ad", "end": 5840, "score": 0.9802000522613525, "start": 5835, "tag": "USERNAME", "value": "admin" }, { "context": "tor Password;\");\n\n\t\t\t\t\tif (!adminPassword.equals(\"admin11\"))// search admin list for admin with matching ad", "end": 6461, "score": 0.999047040939331, "start": 6454, "tag": "PASSWORD", "value": "admin11" }, { "context": "\t\"CustomerID = \" + CustomerID + \"\\n Password = \" + password, \"Customer created.\",\n\t\t\t\t\t\t\t\t\t\tJOptionPane.INFOR", "end": 9517, "score": 0.9654831290245056, "start": 9509, "tag": "PASSWORD", "value": "password" } ]
null
[]
package refactoring; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.SwingConstants; import refactoring.constants.ButtonConstants; import refactoring.constants.Constants; import refactoring.constants.MessageConstants; import refactoring.listeners.admin.AccountButtonListener; import refactoring.listeners.admin.BankChargesButtonListener; import refactoring.listeners.admin.DeleteAccountListener; import refactoring.listeners.admin.DeleteCustomerListener; import refactoring.listeners.admin.EditCustomerButtonListener; import refactoring.listeners.admin.InterestButtonListener; import refactoring.listeners.admin.NavigationListener; import refactoring.listeners.admin.SummaryButtonListener; import refactoring.listeners.customer.LodgementButtonListener; import refactoring.listeners.customer.StatementListener; import refactoring.listeners.customer.WithdrawButtonListener; import refactoring.listeners.general.ReturnButtonListener; import refactoring.service.CustomerService; public class Menu extends JFrame { public int position = 0; public String password; public Customer customer = null; public CustomerAccount customerAccount; public JFrame frame, adminFrame; public JLabel firstNameLabel, surnameLabel, pPPSLabel, dOBLabel; public JTextField firstNameTextField, surnameTextField, pPSTextField, dOBTextField; public JLabel customerIDLabel, passwordLabel; public JTextField customerIDTextField, passwordTextField; public Container content; public Customer cust; JPanel panel2; JButton addButton; String PPS, firstName, surname, DOB, CustomerID; private CustomerService customerService = CustomerService.getInstance(); public static void main(String[] args) { Menu driver = new Menu(); driver.menuStart(); } public CustomerService getCustomerService() { return customerService; } public void menuStart() { /* * The menuStart method asks the user if they are a new customer, an existing * customer or an admin. It will then start the create customer process if they * are a new customer, or will ask them to log in if they are an existing * customer or admin. */ frame = new JFrame("User Type"); frame.setSize(400, 300); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); JPanel userTypePanel = new JPanel(); final ButtonGroup userType = new ButtonGroup(); // TODO Method to add button addToPanel(userTypePanel, userType, "Existing Customer", "Customer"); addToPanel(userTypePanel, userType, Constants.ADMIN, Constants.ADMIN); addToPanel(userTypePanel, userType, Constants.NEW_CUSTOMER, Constants.NEW_CUSTOMER); JPanel continuePanel = new JPanel(); JButton continueButton = new JButton("Continue"); continuePanel.add(continueButton); Container content = frame.getContentPane(); content.setLayout(new GridLayout(2, 1)); content.add(userTypePanel); content.add(continuePanel); continueButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String user = userType.getSelection().getActionCommand(); // if user selects NEW CUSTOMER switch (user) { case Constants.NEW_CUSTOMER: newCustomerSwitch(); break; // if user select ADMIN case Constants.ADMIN: adminSwitch(); break; // if user selects CUSTOMER case "Customer": customerSwitch(); break; } } private void customerSwitch() { boolean loop = true, loop2 = true; boolean cont = false; Customer customer = null; // Loop to find username while (loop) { Object customerID = JOptionPane.showInputDialog(frame, "Enter Customer ID:"); customer = customerService.getCustomer(customerID); // TODO Replace found by customer null or not if (customer == null) { int reply = JOptionPane.showConfirmDialog(null, null, MessageConstants.USER_NOT_FOUND, JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { loop = true; } else if (reply == JOptionPane.NO_OPTION) { frame.dispose(); loop = false; loop2 = false; menuStart(); } } else { loop = false; } } // Loop to check password while (loop2) { Object customerPassword = JOptionPane.showInputDialog(frame, "Enter Customer Password;"); if (!customer.getPassword().equals(customerPassword))// check if customer password is correct { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect password. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { loop2 = true; } else if (reply == JOptionPane.NO_OPTION) { frame.dispose(); loop2 = false; menuStart(); } } else { loop2 = false; cont = true; } } if (cont) { frame.dispose(); loop = false; customer(customer); } } private void adminSwitch() { boolean loop = true, loop2 = true; boolean cont = false; while (loop) { Object adminUsername = JOptionPane.showInputDialog(frame, "Enter Administrator Username:"); if (!adminUsername.equals("admin"))// search admin list for admin with matching admin username { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect Username. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { loop = true; } else if (reply == JOptionPane.NO_OPTION) { adminFrame.dispose(); loop = false; loop2 = false; menuStart(); } } else { loop = false; } } while (loop2) { Object adminPassword = JOptionPane.showInputDialog(frame, "Enter Administrator Password;"); if (!adminPassword.equals("<PASSWORD>"))// search admin list for admin with matching admin password { int reply = JOptionPane.showConfirmDialog(null, null, "Incorrect Password. Try again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { } else if (reply == JOptionPane.NO_OPTION) { adminFrame.dispose(); loop2 = false; menuStart(); } } else { loop2 = false; cont = true; } } if (cont) { // TODO is null at this stage if (adminFrame != null) { adminFrame.dispose(); } loop = false; admin(); } } private void newCustomerSwitch() { frame.dispose(); adminFrame = new JFrame("Create New Customer"); adminFrame.setSize(400, 300); adminFrame.setLocation(200, 200); adminFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); Container content = adminFrame.getContentPane(); content.setLayout(new BorderLayout()); firstNameLabel = new JLabel("First Name:", SwingConstants.RIGHT); surnameLabel = new JLabel("Surname:", SwingConstants.RIGHT); pPPSLabel = new JLabel("PPS Number:", SwingConstants.RIGHT); dOBLabel = new JLabel("Date of birth", SwingConstants.RIGHT); firstNameTextField = new JTextField(20); surnameTextField = new JTextField(20); pPSTextField = new JTextField(20); dOBTextField = new JTextField(20); JPanel panel = new JPanel(new GridLayout(6, 2)); panel.add(firstNameLabel); panel.add(firstNameTextField); panel.add(surnameLabel); panel.add(surnameTextField); panel.add(pPPSLabel); panel.add(pPSTextField); panel.add(dOBLabel); panel.add(dOBTextField); panel2 = new JPanel(); addButton = new JButton("Add"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PPS = pPSTextField.getText(); firstName = firstNameTextField.getText(); surname = surnameTextField.getText(); DOB = dOBTextField.getText(); password = ""; CustomerID = "ID" + PPS; addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adminFrame.dispose(); boolean loop = true; while (loop) { password = JOptionPane.showInputDialog(frame, "Enter 7 character Password;"); if (password.length() != 7)// Making sure password is 7 characters { JOptionPane.showMessageDialog(null, null, "Password must be 7 charatcers long", JOptionPane.OK_OPTION); } else { loop = false; } } ArrayList<CustomerAccount> accounts = new ArrayList<CustomerAccount>(); Customer customer = new Customer(PPS, surname, firstName, DOB, CustomerID, password, accounts); getCustomerService().addCustomer(customer); JOptionPane.showMessageDialog(frame, "CustomerID = " + CustomerID + "\n Password = " + <PASSWORD>, "Customer created.", JOptionPane.INFORMATION_MESSAGE); menuStart(); frame.dispose(); } }); } }); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adminFrame.dispose(); menuStart(); } }); panel2.add(addButton); panel2.add(cancel); content.add(panel, BorderLayout.CENTER); content.add(panel2, BorderLayout.SOUTH); adminFrame.setVisible(true); } }); frame.setVisible(true); } private void addToPanel(JPanel userTypePanel, final ButtonGroup userType, String buttonTitle, String actionName) { JRadioButton radioButton = new JRadioButton(buttonTitle); userTypePanel.add(radioButton); radioButton.setActionCommand(actionName); userType.add(radioButton); } public void admin() { dispose(); frame = new JFrame("Administrator Menu"); frame.setSize(400, 400); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); frame.setVisible(true); // TODO Same code everywhere, candidate for refactoring List<JPanel> panels = new ArrayList<>(); panels.add(generatePanel("Delete Customer", new DeleteCustomerListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Delete Account", new DeleteAccountListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Apply Bank Charges", new BankChargesButtonListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Apply Interest", new InterestButtonListener(this), null, FlowLayout.LEFT)); panels.add( generatePanel("Edit existing Customer", new EditCustomerButtonListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Navigate Customer Collection", new NavigationListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Display Summary Of All Accounts", new SummaryButtonListener(this), null, FlowLayout.LEFT)); panels.add( generatePanel("Add an Account to a Customer", new AccountButtonListener(this), null, FlowLayout.LEFT)); panels.add(generatePanel("Exit Admin Menu", new ReturnButtonListener(this), null, FlowLayout.RIGHT)); // End refactoring panels addPanels(new GridLayout(10, 1), panels, "Please select an option"); } private JPanel generatePanel(String title, ActionListener listener, Dimension size, int align) { JPanel returnPanel = new JPanel(new FlowLayout(align)); JButton returnButton = new JButton(title); returnPanel.add(returnButton); returnButton.addActionListener(listener); if (size != null) { returnPanel.setPreferredSize(size); } return returnPanel; } public void customer(Customer e1) { frame = new JFrame("Customer Menu"); // TODO Looks like a bug... // e1 = e; cust = e1; frame.setSize(400, 300); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); frame.setVisible(true); // To be used in actionListeners Menu context = this; if (cust.getAccounts().size() == 0) { JOptionPane.showMessageDialog(frame, "This customer does not have any accounts yet. \n An admin must create an account for this customer \n for them to be able to use customer functionality. ", Constants.OOPS, JOptionPane.INFORMATION_MESSAGE); frame.dispose(); menuStart(); } else { JPanel buttonPanel = new JPanel(); JPanel boxPanel = new JPanel(); JPanel labelPanel = new JPanel(); JLabel label = new JLabel("Select Account:"); labelPanel.add(label); JButton returnButton = new JButton(ButtonConstants.RETURN); buttonPanel.add(returnButton); JButton continueButton = new JButton("Continue"); buttonPanel.add(continueButton); JComboBox<String> box = new JComboBox<String>(); for (int i = 0; i < cust.getAccounts().size(); i++) { box.addItem(cust.getAccounts().get(i).getNumber()); } // TODO Fix bug if continue is clicked without choosing anything. Account should // be set to the first from list of accounts. if (customerAccount != null) { box.setSelectedItem(customerAccount); } else { customerAccount = cust.getAccounts().get(0); } box.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < cust.getAccounts().size(); i++) { if (cust.getAccounts().get(i).getNumber() == box.getSelectedItem()) { customerAccount = cust.getAccounts().get(i); } } } }); boxPanel.add(box); content = frame.getContentPane(); content.setLayout(new GridLayout(3, 1)); content.add(labelPanel); content.add(boxPanel); content.add(buttonPanel); returnButton.addActionListener(new ReturnButtonListener(this)); continueButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { frame.dispose(); frame = new JFrame("Customer Menu"); frame.setSize(400, 300); frame.setLocation(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); frame.setVisible(true); List<JPanel> panels = new ArrayList<>(); panels.add(generatePanel("Display Bank Statement", new StatementListener(context), new Dimension(250, 20), FlowLayout.LEFT)); panels.add(generatePanel("Lodge money into account", new LodgementButtonListener(context), new Dimension(250, 20), FlowLayout.LEFT)); panels.add(generatePanel("Withdraw money from account", new WithdrawButtonListener(context), new Dimension(250, 20), FlowLayout.LEFT)); panels.add(generatePanel("Exit CustomerMenu", new ReturnButtonListener(context), null, FlowLayout.RIGHT)); addPanels(new GridLayout(5, 1), panels, "Please select an option"); } }); } } private void addPanels(GridLayout layout, List<JPanel> panels, String title) { JLabel label1 = new JLabel(title); content = frame.getContentPane(); content.setLayout(layout); content.add(label1); for (JPanel jp : panels) { content.add(jp); } } /** * A method that tests if a string is numeric * * @param str * @return */ public static boolean isNumeric(String str) { try { Double.parseDouble(str); } catch (NumberFormatException nfe) { return false; } return true; } }
16,030
0.692481
0.684306
527
29.409866
26.771698
161
false
false
0
0
0
0
0
0
3.776091
false
false
7
c9cf05a12105d3881904d08298d12caabf462bee
5,068,061,467,223
7bc79a6aba16a0b7581f7b20317b46a0ee5a9949
/src/main/java/com/sophie/muliti_thread/daemon/MyThread.java
8820f3685cf31d14b3eceef884bfc13e36bdfe73
[]
no_license
941283088/Java-demo
https://github.com/941283088/Java-demo
b81e7939cc3da7de686f3d21b3cc52aebb884ccf
b7268fe696703fa9841774bcb51824da3f6b057a
refs/heads/master
2022-04-25T08:47:28.734000
2020-04-28T14:13:29
2020-04-28T14:13:29
258,202,404
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sophie.muliti_thread.daemon; /** * Created by yiqiang on 2020/4/26. */ public class MyThread extends Thread { private int i=0; public void run() { try{ while (true) { i++; System.out.println("i="+(i)); sleep(1000); } }catch (InterruptedException e) { e.printStackTrace(); } } }
UTF-8
Java
437
java
MyThread.java
Java
[ { "context": "om.sophie.muliti_thread.daemon;\n\n/**\n * Created by yiqiang on 2020/4/26.\n */\npublic class MyThread extends T", "end": 67, "score": 0.9986458420753479, "start": 60, "tag": "USERNAME", "value": "yiqiang" } ]
null
[]
package com.sophie.muliti_thread.daemon; /** * Created by yiqiang on 2020/4/26. */ public class MyThread extends Thread { private int i=0; public void run() { try{ while (true) { i++; System.out.println("i="+(i)); sleep(1000); } }catch (InterruptedException e) { e.printStackTrace(); } } }
437
0.453089
0.425629
22
18.863636
14.020425
45
false
false
0
0
0
0
0
0
0.272727
false
false
7
21c6e774a6fda3949f71858e365353713a43b4bf
24,292,335,062,292
d1f8d1da73b4cb96043b961139cd27e61c7964f2
/src/main/java/ua/com/integrity/smalltalkingbot/bot/SmallTalkingBot.java
b2adf1e3807e9d3c7b61479b841e748e068d7ef8
[]
no_license
AgienkoSergiy/smalltalkingbot
https://github.com/AgienkoSergiy/smalltalkingbot
e062ffa33707dff2e199f64620c8e7d1b10df33c
79e2483a2df56d4c125a618141a85a1ad9091a0f
refs/heads/master
2021-05-05T07:00:29.354000
2019-03-27T14:49:44
2019-03-27T14:49:44
118,846,528
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.com.integrity.smalltalkingbot.bot; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.methods.send.SendPhoto; import org.telegram.telegrambots.api.objects.PhotoSize; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardRemove; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.exceptions.TelegramApiException; import ua.com.integrity.smalltalkingbot.controller.NotificationController; import ua.com.integrity.smalltalkingbot.controller.OrderController; import ua.com.integrity.smalltalkingbot.controller.UserController; import ua.com.integrity.smalltalkingbot.message.MessageBuilder; import ua.com.integrity.smalltalkingbot.model.Product; import ua.com.integrity.smalltalkingbot.controller.ProductController; import ua.com.integrity.smalltalkingbot.repository.ProductRepository; import ua.com.integrity.smalltalkingbot.util.CommonUtils; import ua.com.integrity.smalltalkingbot.util.DBUtil; import java.util.Collection; import java.util.Comparator; import java.util.List; public class SmallTalkingBot extends TelegramLongPollingBot { private ProductController productController; private OrderController orderController; private NotificationController notificationController; private UserController userController; public SmallTalkingBot() { this.productController = new ProductController(this); this.orderController = new OrderController(this); this.notificationController = new NotificationController(this); this.userController = new UserController(); DBUtil.getInstance(); } public void onUpdateReceived(Update update) { long chatId = update.getMessage().getChatId(); if (update.hasMessage() && update.getMessage().hasText()) { String messageText = update.getMessage().getText(); if (orderController.isActiveOrder(chatId)){ if (CommonUtils.isValidPhoneNumber(messageText)) { processOrder(chatId, messageText); }else if ("\u274C Відмінити".equals(messageText)){ cancelOrder(chatId); }else{ sendWrongNumberMessage(chatId); } } else if (messageText.equals("/start")) { if(!userController.userExists(chatId)) { userController.addUser(chatId); } sendStartMessage(chatId); }else if(messageText.length() == 5 && CommonUtils.isValidProductId(messageText)){ sendProductInfoMessage(chatId, messageText); }else if (messageText.matches("/menu|Меню|меню|Menu|menu|\uD83C\uDF72 Меню")) { sendMenuMessage(chatId); }else if(messageText.equals("\uD83D\uDCB3 Оплатити")){ sendPhoneNumberRequestMessage(chatId); }else if (messageText.matches("/details|\uD83D\uDCDD Деталі страви")&& productController.hasCurrentProduct(chatId)) { sendProductDetailsMessage(chatId); }else{ productController.releaseCurrentProduct(chatId); sendMisunderstandingMessage(chatId); } }else if(update.hasMessage() && update.getMessage().getContact()!=null && orderController.isActiveOrder(chatId)){ String phoneNumber = update.getMessage().getContact().getPhoneNumber(); processOrder(chatId, phoneNumber); }else{ productController.releaseCurrentProduct(chatId); sendMisunderstandingMessage(chatId); } } private void sendTextMessage(String messageText, long chat_id){ SendMessage message = new SendMessage() .setChatId(chat_id) .setText(messageText); try { execute(message); } catch (TelegramApiException e) { e.printStackTrace(); } } private void sendTextMessage(String messageText, long chat_id, ReplyKeyboard keyboardMarkup){ SendMessage message = new SendMessage() .setChatId(chat_id) .setText(messageText); message.setReplyMarkup(keyboardMarkup); try { execute(message); } catch (TelegramApiException e) { e.printStackTrace(); } } private void sendStartMessage(long chatId){ sendTextMessage("Ласкаво просимо до Happy Cherry :)",chatId, MessageBuilder.showButtonText("\uD83C\uDF72 Меню")); //sendTextMessage(MessageBuilder.getGastroPrognosis(),chatId, MessageBuilder.showButtonText("\uD83C\uDF72 Меню")); } private void sendMenuMessage(long chatId){ productController.releaseCurrentProduct(chatId); Collection<Product> products = ProductRepository.getInstance().getProducts().values(); sendTextMessage( MessageBuilder.buildMenuMessage(products), chatId, new ReplyKeyboardRemove()); } private void sendProductPhotoMessage(Product product, long chatId){ String caption = product.getName() + " - " + product.getPrice().intValue() + " грн"; SendPhoto msg = new SendPhoto() .setChatId(chatId) .setPhoto(product.getPicId()) .setCaption(caption); try { sendPhoto(msg); } catch (TelegramApiException e) { e.printStackTrace(); } } private void sendProductInfoMessage(long chatId, String messageText){ Integer productId = CommonUtils.extractProductId(messageText); Product product = productController.holdCurrentProduct(chatId,productId); ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showButtonText("\uD83D\uDCB3 Оплатити"); MessageBuilder.addButton(replyKeyboardMarkup,0,"\uD83D\uDCDD Деталі страви"); MessageBuilder.addRowButton(replyKeyboardMarkup, "\uD83C\uDF72 Меню"); sendProductPhotoMessage(product,chatId); sendTextMessage("Деталі тут \u27A1 /details", chatId, replyKeyboardMarkup); } public void sendDefaultMessage(long chatId, String text){ sendTextMessage(text,chatId, MessageBuilder.showButtonText("\uD83C\uDF72 Меню")); } private void sendMisunderstandingMessage(long chatId){ Collection<Product> products = ProductRepository.getInstance().getProducts().values(); sendTextMessage("Не зрозумів?! Мабуть, хтось дуже голодний.", chatId); sendTextMessage("Сьогодні ми пропонуємо:\n" + MessageBuilder.buildMenuMessage(products),chatId, new ReplyKeyboardRemove()); } private void sendPhoneNumberRequestMessage(long chatId){ orderController.createOrder(chatId, productController.getCurrentProduct(chatId)); productController.releaseCurrentProduct(chatId); ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showPhoneButton(); MessageBuilder.addRowButton(replyKeyboardMarkup,"\u274C Відмінити"); sendTextMessage("Введіть свій номер телефону в форматі +380ХХХХХХХХХ, " + "або натисніть на кнопку 'Надати свій номер телефону':",chatId, replyKeyboardMarkup); } private void processOrder(long chatId, String phoneNumber){ sendDefaultMessage(chatId, MessageBuilder.getAcceptedOrderMessage()); orderController.processOrder(chatId,orderController.getActiveOrder(chatId),phoneNumber); productController.releaseCurrentProduct(chatId); orderController.releaseOrder(chatId); } private void cancelOrder(long chatId){ orderController.releaseOrder(chatId); productController.releaseCurrentProduct(chatId); ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showButtonText("\uD83C\uDF72 Меню"); sendTextMessage( "Оплату відмінено.\n", chatId, replyKeyboardMarkup); } private void sendWrongNumberMessage(long chatId){ ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showPhoneButton(); MessageBuilder.addRowButton(replyKeyboardMarkup,"\u274C Відмінити"); sendTextMessage("Помилка введення.\n" + "Введіть уважно свій номер телефону в форматі +380ХХХХХХХХХ," + " або натисніть на кнопку:",chatId, replyKeyboardMarkup); } private void sendProductDetailsMessage(long chatId){ ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showButtonText("\uD83D\uDCB3 Оплатити"); MessageBuilder.addRowButton(replyKeyboardMarkup, "\uD83C\uDF72 Меню"); sendTextMessage( productController.getCurrentProduct(chatId).getDetails(), chatId, replyKeyboardMarkup); } public String getBotUsername() { return "SmallTalkingBot"; } public String getBotToken() { return "544269816:AAF1lKlnu2Sh-5tmxM-OW4q8KjquwQ4DRMc"; } }
UTF-8
Java
9,423
java
SmallTalkingBot.java
Java
[ { "context": " public String getBotUsername() {\n return \"SmallTalkingBot\";\n }\n\n public String getBotToken() {\n ", "end": 8934, "score": 0.9991344213485718, "start": 8919, "tag": "USERNAME", "value": "SmallTalkingBot" }, { "context": " public String getBotToken() {\n return \"544269816:AAF1lKlnu2Sh-5tmxM-OW4q8KjquwQ4DRMc\";\n }\n}\n", "end": 9039, "score": 0.9685366153717041, "start": 8994, "tag": "KEY", "value": "544269816:AAF1lKlnu2Sh-5tmxM-OW4q8KjquwQ4DRMc" } ]
null
[]
package ua.com.integrity.smalltalkingbot.bot; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.methods.send.SendPhoto; import org.telegram.telegrambots.api.objects.PhotoSize; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardRemove; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.exceptions.TelegramApiException; import ua.com.integrity.smalltalkingbot.controller.NotificationController; import ua.com.integrity.smalltalkingbot.controller.OrderController; import ua.com.integrity.smalltalkingbot.controller.UserController; import ua.com.integrity.smalltalkingbot.message.MessageBuilder; import ua.com.integrity.smalltalkingbot.model.Product; import ua.com.integrity.smalltalkingbot.controller.ProductController; import ua.com.integrity.smalltalkingbot.repository.ProductRepository; import ua.com.integrity.smalltalkingbot.util.CommonUtils; import ua.com.integrity.smalltalkingbot.util.DBUtil; import java.util.Collection; import java.util.Comparator; import java.util.List; public class SmallTalkingBot extends TelegramLongPollingBot { private ProductController productController; private OrderController orderController; private NotificationController notificationController; private UserController userController; public SmallTalkingBot() { this.productController = new ProductController(this); this.orderController = new OrderController(this); this.notificationController = new NotificationController(this); this.userController = new UserController(); DBUtil.getInstance(); } public void onUpdateReceived(Update update) { long chatId = update.getMessage().getChatId(); if (update.hasMessage() && update.getMessage().hasText()) { String messageText = update.getMessage().getText(); if (orderController.isActiveOrder(chatId)){ if (CommonUtils.isValidPhoneNumber(messageText)) { processOrder(chatId, messageText); }else if ("\u274C Відмінити".equals(messageText)){ cancelOrder(chatId); }else{ sendWrongNumberMessage(chatId); } } else if (messageText.equals("/start")) { if(!userController.userExists(chatId)) { userController.addUser(chatId); } sendStartMessage(chatId); }else if(messageText.length() == 5 && CommonUtils.isValidProductId(messageText)){ sendProductInfoMessage(chatId, messageText); }else if (messageText.matches("/menu|Меню|меню|Menu|menu|\uD83C\uDF72 Меню")) { sendMenuMessage(chatId); }else if(messageText.equals("\uD83D\uDCB3 Оплатити")){ sendPhoneNumberRequestMessage(chatId); }else if (messageText.matches("/details|\uD83D\uDCDD Деталі страви")&& productController.hasCurrentProduct(chatId)) { sendProductDetailsMessage(chatId); }else{ productController.releaseCurrentProduct(chatId); sendMisunderstandingMessage(chatId); } }else if(update.hasMessage() && update.getMessage().getContact()!=null && orderController.isActiveOrder(chatId)){ String phoneNumber = update.getMessage().getContact().getPhoneNumber(); processOrder(chatId, phoneNumber); }else{ productController.releaseCurrentProduct(chatId); sendMisunderstandingMessage(chatId); } } private void sendTextMessage(String messageText, long chat_id){ SendMessage message = new SendMessage() .setChatId(chat_id) .setText(messageText); try { execute(message); } catch (TelegramApiException e) { e.printStackTrace(); } } private void sendTextMessage(String messageText, long chat_id, ReplyKeyboard keyboardMarkup){ SendMessage message = new SendMessage() .setChatId(chat_id) .setText(messageText); message.setReplyMarkup(keyboardMarkup); try { execute(message); } catch (TelegramApiException e) { e.printStackTrace(); } } private void sendStartMessage(long chatId){ sendTextMessage("Ласкаво просимо до Happy Cherry :)",chatId, MessageBuilder.showButtonText("\uD83C\uDF72 Меню")); //sendTextMessage(MessageBuilder.getGastroPrognosis(),chatId, MessageBuilder.showButtonText("\uD83C\uDF72 Меню")); } private void sendMenuMessage(long chatId){ productController.releaseCurrentProduct(chatId); Collection<Product> products = ProductRepository.getInstance().getProducts().values(); sendTextMessage( MessageBuilder.buildMenuMessage(products), chatId, new ReplyKeyboardRemove()); } private void sendProductPhotoMessage(Product product, long chatId){ String caption = product.getName() + " - " + product.getPrice().intValue() + " грн"; SendPhoto msg = new SendPhoto() .setChatId(chatId) .setPhoto(product.getPicId()) .setCaption(caption); try { sendPhoto(msg); } catch (TelegramApiException e) { e.printStackTrace(); } } private void sendProductInfoMessage(long chatId, String messageText){ Integer productId = CommonUtils.extractProductId(messageText); Product product = productController.holdCurrentProduct(chatId,productId); ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showButtonText("\uD83D\uDCB3 Оплатити"); MessageBuilder.addButton(replyKeyboardMarkup,0,"\uD83D\uDCDD Деталі страви"); MessageBuilder.addRowButton(replyKeyboardMarkup, "\uD83C\uDF72 Меню"); sendProductPhotoMessage(product,chatId); sendTextMessage("Деталі тут \u27A1 /details", chatId, replyKeyboardMarkup); } public void sendDefaultMessage(long chatId, String text){ sendTextMessage(text,chatId, MessageBuilder.showButtonText("\uD83C\uDF72 Меню")); } private void sendMisunderstandingMessage(long chatId){ Collection<Product> products = ProductRepository.getInstance().getProducts().values(); sendTextMessage("Не зрозумів?! Мабуть, хтось дуже голодний.", chatId); sendTextMessage("Сьогодні ми пропонуємо:\n" + MessageBuilder.buildMenuMessage(products),chatId, new ReplyKeyboardRemove()); } private void sendPhoneNumberRequestMessage(long chatId){ orderController.createOrder(chatId, productController.getCurrentProduct(chatId)); productController.releaseCurrentProduct(chatId); ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showPhoneButton(); MessageBuilder.addRowButton(replyKeyboardMarkup,"\u274C Відмінити"); sendTextMessage("Введіть свій номер телефону в форматі +380ХХХХХХХХХ, " + "або натисніть на кнопку 'Надати свій номер телефону':",chatId, replyKeyboardMarkup); } private void processOrder(long chatId, String phoneNumber){ sendDefaultMessage(chatId, MessageBuilder.getAcceptedOrderMessage()); orderController.processOrder(chatId,orderController.getActiveOrder(chatId),phoneNumber); productController.releaseCurrentProduct(chatId); orderController.releaseOrder(chatId); } private void cancelOrder(long chatId){ orderController.releaseOrder(chatId); productController.releaseCurrentProduct(chatId); ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showButtonText("\uD83C\uDF72 Меню"); sendTextMessage( "Оплату відмінено.\n", chatId, replyKeyboardMarkup); } private void sendWrongNumberMessage(long chatId){ ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showPhoneButton(); MessageBuilder.addRowButton(replyKeyboardMarkup,"\u274C Відмінити"); sendTextMessage("Помилка введення.\n" + "Введіть уважно свій номер телефону в форматі +380ХХХХХХХХХ," + " або натисніть на кнопку:",chatId, replyKeyboardMarkup); } private void sendProductDetailsMessage(long chatId){ ReplyKeyboardMarkup replyKeyboardMarkup = MessageBuilder.showButtonText("\uD83D\uDCB3 Оплатити"); MessageBuilder.addRowButton(replyKeyboardMarkup, "\uD83C\uDF72 Меню"); sendTextMessage( productController.getCurrentProduct(chatId).getDetails(), chatId, replyKeyboardMarkup); } public String getBotUsername() { return "SmallTalkingBot"; } public String getBotToken() { return "<KEY>"; } }
9,383
0.701326
0.692928
202
43.801979
33.254353
131
false
false
0
0
0
0
0
0
0.732673
false
false
7
b994ec7e65cdee616c4b7fd6e995f9e3343648ca
6,786,048,368,872
5b5726ddaf127777681920e50cf360f46f8896d2
/uPet/app/src/main/java/com/example/proyectoupet/model/PaseoSolicitar.java
07ba8d63ac82c9e23c138cd9afb6f429a931758f
[]
no_license
compumovil2020/UPet
https://github.com/compumovil2020/UPet
1bb4a11e19093add14dfd130e546116d9dba37f2
857a5bcdcdc70059d537e7843a7668274e40501c
refs/heads/master
2023-01-27T12:32:46.910000
2020-12-02T11:21:30
2020-12-02T11:21:30
288,046,268
0
0
null
false
2020-12-02T10:08:01
2020-08-17T00:11:32
2020-12-02T08:48:56
2020-12-02T10:08:00
11,862
0
0
0
Java
false
false
package com.example.proyectoupet.model; import java.util.List; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; @Getter @Setter @NoArgsConstructor @Accessors(chain = true) public class PaseoSolicitar { private String idPaseo; private List<MascotaPuntoRecogida> mascotasPuntoRecogida; public PaseoSolicitar(String idPaseo, List<MascotaPuntoRecogida> mascotasPuntoRecogida) { this.idPaseo = idPaseo; this.mascotasPuntoRecogida = mascotasPuntoRecogida; } public String getIdPaseo() { return idPaseo; } public void setIdPaseo(String idPaseo) { this.idPaseo = idPaseo; } public List<MascotaPuntoRecogida> getMascotasPuntoRecogida() { return mascotasPuntoRecogida; } public void setMascotasPuntoRecogida(List<MascotaPuntoRecogida> mascotasPuntoRecogida) { this.mascotasPuntoRecogida = mascotasPuntoRecogida; } }
UTF-8
Java
977
java
PaseoSolicitar.java
Java
[]
null
[]
package com.example.proyectoupet.model; import java.util.List; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; @Getter @Setter @NoArgsConstructor @Accessors(chain = true) public class PaseoSolicitar { private String idPaseo; private List<MascotaPuntoRecogida> mascotasPuntoRecogida; public PaseoSolicitar(String idPaseo, List<MascotaPuntoRecogida> mascotasPuntoRecogida) { this.idPaseo = idPaseo; this.mascotasPuntoRecogida = mascotasPuntoRecogida; } public String getIdPaseo() { return idPaseo; } public void setIdPaseo(String idPaseo) { this.idPaseo = idPaseo; } public List<MascotaPuntoRecogida> getMascotasPuntoRecogida() { return mascotasPuntoRecogida; } public void setMascotasPuntoRecogida(List<MascotaPuntoRecogida> mascotasPuntoRecogida) { this.mascotasPuntoRecogida = mascotasPuntoRecogida; } }
977
0.745138
0.745138
39
24.051283
24.985071
93
false
false
0
0
0
0
0
0
0.384615
false
false
7
a9f19e3aa21a2d51c9f94fb53d7194588b3441a3
13,632,226,257,997
f511062012cd2c84a8a0f45a886fceaaf0c7d534
/src/main/java/com/zking/lq/biz/impl/IProductLQBizImpl.java
0786ff08ff3126250d1799e040d9472bed3517f7
[]
no_license
xiangmiao1998/crm7
https://github.com/xiangmiao1998/crm7
71999166665c5ec81f88aee63d3a16a415463e15
fb8c0d94efe4ef66de22f91c799f29ad3b4ca62c
refs/heads/master
2020-04-07T20:38:56.479000
2018-03-17T06:46:55
2018-03-17T06:46:55
124,229,826
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zking.lq.biz.impl; import com.zking.lq.biz.IProductLQBiz; import com.zking.lq.mapper.ProductLQMapper; import com.zking.lq.model.ProductLQ; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class IProductLQBizImpl implements IProductLQBiz { @Autowired private ProductLQMapper productLQMapper; @Override public ProductLQ loadByprodId(ProductLQ productLQ) { return productLQMapper.selectByPrimaryKey(productLQ.getProdId()); } }
UTF-8
Java
545
java
IProductLQBizImpl.java
Java
[]
null
[]
package com.zking.lq.biz.impl; import com.zking.lq.biz.IProductLQBiz; import com.zking.lq.mapper.ProductLQMapper; import com.zking.lq.model.ProductLQ; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class IProductLQBizImpl implements IProductLQBiz { @Autowired private ProductLQMapper productLQMapper; @Override public ProductLQ loadByprodId(ProductLQ productLQ) { return productLQMapper.selectByPrimaryKey(productLQ.getProdId()); } }
545
0.794495
0.794495
19
27.68421
24.052689
73
false
false
0
0
0
0
0
0
0.421053
false
false
7
da1977ba772ce2736c405ea1bcedce17458a6736
24,318,104,887,415
dd58ccbab5c83db554069083667949619c926d89
/src/main/java/pdp/uz/controller/IncomeController.java
db69df47c97ef1f78f4f0835afdf8b57acd2ad9b
[]
no_license
Erlan01/app-transfer
https://github.com/Erlan01/app-transfer
038243b9aeae3aa89b3136f76556580a962e8e7a
9023bcd8dea453ea77496d531045e60eac6e0cdc
refs/heads/main
2023-08-29T14:23:38.871000
2021-10-04T07:54:15
2021-10-04T07:54:15
412,121,095
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pdp.uz.controller; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import pdp.uz.service.IncomeService; import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/api/income") public class IncomeController { @Autowired IncomeService incomeService; @GetMapping("/get/{id}") ResponseEntity<?> get(@PathVariable Long id, HttpServletRequest request) { return incomeService.get(id, request); } }
UTF-8
Java
802
java
IncomeController.java
Java
[]
null
[]
package pdp.uz.controller; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import pdp.uz.service.IncomeService; import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/api/income") public class IncomeController { @Autowired IncomeService incomeService; @GetMapping("/get/{id}") ResponseEntity<?> get(@PathVariable Long id, HttpServletRequest request) { return incomeService.get(id, request); } }
802
0.802993
0.802993
26
29.846153
24.259323
78
false
false
0
0
0
0
0
0
0.538462
false
false
7
26643c9af2ab9d5612400a1ad6c523464fff2e0a
16,054,587,753,165
c9346208d0768892aa667d7460274c49d95744fb
/src/main/java/com/mycompany/callprocedure/dao/CallProcedureDataAccess.java
f10b861d72fb9178af6a79328372e2ef11b5b22a
[]
no_license
nagaraju01/multidbchecker
https://github.com/nagaraju01/multidbchecker
acd16a82afcbe0d8a9cd43f76920184c4e766fbc
ec8845fb5ab0f4161e922d0130f748e08f65d79b
refs/heads/master
2020-12-31T05:09:45.714000
2016-05-06T06:52:53
2016-05-06T06:52:53
58,161,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* \* Copyright © MyCompany. All Rights Reserved. */ package com.mycompany.callprocedure.dao; import com.mycompany.web.exception.BusinessException; import com.mycompany.web.forms.CallProcedureForm; /** * CallProcedureDataAccess interface * * @author Nagarajut */ public interface CallProcedureDataAccess { Boolean callProcedure(CallProcedureForm request) throws BusinessException; }
UTF-8
Java
397
java
CallProcedureDataAccess.java
Java
[ { "context": " * CallProcedureDataAccess interface\n *\n * @author Nagarajut\n */\npublic interface CallProcedureDataAccess {\n\n\t", "end": 268, "score": 0.9594182968139648, "start": 259, "tag": "NAME", "value": "Nagarajut" } ]
null
[]
/* \* Copyright © MyCompany. All Rights Reserved. */ package com.mycompany.callprocedure.dao; import com.mycompany.web.exception.BusinessException; import com.mycompany.web.forms.CallProcedureForm; /** * CallProcedureDataAccess interface * * @author Nagarajut */ public interface CallProcedureDataAccess { Boolean callProcedure(CallProcedureForm request) throws BusinessException; }
397
0.787879
0.787879
18
21
24.030073
75
false
false
0
0
0
0
0
0
0.277778
false
false
7
d1ec04bf0268657337fce0a4cffb701cd13749c4
712,964,605,434
8ac07c4ec287e48acd1055b1510244c39aa8e98c
/src/com/syntax/class04/Nestedelseif.java
ba0acc9057ea8017f8afdb16e1ace621eac5c965
[]
no_license
fakahrdine/JavaB-automation
https://github.com/fakahrdine/JavaB-automation
05ff3f135aed9aef2d52cf53f69c4e9e29be5f6d
57ce0581c9b34d7d4f8b302c375065b650b09666
refs/heads/master
2021-04-21T18:31:49.450000
2020-04-02T16:57:04
2020-04-02T16:57:04
249,804,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.syntax.class04; public class Nestedelseif { public static void main(String[] args) { // TODO Auto-generated method stub /*if student completed the quiz we will check for score * if scor .90>>greate job * if score >80>>well done * if score >70 -->you could have done better * * if student did not completed the quiz ---.> not good * please do your hommework ontime */ boolean quizcomplet=false ; int score=20; if(quizcomplet) { System.out.println("lets check your your scooor"); if(score>90) { System.out.println("greate job you studied a lot"); }else if(score>70){ System.out.println("well done"); }else if (score>70) { System.out.println("you could have done better"); }else { System.out.println("you failed"); } }else { System.out.println("please do your homework on time"); } } }
UTF-8
Java
907
java
Nestedelseif.java
Java
[]
null
[]
/** * */ package com.syntax.class04; public class Nestedelseif { public static void main(String[] args) { // TODO Auto-generated method stub /*if student completed the quiz we will check for score * if scor .90>>greate job * if score >80>>well done * if score >70 -->you could have done better * * if student did not completed the quiz ---.> not good * please do your hommework ontime */ boolean quizcomplet=false ; int score=20; if(quizcomplet) { System.out.println("lets check your your scooor"); if(score>90) { System.out.println("greate job you studied a lot"); }else if(score>70){ System.out.println("well done"); }else if (score>70) { System.out.println("you could have done better"); }else { System.out.println("you failed"); } }else { System.out.println("please do your homework on time"); } } }
907
0.631753
0.614112
43
20.093023
19.47427
57
false
false
0
0
0
0
0
0
2.116279
false
false
7
298becf7cc5a9cd37a08af4d52fc7c422a2eab8c
4,372,276,750,397
86acb68117850eeef0799ff880efdc7eb1512f62
/src/main/java/br/com/senac/poo/model/Funcionario.java
e41a702eb1c63bf58c3f0be0cd79d3c0d2a262b2
[ "MIT" ]
permissive
PWDA/CaixaMercado
https://github.com/PWDA/CaixaMercado
ebfabfd9fe6ee7711e03474019f6b5e02d13868f
fdac99b6833e969ab295613b2a7df0c70433121f
refs/heads/master
2020-04-05T18:03:18.981000
2018-12-04T00:12:48
2018-12-04T00:12:48
157,087,035
1
0
MIT
false
2018-12-04T00:12:49
2018-11-11T14:23:03
2018-12-03T23:47:33
2018-12-04T00:12:48
6,593
0
0
0
Java
false
null
package br.com.senac.poo.model; import java.util.Date; public class Funcionario extends Pessoa{ private Integer registro; private String cargo; private Integer idLogin; public Funcionario(Integer registro, String cargo, Integer idLogin, Integer id, String nome, String documento, String telefone, Date dataNascimento, String endereco, String bairro, String cidade, String estado, String cep, String email, String sexo, String situacao, int inativo) { super(id, nome, documento, telefone, dataNascimento, endereco, bairro, cidade, estado, cep, email, sexo, situacao, inativo); this.registro = registro; this.cargo = cargo; this.idLogin = idLogin; } public Funcionario() { } public Integer getRegistro() { return registro; } public void setRegistro(Integer registro) { this.registro = registro; } public String getCargo() { return cargo; } public void setCargo(String cargo) { this.cargo = cargo; } public Integer getIdLogin() { return idLogin; } public void setIdLogin(Integer idLogin) { this.idLogin = idLogin; } public void abrirCaixa(){ } public void reporCaixa(){ } public void cancelarVenda(){ } public void aplicarDesconto(){ } }
UTF-8
Java
1,456
java
Funcionario.java
Java
[]
null
[]
package br.com.senac.poo.model; import java.util.Date; public class Funcionario extends Pessoa{ private Integer registro; private String cargo; private Integer idLogin; public Funcionario(Integer registro, String cargo, Integer idLogin, Integer id, String nome, String documento, String telefone, Date dataNascimento, String endereco, String bairro, String cidade, String estado, String cep, String email, String sexo, String situacao, int inativo) { super(id, nome, documento, telefone, dataNascimento, endereco, bairro, cidade, estado, cep, email, sexo, situacao, inativo); this.registro = registro; this.cargo = cargo; this.idLogin = idLogin; } public Funcionario() { } public Integer getRegistro() { return registro; } public void setRegistro(Integer registro) { this.registro = registro; } public String getCargo() { return cargo; } public void setCargo(String cargo) { this.cargo = cargo; } public Integer getIdLogin() { return idLogin; } public void setIdLogin(Integer idLogin) { this.idLogin = idLogin; } public void abrirCaixa(){ } public void reporCaixa(){ } public void cancelarVenda(){ } public void aplicarDesconto(){ } }
1,456
0.600275
0.600275
65
21.4
25.059191
127
false
false
0
0
0
0
0
0
0.676923
false
false
7
039da999c5ea72746b93cb8587a14fbf5c4cda93
11,931,419,200,260
93141239429e90b654f44eb42c6fb33de1ed3dd0
/src/entidades/Marca.java
90a841c5aecd1cb9634c6172db8fc26b0b4d4668
[]
no_license
Franco-Hasper/SisemaSeguros
https://github.com/Franco-Hasper/SisemaSeguros
d1b6a7fa1a0a06bb1b033c44a36fa6360dc092d8
380ebb95a56b0b443c49d0a3fbde85bb9cd88ec8
refs/heads/master
2022-12-28T13:22:53.032000
2020-10-14T01:54:46
2020-10-14T01:54:46
274,511,273
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entidades; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author TELCOM MPC */ @Entity //en la bd tiene este nombre (distinto al de mi clase) @Table(name = "marca") public class Marca { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "nombre") private String nombre; @OneToMany(mappedBy = "marcaId") private List<Modelo> modelos; public Marca() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public List<Modelo> getModelos() { return modelos; } public void setModelos(List<Modelo> modelos) { this.modelos = modelos; } }
UTF-8
Java
1,211
java
Marca.java
Java
[ { "context": "import javax.persistence.Table;\n\n/**\n *\n * @author TELCOM MPC\n */\n@Entity\n//en la bd tiene este nombre (distint", "end": 390, "score": 0.9344896078109741, "start": 380, "tag": "NAME", "value": "TELCOM MPC" } ]
null
[]
package entidades; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author <NAME> */ @Entity //en la bd tiene este nombre (distinto al de mi clase) @Table(name = "marca") public class Marca { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "nombre") private String nombre; @OneToMany(mappedBy = "marcaId") private List<Modelo> modelos; public Marca() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public List<Modelo> getModelos() { return modelos; } public void setModelos(List<Modelo> modelos) { this.modelos = modelos; } }
1,207
0.65896
0.65896
66
17.348484
15.994783
55
false
false
0
0
0
0
0
0
0.30303
false
false
7
2834ea4e9582e335511d69913f8ebbeb4641c019
6,657,199,315,076
bc88938801b0a24067b63b51b38d6683456fad0a
/src/org/commoncrawl/query/QueryResult.java
a6d1aea60cd083958e474cd10d56a52dd069d238
[]
no_license
ssalevan/commoncrawl
https://github.com/ssalevan/commoncrawl
12ed792d5365dc6278a2fa9ea0a4501de0d61225
5f8d26ea992b3fb00bc91b45bf8ca0b9de98bb79
refs/heads/master
2021-01-16T22:04:53.777000
2011-12-11T01:31:09
2011-12-11T01:31:09
2,792,745
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.commoncrawl.query; import java.util.Vector; import org.apache.hadoop.fs.Path; public class QueryResult<KeyType,ValueType> { Vector<QueryResultRecord<KeyType,ValueType>> results = new Vector<QueryResultRecord<KeyType,ValueType>>(); int pageNumber = 0; long totalRecordCount = 0; Path srcFilePath = null; public QueryResult() { results = new Vector<QueryResultRecord<KeyType,ValueType>>(); } public int getPageNumber() { return pageNumber; } public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public long getTotalRecordCount() { return totalRecordCount; } public void setTotalRecordCount(long totalRecordCount) { this.totalRecordCount = totalRecordCount; } public int getResultCount() { return results.size(); } public QueryResultRecord<KeyType,ValueType> getResultAt(int index) { return results.get(index); } public Vector<QueryResultRecord<KeyType,ValueType>> getResults() { return results; } public Path getSrcPath() { return srcFilePath; } public void setSrcPath(Path path) { srcFilePath = path; } }
UTF-8
Java
1,189
java
QueryResult.java
Java
[]
null
[]
package org.commoncrawl.query; import java.util.Vector; import org.apache.hadoop.fs.Path; public class QueryResult<KeyType,ValueType> { Vector<QueryResultRecord<KeyType,ValueType>> results = new Vector<QueryResultRecord<KeyType,ValueType>>(); int pageNumber = 0; long totalRecordCount = 0; Path srcFilePath = null; public QueryResult() { results = new Vector<QueryResultRecord<KeyType,ValueType>>(); } public int getPageNumber() { return pageNumber; } public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public long getTotalRecordCount() { return totalRecordCount; } public void setTotalRecordCount(long totalRecordCount) { this.totalRecordCount = totalRecordCount; } public int getResultCount() { return results.size(); } public QueryResultRecord<KeyType,ValueType> getResultAt(int index) { return results.get(index); } public Vector<QueryResultRecord<KeyType,ValueType>> getResults() { return results; } public Path getSrcPath() { return srcFilePath; } public void setSrcPath(Path path) { srcFilePath = path; } }
1,189
0.689655
0.687973
31
37.354839
34.600529
109
false
false
0
0
0
0
0
0
0.741935
false
false
7
a14cf92c2735bff836341652371f943c080c674b
19,370,302,549,409
63b904315830636060a8254ae2ad1919c6bd9979
/platform-cbb-3.0.1-osm/src/main/java/cn/com/qytx/cbb/org/service/impl/GenerateDataImpl.java
b65ca093035bd9f7fadb73764aea7f59c9d8e154
[]
no_license
anxingg/online-safe-monitor
https://github.com/anxingg/online-safe-monitor
a7f07edf64c11963afd3a376a6ce77e8cfdcf1d5
ab340521bc1a18d82657572eed740ba0356d02d9
refs/heads/master
2021-01-21T10:55:07.980000
2017-04-16T12:59:40
2017-04-16T12:59:40
83,502,219
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.com.qytx.cbb.org.service.impl; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.annotation.Resource; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.qytx.cbb.cache.CacheNameUtil; import cn.com.qytx.cbb.cache.RedisCache; import cn.com.qytx.cbb.file.config.FilePathConfig; import cn.com.qytx.cbb.org.action.mobile.OrgInitAction; import cn.com.qytx.cbb.org.service.GenerateDataService; import cn.com.qytx.cbb.secret.domain.SecretSettings; import cn.com.qytx.cbb.secret.sevice.ISecretSettings; import cn.com.qytx.cbb.util.CalculateUtil; import cn.com.qytx.cbb.util.FileToZip; import cn.com.qytx.platform.base.PlatformException; import cn.com.qytx.platform.org.domain.CompanyInfo; import cn.com.qytx.platform.org.domain.GroupInfo; import cn.com.qytx.platform.org.domain.GroupUser; import cn.com.qytx.platform.org.domain.UserGroup; import cn.com.qytx.platform.org.domain.UserInfo; import cn.com.qytx.platform.org.service.ICompany; import cn.com.qytx.platform.org.service.IGroup; import cn.com.qytx.platform.org.service.IGroupUser; import cn.com.qytx.platform.org.service.IUser; import cn.com.qytx.platform.org.service.IUserGroup; import cn.com.qytx.platform.utils.datetime.DateTimeUtil; import com.google.gson.Gson; /** * 功能: 自动化生成数据文件 版本: 1.0 开发人员: zyf 创建日期: 2015年5月13日 修改日期: 2015年5月13日 修改列表: */ @Service("generateDataService") @Transactional public class GenerateDataImpl implements GenerateDataService { protected final static Logger logger = LoggerFactory.getLogger(GenerateDataImpl.class); @Resource(name = "userService") IUser userService;// 人员接口实现类 @Resource(name = "filePathConfig") private FilePathConfig filePathConfig; @Resource(name = "groupUserService") IGroupUser groupUserService; // 部门人员信息实现类 @Resource(name = "companyService") private ICompany companyService; @Resource(name = "groupService") private IGroup groupService; // 部门/群组管理接口 @Resource(name="userGroupService") private IUserGroup userGroupService; @Resource private ISecretSettings secretSettingsService; /** * 初始化通讯录 * * @param companyId * 单位ID * @param userId * 登陆人员ID * @param dbFilePath * 数据库文件物理路径 * @return */ public Map<String,Object> initContact(Integer companyId, Integer userId, Integer count, String url, String dbFilePath, String dbFileLocalPath) throws Exception { Map<String,Object> result = null; // 得到数据库生成地址,下载地址 if (companyId == null) { throw new PlatformException("单位ID不能为空"); } if (userId == null) { throw new PlatformException("操作人员ID不能为空"); } Long num = userService.count( "companyId=?1 and isDelete=0 and partitionCompanyId=?2 ", companyId, companyId % 10);// 获取单位总人数 if (num < count) { // ret = getInitContact(companyId, userId); result = this.getBasicInfo(companyId, userId, ""); } else { result = getInitContactDBFile(companyId, userId, url, dbFilePath); if (result == null) { result = this.getBasicInfo(companyId, userId, ""); } } return result; } /** * 获取初始化通讯录数据 数据库文件 * * @param companyId * @param userId * @param url * 下载地址 * @param dbFilePath * 共享盘地址 * @return * @throws Exception */ private Map<String,Object> getInitContactDBFile(Integer companyId, Integer userId, String url, String dbFilePath) throws Exception { String file = "/" + companyId + "/" + OrgInitAction.BigData_FileName; File f = new File(dbFilePath + file); if (f.exists()) { url += file; Map map = new HashMap(); map.put("type", 2); map.put("result", url); return map; } else { return null; } } public void generateFileWithTargetCompanyInfo(int companyId, String dbFilePath, String dbFileLocalPath, boolean isNeedClear) { // TODO Auto-generated method stub // 1,判断公司人员是否达到生成标准 Long num = userService.count( "companyId=?1 and isDelete=0 and partitionCompanyId=?2 ", companyId, companyId % 10);// 获取单位总人数 if (num < filePathConfig.getBigDataStand()) { return; } CompanyInfo company = companyService.findOne(companyId); if (company != null) { Date cur = new Date(Calendar.getInstance().getTimeInMillis()); if (!isNeedClear) {// 如果不需要强制清除,则判断是否当日更新过 // 2,如果单位、人员、信息的更新时间超过一天,且存在zip文件,则不生成新文件 Timestamp userLastUpdateDate = userService .getLastUpdateNew(companyId); Timestamp groupLastUpdateDate = groupService .getLastUpdateTime(companyId); long currentTime = cur.getTime(); if ((currentTime - userLastUpdateDate.getTime() >= OrgInitAction.ONE_DAY) || (currentTime - groupLastUpdateDate.getTime() >= OrgInitAction.ONE_DAY)) { if (isExist(companyId)) { return; } } } // 3,生成文件 try { // 本地文件路径 String dbParentLocalPath = dbFileLocalPath + companyId + "/"; // 共享盘路径 String dbParent = dbFilePath + companyId + "/"; // 3.1创建本地文件目录和共享盘文件目录 // 将本地文件删除 FileUtils.deleteDirectory(new File(dbParentLocalPath)); File fileParent = new File(dbParent); File fileParentLocal = new File(dbParentLocalPath); if (!fileParent.exists() && !fileParent.isDirectory()) { fileParent.mkdirs(); } if (!fileParentLocal.exists() && !fileParentLocal.isDirectory()) { fileParentLocal.mkdirs(); } // 3.2 创建临时文件 (在本地文件目录) String dbLocal = dbParentLocalPath + "/" + UUID.randomUUID().toString(); System.out.println(dbLocal); Boolean isOk = createTable(dbLocal, new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(cur));// 创建表 if (isOk) { // 获取人员列表 List<UserInfo> userList = userService .findAll( "companyId=?1 and isDelete=0 and partitionCompanyId=?2 ", companyId, companyId % 10); if (userList != null && userList.size() > 0) { for (UserInfo userInfo : userList) { userInfo.setIsLogined(1); } } // 获取部门人员对应关系 List<GroupUser> groupUserList = groupUserService.findAll( "companyId=?1", companyId); // 获取部门列表 List<GroupInfo> groupList = groupService.findAll( "companyId=?1 and isDelete=0", companyId); // 获取部门下面对应人员数量 Map<Integer, Integer> groupCountMap = groupService .getCompanyGroupCountMap(companyId); if (groupList != null && !groupList.isEmpty()) { addGroupDataToDB(dbLocal, groupList, userList, groupUserList, groupCountMap); } if (userList != null && !userList.isEmpty()) { addUserDataToDB(dbLocal, userList); } // 3.3 压缩文件到共享盘 FileToZip.toZip(dbParentLocalPath, dbParent + "/" + OrgInitAction.BigData_FileName); } } catch (Exception e) { e.printStackTrace(); } } } /** * 判断单位下的文件是否存在,如果不存在,且记录数大于 * * @param companyId * @return */ private boolean isExist(int companyId) { boolean result = false; String fileUploadPath = filePathConfig.getFileUploadPath(); fileUploadPath += OrgInitAction.BigData_PREX + companyId + "/" + OrgInitAction.BigData_FileName; File f = new File(fileUploadPath); if (f.exists() && f.isFile()) { result = true; } return result; } /** * 创建表 * * @param db * 数据库文件 * @return */ private boolean createTable(String db, String updateDate) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite://" + db); stmt = c.createStatement(); // 创建DBUserInfo表 String sql = "CREATE TABLE user_list " + "(id integer primary key autoincrement ," + " sex INT , " + " userId INT, " + " phone VCHAR(20) , " + " groupName VCHAR(200), " + " groupId INT, " + " vNum VCHAR(20), " + " userName VCHAR(200), " + " telephone VCHAR(20), " + " telephone2 VCHAR(200), " + " phone2 VCHAR(200), " + " vgroup VCHAR(200), " + " job VCHAR(200), " + " title VCHAR(200), " + " email VCHAR(200), " + " userPY VCHAR(200), " + " userNum VCHAR(200), " + " userPower INT, " + " signName VCHAR(200), " + " userState INT, " + " role INT, " + " orderIndex INT, " + " action INT, " + " photo VCHAR(200), " + " flg INT, " + " userType INT, " + " isSelected INT, " + " firstName VCHAR(200), " + " personType text," + " recordID INT," + " isVirtual INT," + " isLogined INT," + " linkId INT," + " fullPy VCHAR(200)," + " formattedNumber VCHAR(200)) "; stmt.executeUpdate(sql); // 创建DBGroupInfo实体 sql = "CREATE TABLE group_list " + "(id integer primary key autoincrement," + // "(id INT PRIMARY KEY NOT NULL," + " groupName VCHAR(200), " + " groupId INT, " + " parentId INT, " + " type INT, " + " createUserId INT, " + " unitType INT, " + " userIdstr TEXT, " + " hasecode VCHAR(200), " + " isChecked INT, " + " orderIndex INT, " + " action INT, " + " userCount INT, " + " path VCHAR(200), " + " isAllSelected INT, " + " createGroupMember text" + ",groupUserNum INT," + " grade INT)"; stmt.executeUpdate(sql); // 创建数据库更新时间表 sql = "CREATE TABLE db_update_time " + "(id INT , lastUpdateTime VCHAR(32)) "; stmt.executeUpdate(sql); // 添加默认数据 sql = "insert into db_update_time(id,lastUpdateTime) values (1," + "'" + updateDate + "')"; stmt.executeUpdate(sql); // 创建android_metadata表 sql = "CREATE TABLE android_metadata " + "( locale VCHAR(32)) "; stmt.executeUpdate(sql); // android_metadata添加默认数据 sql = "insert into android_metadata(locale) values (" + "'zh_CN')"; stmt.executeUpdate(sql); stmt.close(); stmt = null; c.close(); c = null; } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 添加部门数据到数据库文件 * * @param db * @param groupList * @return */ private boolean addGroupDataToDB(String db, List<GroupInfo> groupList, List<UserInfo> userList, List<GroupUser> groupUserList, Map<Integer, Integer> groupCountMap) { Connection conn = null; PreparedStatement stmt = null; try { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite://" + db); conn.setAutoCommit(false); int id = 0; Map<Integer, String> deptUserMap = getGroupUserMap(groupUserList);// 获取群组人员id // map Map<Integer, String> groupUserMap = getGroupUserIdstrMap(groupList, userList);// 获取部门人员id map // Map<Integer,String> groupPathMap=new HashMap<Integer, // String>();//部门路径Map // getGroupPaths(groupList,0,groupPathMap); Map<Integer, Integer> groupUserCountMap = getGroupUserCount( groupList, deptUserMap); String sql = "insert into group_list(groupName,groupId,parentId,type,createUserId,unitType,userIdstr,hasecode,isChecked,orderIndex,action,userCount,path,isAllSelected,createGroupMember,groupUserNum,grade) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; stmt = conn.prepareStatement(sql); for (GroupInfo group : groupList) { try { id++; // stmt.setInt(1, id); stmt.setString(1, group.getGroupName()); stmt.setInt(2, group.getGroupId()); stmt.setInt(3, group.getParentId()); stmt.setInt(4, group.getGroupType()); Integer userId = group.getUserId(); if (userId == null) { userId = 0; } stmt.setInt(5, userId); stmt.setInt(6, group.getGroupType()); String userIdStr = ""; if (group.getGroupType().intValue() == GroupInfo.DEPT .intValue()) { userIdStr = groupUserMap.get(group.getGroupId()); } else { userIdStr = deptUserMap.get(group.getGroupId()); } if (userIdStr != null) { if (userIdStr.startsWith(",")) { userIdStr = userIdStr.replaceFirst(",", ""); } if (userIdStr.endsWith(",")) { userIdStr = userIdStr.substring(0, userIdStr.length() - 1); } } else { userIdStr = ""; } stmt.setString(7, userIdStr); stmt.setString(8, "0"); stmt.setInt(9, 0); stmt.setInt( 10, group.getOrderIndex() == null ? 0 : group .getOrderIndex()); stmt.setInt(11, 1); int userCount = 0; // 人数 if (group.getGroupType().intValue() == GroupInfo.DEPT .intValue()) { userCount = groupCountMap.get(group.getGroupId()) == null ? 0 : groupCountMap.get(group.getGroupId()); } else if (groupUserCountMap.get(group.getGroupId()) != null) { userCount = groupUserCountMap.get(group.getGroupId()); } stmt.setInt(12, userCount); // 部门路径 // String groupPath=groupPathMap.get(group.getGroupId()); String groupPath = group.getPath(); if (groupPath != null) { if (groupPath.startsWith(",")) { groupPath = groupPath.replaceFirst(",", ""); ; } if (groupPath.endsWith(",")) { groupPath = groupPath.substring(0, userIdStr.length() - 1); } } else { groupPath = ""; } stmt.setString(13, groupPath); stmt.setString(14, "0"); stmt.setString(15, userId + ""); stmt.setInt(16, userCount); stmt.setInt(17, group.getGrade()==null?0:group.getGrade()); stmt.addBatch(); } catch (Exception ee) { ee.printStackTrace(); } } stmt.executeBatch(); conn.commit(); } catch (Exception e) { e.printStackTrace(); return false; } finally { release(conn, stmt); } return true; } /** * 添加人员信息到数据库文件 * * @return */ private boolean addUserDataToDB(String db, List<UserInfo> userList) { Connection conn = null; PreparedStatement stmt = null; try { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite://" + db); conn.setAutoCommit(false); int id = 0; String sql = "insert into user_list(sex,userId,phone,groupName,groupId,vNum,userName,telephone,telephone2,phone2,vgroup,job,title," + "email,userPY,userNum,userPower,signName,userState,role,orderIndex,action,photo,flg,userType,isSelected,firstName,personType,recordID,isVirtual,isLogined,linkId,fullPy,formattedNumber) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; stmt = conn.prepareStatement(sql); for (UserInfo user : userList) { try { id++; // stmt.setInt(1, id); stmt.setInt(1, user.getSex() == null ? 0 : user.getSex()); stmt.setInt(2, user.getUserId() == null ? 0 : user.getUserId()); stmt.setString(3, user.getPhone() == null ? "" : user.getPhone()); stmt.setString( 4, user.getGroupName() == null ? "" : user .getGroupName()); stmt.setInt(5, user.getGroupId() == null ? 0 : user.getGroupId()); stmt.setString(6, user.getVNum() == null ? "" : user.getVNum()); stmt.setString( 7, user.getUserName() == null ? "" : user .getUserName()); stmt.setString( 8, user.getOfficeTel() == null ? "" : user .getOfficeTel()); stmt.setString(9, user.getHomeTel() == null ? "" : user.getHomeTel()); stmt.setString(10, user.getPhone2() == null ? "" : user.getPhone2()); stmt.setString(11, user.getVGroup() == null ? "" : user.getVGroup()); stmt.setString(12, user.getJob() == null ? "" : user.getJob()); stmt.setString(13, user.getTitle() == null ? "" : user.getTitle()); stmt.setString(14, user.getEmail() == null ? "" : user.getEmail()); stmt.setString(15, user.getPy() == null ? "" : user.getPy()); stmt.setString(16, user.getUserNum() == null ? "" : user.getUserNum()); stmt.setInt( 17, user.getUserPower() == null ? 0 : user .getUserPower()); stmt.setString( 18, user.getSignName() == null ? "" : user .getSignName()); stmt.setInt(19, user.getMobileShowState() == null ? 0 : user.getMobileShowState()); stmt.setInt(20, user.getRole() == null ? 0 : user.getRole()); stmt.setInt( 21, user.getOrderIndex() == null ? 0 : user .getOrderIndex()); stmt.setInt(22, 1);// action stmt.setString(23, user.getPhoto() == null ? "" : user.getPhoto()); stmt.setInt(24, 0);// flag stmt.setInt(25, 1);// userType stmt.setInt(26, 0);// isSelected stmt.setString(27, user.getPy() == null ? "" : user.getPy());// firstName stmt.setInt(28, 0);// personType stmt.setInt(29, 0);// groupUserNum Integer isVirtual = user.getIsVirtual(); if (isVirtual == null) { isVirtual = 0; } stmt.setInt(30, isVirtual); Integer linkId = user.getLinkId(); if (linkId == null) { linkId = 0; } stmt.setInt( 31, user.getIsLogined() == null ? 0 : user .getIsLogined()); stmt.setInt(32, linkId); stmt.setString(33, user.getFullPy() == null ? "" : user.getFullPy()); stmt.setString(34, user.getFormattedNumber() == null ? "" : user.getFormattedNumber()); stmt.addBatch(); } catch (Exception ee) { ee.printStackTrace(); } } stmt.executeBatch(); conn.commit(); } catch (Exception e) { e.printStackTrace(); return false; } finally { release(conn, stmt); } return true; } /** * 释放资源 * * @param conn * @param pstmt */ private void release(Connection conn, PreparedStatement pstmt) { try { if (pstmt != null) { pstmt.close(); } pstmt = null; if (conn != null) { conn.close(); } conn = null; } catch (Exception e) { e.printStackTrace(); } } /** * 获取该部门对应的人员ID * * @param groupUserList * @return */ private Map<Integer, String> getGroupUserMap( final List<GroupUser> groupUserList) { if (groupUserList != null) { Map<Integer, String> map = new HashMap<Integer, String>(); for (GroupUser groupUser : groupUserList) { String ids = ""; if (map.get(groupUser.getGroupId()) != null) { ids += map.get(groupUser.getGroupId()) + "," + groupUser.getUserId(); } else { ids = groupUser.getUserId().toString(); } map.put(groupUser.getGroupId(), ids); } return map; } return null; } /** * 功能:获得部门下面所有人员的str,同getCompanyGroupCountMap * * @param groupList * @param userList * @return */ private Map<Integer, String> getGroupUserIdstrMap( List<GroupInfo> groupList, List<UserInfo> userList) { Map<Integer, String> map = new HashMap<Integer, String>(); for (int i = 0; i < groupList.size(); i++) { GroupInfo g = groupList.get(i); if (g.getGroupType().intValue() == GroupInfo.DEPT) {// 只判断部门 int groupId = g.getGroupId(); StringBuffer sb = new StringBuffer(); for (UserInfo userInfo : userList) {// 初始化部门人员对应关系 if (userInfo.getGroupId().intValue() == groupId) { sb.append(userInfo.getUserId() + ","); } } map.put(groupId, sb.toString()); } } Map<Integer, String> mapStr = map; for (int i = 0; i < groupList.size(); i++) { GroupInfo g = groupList.get(i); if (g.getGroupType().intValue() == GroupInfo.DEPT) {// 只判断部门 int groupId = g.getGroupId(); String path = g.getPath(); if (StringUtils.isNotEmpty(path)) { String[] strs = path.split(","); for (String str : strs) { if (StringUtils.isNotEmpty(str)) { int targetGroupId = Integer.parseInt(str); if (targetGroupId != groupId) { String oldStr = (mapStr.get(targetGroupId) == null ? "" : mapStr.get(targetGroupId).toString()); String incrStr = (map.get(groupId) == null ? "" : map.get(groupId).toString()); mapStr.put(targetGroupId, oldStr + incrStr); } } } } } } Set<Integer> set = new HashSet<Integer>(); set = mapStr.keySet(); for (Integer groupId : set) { map.put(groupId, mapStr.get(groupId)); } return map; } private Map<Integer, Integer> getGroupUserCount(List<GroupInfo> groupList, Map<Integer, String> groupUserMap) { Map<Integer, Integer> groupUserCountMap = new HashMap<Integer, Integer>(); if (null != groupUserMap && !groupUserMap.isEmpty()) { Set<Map.Entry<Integer, String>> set = groupUserMap.entrySet(); Iterator<Map.Entry<Integer, String>> ite = set.iterator(); while (ite.hasNext()) { Map.Entry<Integer, String> entry = ite.next(); CalculateUtil t = new CalculateUtil(); t.getGroupUserCount(entry.getKey(), groupList, groupUserMap); groupUserCountMap.put(entry.getKey(), t.getTotal()); } } return groupUserCountMap; } /* * 变量更新 * @param companyId 单位ID * @param userId 操作人员ID * @param lastUpdateTime 最后更新时间,如果为全量更新,则为空值 * @param isOrg 是否需要群组 0不需要,1需要 */ @Override public Map<String, Object> getBasicInfo(Integer companyId, Integer userId,String lastUpdateTime)throws PlatformException { Date time=null; if(StringUtils.isNotBlank(lastUpdateTime)){ time=DateTimeUtil.stringToDate(lastUpdateTime,"yyyy-MM-dd HH:mm:ss"); } //获取部门和群组的更新数据 List<Map<String,Object>> groupMap = getGroupUpdateInfo(companyId, userId, time); List<Map<String,Object>> userMap = getUserUpdateInfo(companyId, userId, lastUpdateTime); Gson gson =new Gson(); String groupInfo=gson.toJson(groupMap); String userInfo =gson.toJson(userMap); Map<String,Object> map=new HashMap<String, Object>(); map.put("type", 1); map.put("uDate",DateTimeUtil.getCurrentTime()); map.put("groupInfo",groupInfo); map.put("userInfo",userInfo); return map; } /** * 获取部门和群组的更新数据 * @param companyId * @param userId * @param lastUpdateTime * @return */ private List<Map<String,Object>> getGroupUpdateInfo(Integer companyId, Integer userId,Date lastUpdateTime){ List<Map<String,Object>> groupMap=new ArrayList<Map<String, java.lang.Object>>();//部门Map List<GroupInfo> groupList= groupService.getGroupListChanged(companyId,userId,lastUpdateTime); if(groupList!=null && groupList.size()>0){ //得到部门人员Map Map<Integer,Integer> userNumMap=groupService.getCompanyGroupCountMap(companyId); for(GroupInfo group:groupList) { Map<String,Object> map=new HashMap<String, Object>(); map.put("groupId",group.getGroupId()); map.put("groupName",group.getGroupName()); map.put("parentId",group.getParentId()); map.put("unitType",group.getGroupType()); map.put("orderIndex",group.getOrderIndex()); map.put("createUserId",group.getUserId()); //Integer groupUserNum=groupService.getGroupUserAllNum(companyId, group.getGroupId()); Integer userNum=userNumMap.get(group.getGroupId()); if(userNum==null){ userNum=0; } map.put("groupUserNum", userNum.intValue()); map.put("path", group.getPath()); map.put("grade", group.getGrade()); if(group.getIsDelete()==0) { map.put("action",1);//增加 } else if(group.getIsDelete()==1) { map.put("action",3);//删除 } //如果为群组,获取群组人员ID if(group.getGroupType()==4||group.getGroupType()==5) { List<Integer> list= groupUserService.getUserIdsBySetId(companyId,group.getGroupId()); if(list!=null&&list.size()>0) { if(list!=null&&list.size()>0) { map.put("userIds",list); } } } groupMap.add(map); } } return groupMap; } /** * 获取人员的更新数据 * @param companyId * @param userId * @param lastUpdateTime * @return */ private List<Map<String,Object>> getUserUpdateInfo(Integer companyId, Integer userId,String lastUpdateTime){ List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>(); //获取人员数据 List<UserInfo> userList = userService.findUsersByLastUpdateTime(companyId,lastUpdateTime); /**====获得保密设置======**/ List<SecretSettings> listSecretSettings = secretSettingsService.getSettingsByUserAndCompany(companyId,userId); List<UserGroup> ugList = userGroupService.findAllCompanyUserGroup(); if(userList!=null && userList.size()>0){ userMap = formatUserDate(userList, null, listSecretSettings, userId); } return userMap; } /** * 获取基础数据 * @param companyId 单位ID * @param userId 操作人员ID * @param lastUpdateTime 最后更新时间,如果为全量更新,则为空值 * @param infoType 更新类型 按位操作 第0位 部门数据 第1位 人员数据 第2位模板 第3位公用电话本 第4位推荐内容 第5位群组人员对应 * @param isOrg 是否需要群组 0不需要,1需要 * @return */ public Map<String, Object> getBasicInfoFromCache(Integer companyId, Integer userId, String lastUpdateTime) throws Exception { List<Map<String,Object>> groupMap=new ArrayList<Map<String, java.lang.Object>>();//部门Map List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>();//人员Map Date time=null; if(StringUtils.isNotBlank(lastUpdateTime)) { time=DateTimeUtil.stringToDate(lastUpdateTime,"yyyy-MM-dd HH:mm:ss"); } boolean fromCache = false;//是否从缓存中读取数据 RedisCache rc = RedisCache.getInstance(); Gson gson = new Gson(); if (StringUtils.isNotBlank(lastUpdateTime)) { //判断上次更新时间是否在缓存有效期内 if (rc.checkCacheEnable()&&rc.checkTimeInCacheTime(time)) { fromCache = true; } } if(fromCache){ //封装部门数据 groupMap = getGroupUpdateInfo(rc,fromCache,lastUpdateTime,companyId,userId); //封装人员数据 userMap = getUserUpdateInfo(rc,fromCache,lastUpdateTime,companyId,userId); String groupInfo=gson.toJson(groupMap); String userInfo =gson.toJson(userMap); Map<String,Object> map=new HashMap<String, Object>(); map.put("type", 1); map.put("uDate",DateTimeUtil.getCurrentTime()); map.put("groupInfo",groupInfo); map.put("userInfo",userInfo); return map; }else{ return this.getBasicInfo(companyId, userId, lastUpdateTime); } } /** * 得到前天凌晨0点的时间 */ private static String getXXDaysAgo(int days){ String oneHoursAgoTime = ""; try { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, days); oneHoursAgoTime = new SimpleDateFormat("yyyy-MM-dd") .format(c.getTime()); } catch (Exception e) { // TODO: handle exception } return oneHoursAgoTime+" 00:00:00"; } /** * 得到n天后的时间 */ private static Date getXXDaysAgo(Date startTime,int days){ try { Calendar c = Calendar.getInstance(); c.setTime(startTime); c.add(Calendar.DAY_OF_YEAR, days); return c.getTime(); } catch (Exception e) { return null; } } /** * 获得从开始时间到今天的所有日期列表 * @param startTime */ public static List<Date> getTimeList(String startTime){ List<Date> list = new ArrayList<Date>(); try { Date startDate = null; if(StringUtils.isNotBlank(startTime)) { startTime = startTime.substring(0,10) + " 00:00:00"; startDate = DateTimeUtil.stringToDate(startTime,"yyyy-MM-dd HH:mm:ss"); String todayZero = DateTimeUtil.getCurrentTime("yyyy-MM-dd")+" 00:00:00"; Date todayZeroDate = DateTimeUtil.stringToDate(todayZero, "yyyy-MM-dd HH:mm:ss"); int i = 1; while (startDate.getTime()<=todayZeroDate.getTime()) { list.add(startDate); startDate = getXXDaysAgo(startDate,i); } }else { startDate = new Date(); list.add(startDate); } } catch (Exception e) { // TODO: handle exception } return list; } /** * 获得部门变量更新数据 * @param rc * @param fromCache * @param infoType * @param isOrg * @param lastUpdateTime * @param companyId * @param userId * @return */ private List<Map<String,Object>> getGroupUpdateInfo(RedisCache rc,boolean fromCache,String lastUpdateTime,Integer companyId,Integer userId){ List<Map<String,Object>> map = new ArrayList<Map<String,Object>>(); //判断缓存中是否有数据 上次更新时间大于上线时间 并且 大于等于前天零点的时间 List<GroupInfo> groupList = new ArrayList<GroupInfo>(); if(fromCache){ Gson gson = new Gson(); logger.info("************************从缓存服务器中取部门数据******************"); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<GroupInfo>>() {}.getType(); List<Date> list = getTimeList(lastUpdateTime); if (list!=null&&list.size()>0) { for (Date date : list) { String cacheName = CacheNameUtil.createCacheName(companyId, "Group", "getGroupListChanged", date); String caheDate = rc.getDataFromCache(cacheName); if (StringUtils.isNotBlank(caheDate)) { List<GroupInfo> oneDayAgoDate = gson.fromJson(caheDate, type); groupList.addAll(oneDayAgoDate); } } } if(groupList!=null && groupList.size()>0){ //得到部门人员Map Map<Integer,Integer> userNumMap = findGroupUserNum(rc, companyId); //得到群组人员Map Map<Integer, List<Integer>> userIdListMap = findGroupUserList(rc, companyId); //封装部门群组数据格式 map = formatGroupDate(groupList,userNumMap,userIdListMap,companyId,userId); } }else { logger.info("************************从数据库中取部门数据******************"); Date time=null; if(StringUtils.isNotBlank(lastUpdateTime)){ time=DateTimeUtil.stringToDate(lastUpdateTime,"yyyy-MM-dd HH:mm:ss"); } map = this.getGroupUpdateInfo(companyId, userId, time); } return map; } /** * 获得公司下的所有的部门人数对应关系 * @param rc 缓存服务器 * @param companyId * @return */ private Map<Integer,Integer> findGroupUserNum(RedisCache rc,Integer companyId){ //得到部门人员Map Map<Integer,Integer> userNumMap = new HashMap<Integer, Integer>(); Gson gson = new Gson(); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<Integer, Integer>>() {}.getType(); String userNumCacheName = CacheNameUtil.createCacheName(companyId, "Group", "getCompanyGroupCountMap"); String userNumStr = rc.getDataFromCache(userNumCacheName); if (userNumStr==null) {//缓存中没有 userNumMap=groupService.getCompanyGroupCountMap(companyId); String json = gson.toJson(userNumMap); rc.putDataToCache(userNumCacheName, json); }else {//缓存中存在,且正常 userNumMap = gson.fromJson(userNumStr, type); } return userNumMap; } /** * 得到群组人员Map * @param rc 缓存服务器 * @param companyId * @return */ private Map<Integer, List<Integer>> findGroupUserList(RedisCache rc,Integer companyId){ Map<Integer, List<Integer>> userIdListMap = new HashMap<Integer, List<Integer>>() ; Gson gson = new Gson(); java.lang.reflect.Type listtype = new com.google.gson.reflect.TypeToken<Map<Integer, List<Integer>>>() {}.getType(); String userIdListCacheName = CacheNameUtil.createCacheName(companyId, "Group", "getGroupUserIDList"); String userIdListStr = rc.getDataFromCache(userIdListCacheName); if (userIdListStr==null) {//缓存中没有 List<GroupInfo> allGroup = new ArrayList<GroupInfo>(); List<GroupInfo> publicGroup = groupService.getGroupList(companyId, (Integer)4,null,null); if (publicGroup!=null&&publicGroup.size()>0) { allGroup.addAll(publicGroup); } List<GroupInfo> privateGroup = groupService.getGroupList(companyId, (Integer)5,null,null); if (privateGroup!=null&&privateGroup.size()>0) { allGroup.addAll(privateGroup); } if (allGroup!=null&&allGroup.size()>0) { for (GroupInfo groupInfo : allGroup) { List<Integer> userIdList = groupUserService.getUserIdsBySetId(companyId,groupInfo.getGroupId()); userIdListMap.put(groupInfo.getGroupId(), userIdList); } } String json = gson.toJson(userIdListMap); rc.putDataToCache(userIdListCacheName, json); }else {//缓存中有 userIdListMap = gson.fromJson(userIdListStr, listtype); } return userIdListMap; } /** * 封装部门列表为手机端返回时数据格式 * @param groupList 要格式化的部门列表 * @param userNumMap 部门人数map * @param userIdListMap 群组人员id map * @return List<Map<String,Object>> */ private List<Map<String,Object>> formatGroupDate(List<GroupInfo> groupList,Map<Integer, Integer> userNumMap,Map<Integer, List<Integer>> userIdListMap,Integer companyId,Integer userId){ List<Map<String,Object>> groupMap=new ArrayList<Map<String, java.lang.Object>>(); if (groupList!=null&&groupList.size()>0) { for(GroupInfo group:groupList) { Map<String,Object> map=new HashMap<String, Object>(); map.put("groupId",group.getGroupId()); map.put("groupName",group.getGroupName()); map.put("parentId",group.getParentId()); map.put("unitType",group.getGroupType()); map.put("orderIndex",group.getOrderIndex()); map.put("createUserId",group.getUserId()); //Integer groupUserNum=groupService.getGroupUserAllNum(companyId, group.getGroupId()); Integer userNum = 0; if(userNumMap!=null&&group!=null&&group.getGroupId()!=null){ userNum = userNumMap.get(group.getGroupId())==null?0:userNumMap.get(group.getGroupId()); } map.put("groupUserNum", userNum.intValue()); map.put("path", group.getPath()); map.put("grade", group.getGrade()); if(group.getIsDelete()==0) { map.put("action",1);//增加 } else if(group.getIsDelete()==1) { map.put("action",3);//删除 } //如果为群组,获取群组人员ID if(group.getGroupType()==4||group.getGroupType()==5) { //去掉公共群组中部包含自己的群组和非自己创建的群组 if (group.getGroupType()==5) {//个人群组 只返回用户自己创建的群组 if (group.getUserId()!=userId) { continue; } } List<Integer> list= userIdListMap.get(group.getGroupId()); if (group.getGroupType()==4) {//公共群组 只返回包含自己的群组 if (list==null||!list.contains(userId)) { continue; } } if(list!=null&&list.size()>0) { for(int i=0;i<list.size();i++){ UserInfo user = userService.findOne(list.get(i)); if(user==null||user.getIsDelete()==1){ groupUserService.deleteGroupUserByUserIds(list.get(i)+"",group.getGroupType(),companyId); list.remove(i); i--; } } if(list!=null&&list.size()>0) { map.put("userIds",list); } } } groupMap.add(map); } } return groupMap; } /** * 获得人员数据 */ private List<Map<String,Object>> getUserUpdateInfo(RedisCache rc,boolean fromCache,String lastUpdateTime,Integer companyId,Integer userId){ List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>(); Gson gson = new Gson(); List<UserInfo> userList=new ArrayList<UserInfo>();//人员列表 if(fromCache){ logger.info("************************从缓存服务器中取人员变动数据******************"); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<UserInfo>>() {}.getType(); List<Date> list = getTimeList(lastUpdateTime); if (list!=null&&list.size()>0) { for (Date date : list) { String cacheName = CacheNameUtil.createCacheName(companyId, "User", "findUserByLastUpdateTime", date); String caheDate = rc.getDataFromCache(cacheName); if (StringUtils.isNotBlank(caheDate)) { List<UserInfo> oneDayAgoDate = gson.fromJson(caheDate, type); userList.addAll(oneDayAgoDate); } } } //得到管理范围 String userPower = null; Map<String,String> userPowMap = findAllUserPower(rc); if (userPowMap!=null) { if (userPowMap.get(companyId+"_"+userId)!=null) { userPower = userPowMap.get(companyId+"_"+userId); } } List<String> ugPowerList = new ArrayList<String>(); if(StringUtils.isNotBlank(userPower)){ ugPowerList=Arrays.asList(userPower.split(",")); } //获得当前用户的保密设置 List<SecretSettings> listSecretSettings = findMySecretSettings(rc,userId); //封装人员数据格式为手机端返回的数据格式 userMap = formatUserDate(userList,ugPowerList,listSecretSettings,userId); }else { logger.info("************************从数据库中取人员变动数据******************"); userMap = this.getUserUpdateInfo(companyId, userId, lastUpdateTime); } return userMap; } /** * 获得所有的管理范围数据 */ private Map<String,String> findAllUserPower(RedisCache rc){ Map<String,String> userPowMap = new HashMap<String, String>(); Gson gson = new Gson(); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<String, String>>() {}.getType(); String userPowCacheName = CacheNameUtil.createCacheName(-1, "UserGroup", "findAll"); String userPowStr = rc.getDataFromCache(userPowCacheName); if (userPowStr==null) {//缓存中没有 logger.info("************************从数据库中取管理范围数据******************"); List<UserGroup> ugList = userGroupService.findAllCompanyUserGroup(); if (ugList!=null&&ugList.size()>0) { for (UserGroup userGroup : ugList) { String key = userGroup.getCompanyId()+"_"+(userGroup.getUser()==null?-1:userGroup.getUser().getUserId()); String value = userGroup.getGroupPower(); userPowMap.put(key, value); } String json = gson.toJson(userPowMap); rc.putDataToCache(userPowCacheName, json); }else { rc.putDataToCache(userPowCacheName, ""); } }else {//缓存中存在,且正常 logger.info("************************从缓存服务器中取管理范围数据******************"); userPowMap = gson.fromJson(userPowStr, type); } return userPowMap; } private List<SecretSettings> findMySecretSettings(RedisCache rc,Integer userId){ List<SecretSettings> listSecretSettings = new ArrayList<SecretSettings>(); Gson gson = new Gson(); java.lang.reflect.Type secrettype = new com.google.gson.reflect.TypeToken<List<SecretSettings>>() {}.getType(); String secretCacheName = CacheNameUtil.createCacheName(-1, "SecretSettings", "findAll"); String secretCacheStr = rc.getDataFromCache(secretCacheName); if (secretCacheStr==null) {//缓存中没有 logger.info("************************从数据库中取保密设置数据******************"); listSecretSettings = secretSettingsService.findAllCompanySettings(); String json = gson.toJson(listSecretSettings); rc.putDataToCache(secretCacheName, json); }else {//缓存中存在,且正常 logger.info("************************从缓存服务器中取保密设置数据******************"); listSecretSettings = gson.fromJson(secretCacheStr, secrettype); } //筛选包含当前用户的保密设置 if (listSecretSettings!=null&&listSecretSettings.size()>0) { for (int i = 0; i < listSecretSettings.size(); i++) { SecretSettings ss = listSecretSettings.get(i); if (ss.getInvisibleUserIds().indexOf(","+userId+",")==-1) { listSecretSettings.remove(i); i--; } } } return listSecretSettings; } public List<Map<String,Object>> formatUserDate(List<UserInfo> userList,List<String> ugPowerList,List<SecretSettings> listSecretSettings,Integer userId){ List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>(); if(userList!=null && userList.size()>0) { for(UserInfo user:userList) { Map<String,Object> map=new HashMap<String, Object>(); map.put("userId",user.getUserId()); map.put("phone",user.getPhone()); //int groupId=getGroupId(user.getUserId()); map.put("groupId",user.getGroupId()); map.put("userName",user.getUserName()); map.put("sex",user.getSex()); map.put("telephone",user.getOfficeTel()); map.put("telephone2",user.getHomeTel()); map.put("phone2",user.getPhone2()); map.put("job",user.getJob()); map.put("title",user.getTitle()); map.put("email",user.getEmail()); map.put("lastLoginTime",""); if(user.getLastLoginTime()!=null){ map.put("lastLoginTime",user.getLastLoginTime()); } String userPy=user.getPy(); if(userPy!=null){ userPy=userPy.toUpperCase(); } map.put("userPY",userPy); map.put("userNum",user.getUserNum()); map.put("orderIndex",user.getOrderIndex()); map.put("vgroup",user.getvGroup()); map.put("vNum",user.getVNum()); map.put("isVirtual", 0);//是否是虚拟人 map.put("linkId", 0); if(user.getIsVirtual()!=null && user.getIsVirtual().intValue() == 1){ map.put("isVirtual", 1); map.put("linkId", user.getLinkId()); } map.put("userState",user.getMobileShowState()); // //控制手机端该用户是否展示 1,隐藏;0展示,默认0 if(user.getIsDelete()==0) { map.put("action",1);//增加 } else if(user.getIsDelete()==1) { map.put("action",3);//删除 } map.put("userPower",user.getUserPower()); map.put("signName",user.getSignName()); map.put("role",user.getRole()); map.put("photo",user.getPhoto()); map.put("isLogined", user.getIsLogined()); map.put("fullPy",user.getFullPy()==null?"":user.getFullPy()); map.put("formattedNumber",user.getFormattedNumber()==null?"":user.getFormattedNumber()); map.put("property1", "测试字段1"); map.put("property2", "测试字段2"); //保密设置 Boolean hasPower =false; if(user.getGroupId()!=null && ugPowerList!=null){ hasPower=ugPowerList.contains(user.getGroupId().toString()); } if(listSecretSettings!=null && listSecretSettings.size()>0){ if(userId != user.getUserId().intValue() ){//自己的不用保密设置 for(SecretSettings settings: listSecretSettings){ String applyUserIds = settings.getApplyUserIds(); if((applyUserIds.indexOf(","+user.getUserId()+",") >=0 || (user.getLinkId()!=null&&applyUserIds.indexOf(","+user.getLinkId()+",")>=0)) && !hasPower){ String[] arrs= settings.getAttribute().split(","); for(String att:arrs){ if(att.equals("officeTel")){ map.put("telephone",""); }else if(att.equals("homeTel")){ map.put("telephone2",""); }else{ map.put(att, ""); } } } } } } userMap.add(map); } } return userMap; } public static void main(String[] args) { String lastUpdateTime = "2015-05-04 15:52:00"; List<Date> list = getTimeList(lastUpdateTime); for (Date date : list) { System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)); } } }
UTF-8
Java
47,902
java
GenerateDataImpl.java
Java
[ { "context": "gle.gson.Gson;\n\n/**\n * 功能: 自动化生成数据文件 版本: 1.0 开发人员: zyf 创建日期: 2015年5月13日 修改日期: 2015年5月13日 修改列表:\n */\n@Serv", "end": 1925, "score": 0.9996546506881714, "start": 1922, "tag": "USERNAME", "value": "zyf" }, { "context": "user_list(sex,userId,phone,groupName,groupId,vNum,userName,telephone,telephone2,phone2,vgroup,job,title,\"\n\t\t", "end": 14651, "score": 0.9838115572929382, "start": 14643, "tag": "USERNAME", "value": "userName" } ]
null
[]
package cn.com.qytx.cbb.org.service.impl; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.annotation.Resource; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.qytx.cbb.cache.CacheNameUtil; import cn.com.qytx.cbb.cache.RedisCache; import cn.com.qytx.cbb.file.config.FilePathConfig; import cn.com.qytx.cbb.org.action.mobile.OrgInitAction; import cn.com.qytx.cbb.org.service.GenerateDataService; import cn.com.qytx.cbb.secret.domain.SecretSettings; import cn.com.qytx.cbb.secret.sevice.ISecretSettings; import cn.com.qytx.cbb.util.CalculateUtil; import cn.com.qytx.cbb.util.FileToZip; import cn.com.qytx.platform.base.PlatformException; import cn.com.qytx.platform.org.domain.CompanyInfo; import cn.com.qytx.platform.org.domain.GroupInfo; import cn.com.qytx.platform.org.domain.GroupUser; import cn.com.qytx.platform.org.domain.UserGroup; import cn.com.qytx.platform.org.domain.UserInfo; import cn.com.qytx.platform.org.service.ICompany; import cn.com.qytx.platform.org.service.IGroup; import cn.com.qytx.platform.org.service.IGroupUser; import cn.com.qytx.platform.org.service.IUser; import cn.com.qytx.platform.org.service.IUserGroup; import cn.com.qytx.platform.utils.datetime.DateTimeUtil; import com.google.gson.Gson; /** * 功能: 自动化生成数据文件 版本: 1.0 开发人员: zyf 创建日期: 2015年5月13日 修改日期: 2015年5月13日 修改列表: */ @Service("generateDataService") @Transactional public class GenerateDataImpl implements GenerateDataService { protected final static Logger logger = LoggerFactory.getLogger(GenerateDataImpl.class); @Resource(name = "userService") IUser userService;// 人员接口实现类 @Resource(name = "filePathConfig") private FilePathConfig filePathConfig; @Resource(name = "groupUserService") IGroupUser groupUserService; // 部门人员信息实现类 @Resource(name = "companyService") private ICompany companyService; @Resource(name = "groupService") private IGroup groupService; // 部门/群组管理接口 @Resource(name="userGroupService") private IUserGroup userGroupService; @Resource private ISecretSettings secretSettingsService; /** * 初始化通讯录 * * @param companyId * 单位ID * @param userId * 登陆人员ID * @param dbFilePath * 数据库文件物理路径 * @return */ public Map<String,Object> initContact(Integer companyId, Integer userId, Integer count, String url, String dbFilePath, String dbFileLocalPath) throws Exception { Map<String,Object> result = null; // 得到数据库生成地址,下载地址 if (companyId == null) { throw new PlatformException("单位ID不能为空"); } if (userId == null) { throw new PlatformException("操作人员ID不能为空"); } Long num = userService.count( "companyId=?1 and isDelete=0 and partitionCompanyId=?2 ", companyId, companyId % 10);// 获取单位总人数 if (num < count) { // ret = getInitContact(companyId, userId); result = this.getBasicInfo(companyId, userId, ""); } else { result = getInitContactDBFile(companyId, userId, url, dbFilePath); if (result == null) { result = this.getBasicInfo(companyId, userId, ""); } } return result; } /** * 获取初始化通讯录数据 数据库文件 * * @param companyId * @param userId * @param url * 下载地址 * @param dbFilePath * 共享盘地址 * @return * @throws Exception */ private Map<String,Object> getInitContactDBFile(Integer companyId, Integer userId, String url, String dbFilePath) throws Exception { String file = "/" + companyId + "/" + OrgInitAction.BigData_FileName; File f = new File(dbFilePath + file); if (f.exists()) { url += file; Map map = new HashMap(); map.put("type", 2); map.put("result", url); return map; } else { return null; } } public void generateFileWithTargetCompanyInfo(int companyId, String dbFilePath, String dbFileLocalPath, boolean isNeedClear) { // TODO Auto-generated method stub // 1,判断公司人员是否达到生成标准 Long num = userService.count( "companyId=?1 and isDelete=0 and partitionCompanyId=?2 ", companyId, companyId % 10);// 获取单位总人数 if (num < filePathConfig.getBigDataStand()) { return; } CompanyInfo company = companyService.findOne(companyId); if (company != null) { Date cur = new Date(Calendar.getInstance().getTimeInMillis()); if (!isNeedClear) {// 如果不需要强制清除,则判断是否当日更新过 // 2,如果单位、人员、信息的更新时间超过一天,且存在zip文件,则不生成新文件 Timestamp userLastUpdateDate = userService .getLastUpdateNew(companyId); Timestamp groupLastUpdateDate = groupService .getLastUpdateTime(companyId); long currentTime = cur.getTime(); if ((currentTime - userLastUpdateDate.getTime() >= OrgInitAction.ONE_DAY) || (currentTime - groupLastUpdateDate.getTime() >= OrgInitAction.ONE_DAY)) { if (isExist(companyId)) { return; } } } // 3,生成文件 try { // 本地文件路径 String dbParentLocalPath = dbFileLocalPath + companyId + "/"; // 共享盘路径 String dbParent = dbFilePath + companyId + "/"; // 3.1创建本地文件目录和共享盘文件目录 // 将本地文件删除 FileUtils.deleteDirectory(new File(dbParentLocalPath)); File fileParent = new File(dbParent); File fileParentLocal = new File(dbParentLocalPath); if (!fileParent.exists() && !fileParent.isDirectory()) { fileParent.mkdirs(); } if (!fileParentLocal.exists() && !fileParentLocal.isDirectory()) { fileParentLocal.mkdirs(); } // 3.2 创建临时文件 (在本地文件目录) String dbLocal = dbParentLocalPath + "/" + UUID.randomUUID().toString(); System.out.println(dbLocal); Boolean isOk = createTable(dbLocal, new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(cur));// 创建表 if (isOk) { // 获取人员列表 List<UserInfo> userList = userService .findAll( "companyId=?1 and isDelete=0 and partitionCompanyId=?2 ", companyId, companyId % 10); if (userList != null && userList.size() > 0) { for (UserInfo userInfo : userList) { userInfo.setIsLogined(1); } } // 获取部门人员对应关系 List<GroupUser> groupUserList = groupUserService.findAll( "companyId=?1", companyId); // 获取部门列表 List<GroupInfo> groupList = groupService.findAll( "companyId=?1 and isDelete=0", companyId); // 获取部门下面对应人员数量 Map<Integer, Integer> groupCountMap = groupService .getCompanyGroupCountMap(companyId); if (groupList != null && !groupList.isEmpty()) { addGroupDataToDB(dbLocal, groupList, userList, groupUserList, groupCountMap); } if (userList != null && !userList.isEmpty()) { addUserDataToDB(dbLocal, userList); } // 3.3 压缩文件到共享盘 FileToZip.toZip(dbParentLocalPath, dbParent + "/" + OrgInitAction.BigData_FileName); } } catch (Exception e) { e.printStackTrace(); } } } /** * 判断单位下的文件是否存在,如果不存在,且记录数大于 * * @param companyId * @return */ private boolean isExist(int companyId) { boolean result = false; String fileUploadPath = filePathConfig.getFileUploadPath(); fileUploadPath += OrgInitAction.BigData_PREX + companyId + "/" + OrgInitAction.BigData_FileName; File f = new File(fileUploadPath); if (f.exists() && f.isFile()) { result = true; } return result; } /** * 创建表 * * @param db * 数据库文件 * @return */ private boolean createTable(String db, String updateDate) { Connection c = null; Statement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite://" + db); stmt = c.createStatement(); // 创建DBUserInfo表 String sql = "CREATE TABLE user_list " + "(id integer primary key autoincrement ," + " sex INT , " + " userId INT, " + " phone VCHAR(20) , " + " groupName VCHAR(200), " + " groupId INT, " + " vNum VCHAR(20), " + " userName VCHAR(200), " + " telephone VCHAR(20), " + " telephone2 VCHAR(200), " + " phone2 VCHAR(200), " + " vgroup VCHAR(200), " + " job VCHAR(200), " + " title VCHAR(200), " + " email VCHAR(200), " + " userPY VCHAR(200), " + " userNum VCHAR(200), " + " userPower INT, " + " signName VCHAR(200), " + " userState INT, " + " role INT, " + " orderIndex INT, " + " action INT, " + " photo VCHAR(200), " + " flg INT, " + " userType INT, " + " isSelected INT, " + " firstName VCHAR(200), " + " personType text," + " recordID INT," + " isVirtual INT," + " isLogined INT," + " linkId INT," + " fullPy VCHAR(200)," + " formattedNumber VCHAR(200)) "; stmt.executeUpdate(sql); // 创建DBGroupInfo实体 sql = "CREATE TABLE group_list " + "(id integer primary key autoincrement," + // "(id INT PRIMARY KEY NOT NULL," + " groupName VCHAR(200), " + " groupId INT, " + " parentId INT, " + " type INT, " + " createUserId INT, " + " unitType INT, " + " userIdstr TEXT, " + " hasecode VCHAR(200), " + " isChecked INT, " + " orderIndex INT, " + " action INT, " + " userCount INT, " + " path VCHAR(200), " + " isAllSelected INT, " + " createGroupMember text" + ",groupUserNum INT," + " grade INT)"; stmt.executeUpdate(sql); // 创建数据库更新时间表 sql = "CREATE TABLE db_update_time " + "(id INT , lastUpdateTime VCHAR(32)) "; stmt.executeUpdate(sql); // 添加默认数据 sql = "insert into db_update_time(id,lastUpdateTime) values (1," + "'" + updateDate + "')"; stmt.executeUpdate(sql); // 创建android_metadata表 sql = "CREATE TABLE android_metadata " + "( locale VCHAR(32)) "; stmt.executeUpdate(sql); // android_metadata添加默认数据 sql = "insert into android_metadata(locale) values (" + "'zh_CN')"; stmt.executeUpdate(sql); stmt.close(); stmt = null; c.close(); c = null; } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 添加部门数据到数据库文件 * * @param db * @param groupList * @return */ private boolean addGroupDataToDB(String db, List<GroupInfo> groupList, List<UserInfo> userList, List<GroupUser> groupUserList, Map<Integer, Integer> groupCountMap) { Connection conn = null; PreparedStatement stmt = null; try { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite://" + db); conn.setAutoCommit(false); int id = 0; Map<Integer, String> deptUserMap = getGroupUserMap(groupUserList);// 获取群组人员id // map Map<Integer, String> groupUserMap = getGroupUserIdstrMap(groupList, userList);// 获取部门人员id map // Map<Integer,String> groupPathMap=new HashMap<Integer, // String>();//部门路径Map // getGroupPaths(groupList,0,groupPathMap); Map<Integer, Integer> groupUserCountMap = getGroupUserCount( groupList, deptUserMap); String sql = "insert into group_list(groupName,groupId,parentId,type,createUserId,unitType,userIdstr,hasecode,isChecked,orderIndex,action,userCount,path,isAllSelected,createGroupMember,groupUserNum,grade) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; stmt = conn.prepareStatement(sql); for (GroupInfo group : groupList) { try { id++; // stmt.setInt(1, id); stmt.setString(1, group.getGroupName()); stmt.setInt(2, group.getGroupId()); stmt.setInt(3, group.getParentId()); stmt.setInt(4, group.getGroupType()); Integer userId = group.getUserId(); if (userId == null) { userId = 0; } stmt.setInt(5, userId); stmt.setInt(6, group.getGroupType()); String userIdStr = ""; if (group.getGroupType().intValue() == GroupInfo.DEPT .intValue()) { userIdStr = groupUserMap.get(group.getGroupId()); } else { userIdStr = deptUserMap.get(group.getGroupId()); } if (userIdStr != null) { if (userIdStr.startsWith(",")) { userIdStr = userIdStr.replaceFirst(",", ""); } if (userIdStr.endsWith(",")) { userIdStr = userIdStr.substring(0, userIdStr.length() - 1); } } else { userIdStr = ""; } stmt.setString(7, userIdStr); stmt.setString(8, "0"); stmt.setInt(9, 0); stmt.setInt( 10, group.getOrderIndex() == null ? 0 : group .getOrderIndex()); stmt.setInt(11, 1); int userCount = 0; // 人数 if (group.getGroupType().intValue() == GroupInfo.DEPT .intValue()) { userCount = groupCountMap.get(group.getGroupId()) == null ? 0 : groupCountMap.get(group.getGroupId()); } else if (groupUserCountMap.get(group.getGroupId()) != null) { userCount = groupUserCountMap.get(group.getGroupId()); } stmt.setInt(12, userCount); // 部门路径 // String groupPath=groupPathMap.get(group.getGroupId()); String groupPath = group.getPath(); if (groupPath != null) { if (groupPath.startsWith(",")) { groupPath = groupPath.replaceFirst(",", ""); ; } if (groupPath.endsWith(",")) { groupPath = groupPath.substring(0, userIdStr.length() - 1); } } else { groupPath = ""; } stmt.setString(13, groupPath); stmt.setString(14, "0"); stmt.setString(15, userId + ""); stmt.setInt(16, userCount); stmt.setInt(17, group.getGrade()==null?0:group.getGrade()); stmt.addBatch(); } catch (Exception ee) { ee.printStackTrace(); } } stmt.executeBatch(); conn.commit(); } catch (Exception e) { e.printStackTrace(); return false; } finally { release(conn, stmt); } return true; } /** * 添加人员信息到数据库文件 * * @return */ private boolean addUserDataToDB(String db, List<UserInfo> userList) { Connection conn = null; PreparedStatement stmt = null; try { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite://" + db); conn.setAutoCommit(false); int id = 0; String sql = "insert into user_list(sex,userId,phone,groupName,groupId,vNum,userName,telephone,telephone2,phone2,vgroup,job,title," + "email,userPY,userNum,userPower,signName,userState,role,orderIndex,action,photo,flg,userType,isSelected,firstName,personType,recordID,isVirtual,isLogined,linkId,fullPy,formattedNumber) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; stmt = conn.prepareStatement(sql); for (UserInfo user : userList) { try { id++; // stmt.setInt(1, id); stmt.setInt(1, user.getSex() == null ? 0 : user.getSex()); stmt.setInt(2, user.getUserId() == null ? 0 : user.getUserId()); stmt.setString(3, user.getPhone() == null ? "" : user.getPhone()); stmt.setString( 4, user.getGroupName() == null ? "" : user .getGroupName()); stmt.setInt(5, user.getGroupId() == null ? 0 : user.getGroupId()); stmt.setString(6, user.getVNum() == null ? "" : user.getVNum()); stmt.setString( 7, user.getUserName() == null ? "" : user .getUserName()); stmt.setString( 8, user.getOfficeTel() == null ? "" : user .getOfficeTel()); stmt.setString(9, user.getHomeTel() == null ? "" : user.getHomeTel()); stmt.setString(10, user.getPhone2() == null ? "" : user.getPhone2()); stmt.setString(11, user.getVGroup() == null ? "" : user.getVGroup()); stmt.setString(12, user.getJob() == null ? "" : user.getJob()); stmt.setString(13, user.getTitle() == null ? "" : user.getTitle()); stmt.setString(14, user.getEmail() == null ? "" : user.getEmail()); stmt.setString(15, user.getPy() == null ? "" : user.getPy()); stmt.setString(16, user.getUserNum() == null ? "" : user.getUserNum()); stmt.setInt( 17, user.getUserPower() == null ? 0 : user .getUserPower()); stmt.setString( 18, user.getSignName() == null ? "" : user .getSignName()); stmt.setInt(19, user.getMobileShowState() == null ? 0 : user.getMobileShowState()); stmt.setInt(20, user.getRole() == null ? 0 : user.getRole()); stmt.setInt( 21, user.getOrderIndex() == null ? 0 : user .getOrderIndex()); stmt.setInt(22, 1);// action stmt.setString(23, user.getPhoto() == null ? "" : user.getPhoto()); stmt.setInt(24, 0);// flag stmt.setInt(25, 1);// userType stmt.setInt(26, 0);// isSelected stmt.setString(27, user.getPy() == null ? "" : user.getPy());// firstName stmt.setInt(28, 0);// personType stmt.setInt(29, 0);// groupUserNum Integer isVirtual = user.getIsVirtual(); if (isVirtual == null) { isVirtual = 0; } stmt.setInt(30, isVirtual); Integer linkId = user.getLinkId(); if (linkId == null) { linkId = 0; } stmt.setInt( 31, user.getIsLogined() == null ? 0 : user .getIsLogined()); stmt.setInt(32, linkId); stmt.setString(33, user.getFullPy() == null ? "" : user.getFullPy()); stmt.setString(34, user.getFormattedNumber() == null ? "" : user.getFormattedNumber()); stmt.addBatch(); } catch (Exception ee) { ee.printStackTrace(); } } stmt.executeBatch(); conn.commit(); } catch (Exception e) { e.printStackTrace(); return false; } finally { release(conn, stmt); } return true; } /** * 释放资源 * * @param conn * @param pstmt */ private void release(Connection conn, PreparedStatement pstmt) { try { if (pstmt != null) { pstmt.close(); } pstmt = null; if (conn != null) { conn.close(); } conn = null; } catch (Exception e) { e.printStackTrace(); } } /** * 获取该部门对应的人员ID * * @param groupUserList * @return */ private Map<Integer, String> getGroupUserMap( final List<GroupUser> groupUserList) { if (groupUserList != null) { Map<Integer, String> map = new HashMap<Integer, String>(); for (GroupUser groupUser : groupUserList) { String ids = ""; if (map.get(groupUser.getGroupId()) != null) { ids += map.get(groupUser.getGroupId()) + "," + groupUser.getUserId(); } else { ids = groupUser.getUserId().toString(); } map.put(groupUser.getGroupId(), ids); } return map; } return null; } /** * 功能:获得部门下面所有人员的str,同getCompanyGroupCountMap * * @param groupList * @param userList * @return */ private Map<Integer, String> getGroupUserIdstrMap( List<GroupInfo> groupList, List<UserInfo> userList) { Map<Integer, String> map = new HashMap<Integer, String>(); for (int i = 0; i < groupList.size(); i++) { GroupInfo g = groupList.get(i); if (g.getGroupType().intValue() == GroupInfo.DEPT) {// 只判断部门 int groupId = g.getGroupId(); StringBuffer sb = new StringBuffer(); for (UserInfo userInfo : userList) {// 初始化部门人员对应关系 if (userInfo.getGroupId().intValue() == groupId) { sb.append(userInfo.getUserId() + ","); } } map.put(groupId, sb.toString()); } } Map<Integer, String> mapStr = map; for (int i = 0; i < groupList.size(); i++) { GroupInfo g = groupList.get(i); if (g.getGroupType().intValue() == GroupInfo.DEPT) {// 只判断部门 int groupId = g.getGroupId(); String path = g.getPath(); if (StringUtils.isNotEmpty(path)) { String[] strs = path.split(","); for (String str : strs) { if (StringUtils.isNotEmpty(str)) { int targetGroupId = Integer.parseInt(str); if (targetGroupId != groupId) { String oldStr = (mapStr.get(targetGroupId) == null ? "" : mapStr.get(targetGroupId).toString()); String incrStr = (map.get(groupId) == null ? "" : map.get(groupId).toString()); mapStr.put(targetGroupId, oldStr + incrStr); } } } } } } Set<Integer> set = new HashSet<Integer>(); set = mapStr.keySet(); for (Integer groupId : set) { map.put(groupId, mapStr.get(groupId)); } return map; } private Map<Integer, Integer> getGroupUserCount(List<GroupInfo> groupList, Map<Integer, String> groupUserMap) { Map<Integer, Integer> groupUserCountMap = new HashMap<Integer, Integer>(); if (null != groupUserMap && !groupUserMap.isEmpty()) { Set<Map.Entry<Integer, String>> set = groupUserMap.entrySet(); Iterator<Map.Entry<Integer, String>> ite = set.iterator(); while (ite.hasNext()) { Map.Entry<Integer, String> entry = ite.next(); CalculateUtil t = new CalculateUtil(); t.getGroupUserCount(entry.getKey(), groupList, groupUserMap); groupUserCountMap.put(entry.getKey(), t.getTotal()); } } return groupUserCountMap; } /* * 变量更新 * @param companyId 单位ID * @param userId 操作人员ID * @param lastUpdateTime 最后更新时间,如果为全量更新,则为空值 * @param isOrg 是否需要群组 0不需要,1需要 */ @Override public Map<String, Object> getBasicInfo(Integer companyId, Integer userId,String lastUpdateTime)throws PlatformException { Date time=null; if(StringUtils.isNotBlank(lastUpdateTime)){ time=DateTimeUtil.stringToDate(lastUpdateTime,"yyyy-MM-dd HH:mm:ss"); } //获取部门和群组的更新数据 List<Map<String,Object>> groupMap = getGroupUpdateInfo(companyId, userId, time); List<Map<String,Object>> userMap = getUserUpdateInfo(companyId, userId, lastUpdateTime); Gson gson =new Gson(); String groupInfo=gson.toJson(groupMap); String userInfo =gson.toJson(userMap); Map<String,Object> map=new HashMap<String, Object>(); map.put("type", 1); map.put("uDate",DateTimeUtil.getCurrentTime()); map.put("groupInfo",groupInfo); map.put("userInfo",userInfo); return map; } /** * 获取部门和群组的更新数据 * @param companyId * @param userId * @param lastUpdateTime * @return */ private List<Map<String,Object>> getGroupUpdateInfo(Integer companyId, Integer userId,Date lastUpdateTime){ List<Map<String,Object>> groupMap=new ArrayList<Map<String, java.lang.Object>>();//部门Map List<GroupInfo> groupList= groupService.getGroupListChanged(companyId,userId,lastUpdateTime); if(groupList!=null && groupList.size()>0){ //得到部门人员Map Map<Integer,Integer> userNumMap=groupService.getCompanyGroupCountMap(companyId); for(GroupInfo group:groupList) { Map<String,Object> map=new HashMap<String, Object>(); map.put("groupId",group.getGroupId()); map.put("groupName",group.getGroupName()); map.put("parentId",group.getParentId()); map.put("unitType",group.getGroupType()); map.put("orderIndex",group.getOrderIndex()); map.put("createUserId",group.getUserId()); //Integer groupUserNum=groupService.getGroupUserAllNum(companyId, group.getGroupId()); Integer userNum=userNumMap.get(group.getGroupId()); if(userNum==null){ userNum=0; } map.put("groupUserNum", userNum.intValue()); map.put("path", group.getPath()); map.put("grade", group.getGrade()); if(group.getIsDelete()==0) { map.put("action",1);//增加 } else if(group.getIsDelete()==1) { map.put("action",3);//删除 } //如果为群组,获取群组人员ID if(group.getGroupType()==4||group.getGroupType()==5) { List<Integer> list= groupUserService.getUserIdsBySetId(companyId,group.getGroupId()); if(list!=null&&list.size()>0) { if(list!=null&&list.size()>0) { map.put("userIds",list); } } } groupMap.add(map); } } return groupMap; } /** * 获取人员的更新数据 * @param companyId * @param userId * @param lastUpdateTime * @return */ private List<Map<String,Object>> getUserUpdateInfo(Integer companyId, Integer userId,String lastUpdateTime){ List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>(); //获取人员数据 List<UserInfo> userList = userService.findUsersByLastUpdateTime(companyId,lastUpdateTime); /**====获得保密设置======**/ List<SecretSettings> listSecretSettings = secretSettingsService.getSettingsByUserAndCompany(companyId,userId); List<UserGroup> ugList = userGroupService.findAllCompanyUserGroup(); if(userList!=null && userList.size()>0){ userMap = formatUserDate(userList, null, listSecretSettings, userId); } return userMap; } /** * 获取基础数据 * @param companyId 单位ID * @param userId 操作人员ID * @param lastUpdateTime 最后更新时间,如果为全量更新,则为空值 * @param infoType 更新类型 按位操作 第0位 部门数据 第1位 人员数据 第2位模板 第3位公用电话本 第4位推荐内容 第5位群组人员对应 * @param isOrg 是否需要群组 0不需要,1需要 * @return */ public Map<String, Object> getBasicInfoFromCache(Integer companyId, Integer userId, String lastUpdateTime) throws Exception { List<Map<String,Object>> groupMap=new ArrayList<Map<String, java.lang.Object>>();//部门Map List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>();//人员Map Date time=null; if(StringUtils.isNotBlank(lastUpdateTime)) { time=DateTimeUtil.stringToDate(lastUpdateTime,"yyyy-MM-dd HH:mm:ss"); } boolean fromCache = false;//是否从缓存中读取数据 RedisCache rc = RedisCache.getInstance(); Gson gson = new Gson(); if (StringUtils.isNotBlank(lastUpdateTime)) { //判断上次更新时间是否在缓存有效期内 if (rc.checkCacheEnable()&&rc.checkTimeInCacheTime(time)) { fromCache = true; } } if(fromCache){ //封装部门数据 groupMap = getGroupUpdateInfo(rc,fromCache,lastUpdateTime,companyId,userId); //封装人员数据 userMap = getUserUpdateInfo(rc,fromCache,lastUpdateTime,companyId,userId); String groupInfo=gson.toJson(groupMap); String userInfo =gson.toJson(userMap); Map<String,Object> map=new HashMap<String, Object>(); map.put("type", 1); map.put("uDate",DateTimeUtil.getCurrentTime()); map.put("groupInfo",groupInfo); map.put("userInfo",userInfo); return map; }else{ return this.getBasicInfo(companyId, userId, lastUpdateTime); } } /** * 得到前天凌晨0点的时间 */ private static String getXXDaysAgo(int days){ String oneHoursAgoTime = ""; try { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, days); oneHoursAgoTime = new SimpleDateFormat("yyyy-MM-dd") .format(c.getTime()); } catch (Exception e) { // TODO: handle exception } return oneHoursAgoTime+" 00:00:00"; } /** * 得到n天后的时间 */ private static Date getXXDaysAgo(Date startTime,int days){ try { Calendar c = Calendar.getInstance(); c.setTime(startTime); c.add(Calendar.DAY_OF_YEAR, days); return c.getTime(); } catch (Exception e) { return null; } } /** * 获得从开始时间到今天的所有日期列表 * @param startTime */ public static List<Date> getTimeList(String startTime){ List<Date> list = new ArrayList<Date>(); try { Date startDate = null; if(StringUtils.isNotBlank(startTime)) { startTime = startTime.substring(0,10) + " 00:00:00"; startDate = DateTimeUtil.stringToDate(startTime,"yyyy-MM-dd HH:mm:ss"); String todayZero = DateTimeUtil.getCurrentTime("yyyy-MM-dd")+" 00:00:00"; Date todayZeroDate = DateTimeUtil.stringToDate(todayZero, "yyyy-MM-dd HH:mm:ss"); int i = 1; while (startDate.getTime()<=todayZeroDate.getTime()) { list.add(startDate); startDate = getXXDaysAgo(startDate,i); } }else { startDate = new Date(); list.add(startDate); } } catch (Exception e) { // TODO: handle exception } return list; } /** * 获得部门变量更新数据 * @param rc * @param fromCache * @param infoType * @param isOrg * @param lastUpdateTime * @param companyId * @param userId * @return */ private List<Map<String,Object>> getGroupUpdateInfo(RedisCache rc,boolean fromCache,String lastUpdateTime,Integer companyId,Integer userId){ List<Map<String,Object>> map = new ArrayList<Map<String,Object>>(); //判断缓存中是否有数据 上次更新时间大于上线时间 并且 大于等于前天零点的时间 List<GroupInfo> groupList = new ArrayList<GroupInfo>(); if(fromCache){ Gson gson = new Gson(); logger.info("************************从缓存服务器中取部门数据******************"); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<GroupInfo>>() {}.getType(); List<Date> list = getTimeList(lastUpdateTime); if (list!=null&&list.size()>0) { for (Date date : list) { String cacheName = CacheNameUtil.createCacheName(companyId, "Group", "getGroupListChanged", date); String caheDate = rc.getDataFromCache(cacheName); if (StringUtils.isNotBlank(caheDate)) { List<GroupInfo> oneDayAgoDate = gson.fromJson(caheDate, type); groupList.addAll(oneDayAgoDate); } } } if(groupList!=null && groupList.size()>0){ //得到部门人员Map Map<Integer,Integer> userNumMap = findGroupUserNum(rc, companyId); //得到群组人员Map Map<Integer, List<Integer>> userIdListMap = findGroupUserList(rc, companyId); //封装部门群组数据格式 map = formatGroupDate(groupList,userNumMap,userIdListMap,companyId,userId); } }else { logger.info("************************从数据库中取部门数据******************"); Date time=null; if(StringUtils.isNotBlank(lastUpdateTime)){ time=DateTimeUtil.stringToDate(lastUpdateTime,"yyyy-MM-dd HH:mm:ss"); } map = this.getGroupUpdateInfo(companyId, userId, time); } return map; } /** * 获得公司下的所有的部门人数对应关系 * @param rc 缓存服务器 * @param companyId * @return */ private Map<Integer,Integer> findGroupUserNum(RedisCache rc,Integer companyId){ //得到部门人员Map Map<Integer,Integer> userNumMap = new HashMap<Integer, Integer>(); Gson gson = new Gson(); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<Integer, Integer>>() {}.getType(); String userNumCacheName = CacheNameUtil.createCacheName(companyId, "Group", "getCompanyGroupCountMap"); String userNumStr = rc.getDataFromCache(userNumCacheName); if (userNumStr==null) {//缓存中没有 userNumMap=groupService.getCompanyGroupCountMap(companyId); String json = gson.toJson(userNumMap); rc.putDataToCache(userNumCacheName, json); }else {//缓存中存在,且正常 userNumMap = gson.fromJson(userNumStr, type); } return userNumMap; } /** * 得到群组人员Map * @param rc 缓存服务器 * @param companyId * @return */ private Map<Integer, List<Integer>> findGroupUserList(RedisCache rc,Integer companyId){ Map<Integer, List<Integer>> userIdListMap = new HashMap<Integer, List<Integer>>() ; Gson gson = new Gson(); java.lang.reflect.Type listtype = new com.google.gson.reflect.TypeToken<Map<Integer, List<Integer>>>() {}.getType(); String userIdListCacheName = CacheNameUtil.createCacheName(companyId, "Group", "getGroupUserIDList"); String userIdListStr = rc.getDataFromCache(userIdListCacheName); if (userIdListStr==null) {//缓存中没有 List<GroupInfo> allGroup = new ArrayList<GroupInfo>(); List<GroupInfo> publicGroup = groupService.getGroupList(companyId, (Integer)4,null,null); if (publicGroup!=null&&publicGroup.size()>0) { allGroup.addAll(publicGroup); } List<GroupInfo> privateGroup = groupService.getGroupList(companyId, (Integer)5,null,null); if (privateGroup!=null&&privateGroup.size()>0) { allGroup.addAll(privateGroup); } if (allGroup!=null&&allGroup.size()>0) { for (GroupInfo groupInfo : allGroup) { List<Integer> userIdList = groupUserService.getUserIdsBySetId(companyId,groupInfo.getGroupId()); userIdListMap.put(groupInfo.getGroupId(), userIdList); } } String json = gson.toJson(userIdListMap); rc.putDataToCache(userIdListCacheName, json); }else {//缓存中有 userIdListMap = gson.fromJson(userIdListStr, listtype); } return userIdListMap; } /** * 封装部门列表为手机端返回时数据格式 * @param groupList 要格式化的部门列表 * @param userNumMap 部门人数map * @param userIdListMap 群组人员id map * @return List<Map<String,Object>> */ private List<Map<String,Object>> formatGroupDate(List<GroupInfo> groupList,Map<Integer, Integer> userNumMap,Map<Integer, List<Integer>> userIdListMap,Integer companyId,Integer userId){ List<Map<String,Object>> groupMap=new ArrayList<Map<String, java.lang.Object>>(); if (groupList!=null&&groupList.size()>0) { for(GroupInfo group:groupList) { Map<String,Object> map=new HashMap<String, Object>(); map.put("groupId",group.getGroupId()); map.put("groupName",group.getGroupName()); map.put("parentId",group.getParentId()); map.put("unitType",group.getGroupType()); map.put("orderIndex",group.getOrderIndex()); map.put("createUserId",group.getUserId()); //Integer groupUserNum=groupService.getGroupUserAllNum(companyId, group.getGroupId()); Integer userNum = 0; if(userNumMap!=null&&group!=null&&group.getGroupId()!=null){ userNum = userNumMap.get(group.getGroupId())==null?0:userNumMap.get(group.getGroupId()); } map.put("groupUserNum", userNum.intValue()); map.put("path", group.getPath()); map.put("grade", group.getGrade()); if(group.getIsDelete()==0) { map.put("action",1);//增加 } else if(group.getIsDelete()==1) { map.put("action",3);//删除 } //如果为群组,获取群组人员ID if(group.getGroupType()==4||group.getGroupType()==5) { //去掉公共群组中部包含自己的群组和非自己创建的群组 if (group.getGroupType()==5) {//个人群组 只返回用户自己创建的群组 if (group.getUserId()!=userId) { continue; } } List<Integer> list= userIdListMap.get(group.getGroupId()); if (group.getGroupType()==4) {//公共群组 只返回包含自己的群组 if (list==null||!list.contains(userId)) { continue; } } if(list!=null&&list.size()>0) { for(int i=0;i<list.size();i++){ UserInfo user = userService.findOne(list.get(i)); if(user==null||user.getIsDelete()==1){ groupUserService.deleteGroupUserByUserIds(list.get(i)+"",group.getGroupType(),companyId); list.remove(i); i--; } } if(list!=null&&list.size()>0) { map.put("userIds",list); } } } groupMap.add(map); } } return groupMap; } /** * 获得人员数据 */ private List<Map<String,Object>> getUserUpdateInfo(RedisCache rc,boolean fromCache,String lastUpdateTime,Integer companyId,Integer userId){ List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>(); Gson gson = new Gson(); List<UserInfo> userList=new ArrayList<UserInfo>();//人员列表 if(fromCache){ logger.info("************************从缓存服务器中取人员变动数据******************"); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<UserInfo>>() {}.getType(); List<Date> list = getTimeList(lastUpdateTime); if (list!=null&&list.size()>0) { for (Date date : list) { String cacheName = CacheNameUtil.createCacheName(companyId, "User", "findUserByLastUpdateTime", date); String caheDate = rc.getDataFromCache(cacheName); if (StringUtils.isNotBlank(caheDate)) { List<UserInfo> oneDayAgoDate = gson.fromJson(caheDate, type); userList.addAll(oneDayAgoDate); } } } //得到管理范围 String userPower = null; Map<String,String> userPowMap = findAllUserPower(rc); if (userPowMap!=null) { if (userPowMap.get(companyId+"_"+userId)!=null) { userPower = userPowMap.get(companyId+"_"+userId); } } List<String> ugPowerList = new ArrayList<String>(); if(StringUtils.isNotBlank(userPower)){ ugPowerList=Arrays.asList(userPower.split(",")); } //获得当前用户的保密设置 List<SecretSettings> listSecretSettings = findMySecretSettings(rc,userId); //封装人员数据格式为手机端返回的数据格式 userMap = formatUserDate(userList,ugPowerList,listSecretSettings,userId); }else { logger.info("************************从数据库中取人员变动数据******************"); userMap = this.getUserUpdateInfo(companyId, userId, lastUpdateTime); } return userMap; } /** * 获得所有的管理范围数据 */ private Map<String,String> findAllUserPower(RedisCache rc){ Map<String,String> userPowMap = new HashMap<String, String>(); Gson gson = new Gson(); java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<String, String>>() {}.getType(); String userPowCacheName = CacheNameUtil.createCacheName(-1, "UserGroup", "findAll"); String userPowStr = rc.getDataFromCache(userPowCacheName); if (userPowStr==null) {//缓存中没有 logger.info("************************从数据库中取管理范围数据******************"); List<UserGroup> ugList = userGroupService.findAllCompanyUserGroup(); if (ugList!=null&&ugList.size()>0) { for (UserGroup userGroup : ugList) { String key = userGroup.getCompanyId()+"_"+(userGroup.getUser()==null?-1:userGroup.getUser().getUserId()); String value = userGroup.getGroupPower(); userPowMap.put(key, value); } String json = gson.toJson(userPowMap); rc.putDataToCache(userPowCacheName, json); }else { rc.putDataToCache(userPowCacheName, ""); } }else {//缓存中存在,且正常 logger.info("************************从缓存服务器中取管理范围数据******************"); userPowMap = gson.fromJson(userPowStr, type); } return userPowMap; } private List<SecretSettings> findMySecretSettings(RedisCache rc,Integer userId){ List<SecretSettings> listSecretSettings = new ArrayList<SecretSettings>(); Gson gson = new Gson(); java.lang.reflect.Type secrettype = new com.google.gson.reflect.TypeToken<List<SecretSettings>>() {}.getType(); String secretCacheName = CacheNameUtil.createCacheName(-1, "SecretSettings", "findAll"); String secretCacheStr = rc.getDataFromCache(secretCacheName); if (secretCacheStr==null) {//缓存中没有 logger.info("************************从数据库中取保密设置数据******************"); listSecretSettings = secretSettingsService.findAllCompanySettings(); String json = gson.toJson(listSecretSettings); rc.putDataToCache(secretCacheName, json); }else {//缓存中存在,且正常 logger.info("************************从缓存服务器中取保密设置数据******************"); listSecretSettings = gson.fromJson(secretCacheStr, secrettype); } //筛选包含当前用户的保密设置 if (listSecretSettings!=null&&listSecretSettings.size()>0) { for (int i = 0; i < listSecretSettings.size(); i++) { SecretSettings ss = listSecretSettings.get(i); if (ss.getInvisibleUserIds().indexOf(","+userId+",")==-1) { listSecretSettings.remove(i); i--; } } } return listSecretSettings; } public List<Map<String,Object>> formatUserDate(List<UserInfo> userList,List<String> ugPowerList,List<SecretSettings> listSecretSettings,Integer userId){ List<Map<String,Object>> userMap=new ArrayList<Map<String, java.lang.Object>>(); if(userList!=null && userList.size()>0) { for(UserInfo user:userList) { Map<String,Object> map=new HashMap<String, Object>(); map.put("userId",user.getUserId()); map.put("phone",user.getPhone()); //int groupId=getGroupId(user.getUserId()); map.put("groupId",user.getGroupId()); map.put("userName",user.getUserName()); map.put("sex",user.getSex()); map.put("telephone",user.getOfficeTel()); map.put("telephone2",user.getHomeTel()); map.put("phone2",user.getPhone2()); map.put("job",user.getJob()); map.put("title",user.getTitle()); map.put("email",user.getEmail()); map.put("lastLoginTime",""); if(user.getLastLoginTime()!=null){ map.put("lastLoginTime",user.getLastLoginTime()); } String userPy=user.getPy(); if(userPy!=null){ userPy=userPy.toUpperCase(); } map.put("userPY",userPy); map.put("userNum",user.getUserNum()); map.put("orderIndex",user.getOrderIndex()); map.put("vgroup",user.getvGroup()); map.put("vNum",user.getVNum()); map.put("isVirtual", 0);//是否是虚拟人 map.put("linkId", 0); if(user.getIsVirtual()!=null && user.getIsVirtual().intValue() == 1){ map.put("isVirtual", 1); map.put("linkId", user.getLinkId()); } map.put("userState",user.getMobileShowState()); // //控制手机端该用户是否展示 1,隐藏;0展示,默认0 if(user.getIsDelete()==0) { map.put("action",1);//增加 } else if(user.getIsDelete()==1) { map.put("action",3);//删除 } map.put("userPower",user.getUserPower()); map.put("signName",user.getSignName()); map.put("role",user.getRole()); map.put("photo",user.getPhoto()); map.put("isLogined", user.getIsLogined()); map.put("fullPy",user.getFullPy()==null?"":user.getFullPy()); map.put("formattedNumber",user.getFormattedNumber()==null?"":user.getFormattedNumber()); map.put("property1", "测试字段1"); map.put("property2", "测试字段2"); //保密设置 Boolean hasPower =false; if(user.getGroupId()!=null && ugPowerList!=null){ hasPower=ugPowerList.contains(user.getGroupId().toString()); } if(listSecretSettings!=null && listSecretSettings.size()>0){ if(userId != user.getUserId().intValue() ){//自己的不用保密设置 for(SecretSettings settings: listSecretSettings){ String applyUserIds = settings.getApplyUserIds(); if((applyUserIds.indexOf(","+user.getUserId()+",") >=0 || (user.getLinkId()!=null&&applyUserIds.indexOf(","+user.getLinkId()+",")>=0)) && !hasPower){ String[] arrs= settings.getAttribute().split(","); for(String att:arrs){ if(att.equals("officeTel")){ map.put("telephone",""); }else if(att.equals("homeTel")){ map.put("telephone2",""); }else{ map.put(att, ""); } } } } } } userMap.add(map); } } return userMap; } public static void main(String[] args) { String lastUpdateTime = "2015-05-04 15:52:00"; List<Date> list = getTimeList(lastUpdateTime); for (Date date : list) { System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)); } } }
47,902
0.594165
0.586399
1,281
34.481655
27.679325
270
false
false
0
0
0
0
0
0
3.145199
false
false
7
e328b3c2eea8880d78395fea10fd92530a941c5a
1,340,029,824,466
732336ca5eea6dd1c3021cb74da0345a9dbdb141
/Arraylist/ArrayListSortExample.java
8344f36351b612e5faf860da6edd7ba8e18437c3
[]
no_license
phamvantrung14/java
https://github.com/phamvantrung14/java
cb8ac040cee1e2b049e0a64fe2f4e67d88281989
9398cd6f657a94a2ebd60dbe99d1c3643c271af5
refs/heads/master
2020-12-03T06:23:12.870000
2020-01-08T02:10:27
2020-01-08T02:10:27
231,229,056
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 arrayslist; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * * @author asuspc */ public class ArrayListSortExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Lisa"); names.add("Jennifer"); names.add("Mark"); names.add("David"); System.out.println("Names: "+names); //sort an ArrayList using sort() method. You must pass a Comarator the arraylist.sort() method. names.sort(new Comparator<String>(){ @Override public int compare(String name1, String name2){ return name1.compareTo(name2); } }); //the above sort() method call can also be written simply using lambda expression names.sort(Comparator.naturalOrder()); System.out.println("Sorted Names : "+names); } }
UTF-8
Java
1,229
java
ArrayListSortExample.java
Java
[ { "context": "parator;\nimport java.util.List;\n\n/**\n *\n * @author asuspc\n */\npublic class ArrayListSortExample {\n publi", "end": 311, "score": 0.9996464252471924, "start": 305, "tag": "USERNAME", "value": "asuspc" }, { "context": "ng> names = new ArrayList<>();\n names.add(\"Lisa\");\n names.add(\"Jennifer\");\n names.a", "end": 468, "score": 0.9993915557861328, "start": 464, "tag": "NAME", "value": "Lisa" }, { "context": "();\n names.add(\"Lisa\");\n names.add(\"Jennifer\");\n names.add(\"Mark\");\n names.add(\"", "end": 499, "score": 0.9994287490844727, "start": 491, "tag": "NAME", "value": "Jennifer" }, { "context": " names.add(\"Jennifer\");\n names.add(\"Mark\");\n names.add(\"David\");\n \n S", "end": 526, "score": 0.9998554587364197, "start": 522, "tag": "NAME", "value": "Mark" }, { "context": "\");\n names.add(\"Mark\");\n names.add(\"David\");\n \n System.out.println(\"Names: \"+", "end": 554, "score": 0.9998520016670227, "start": 549, "tag": "NAME", "value": "David" } ]
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 arrayslist; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * * @author asuspc */ public class ArrayListSortExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Lisa"); names.add("Jennifer"); names.add("Mark"); names.add("David"); System.out.println("Names: "+names); //sort an ArrayList using sort() method. You must pass a Comarator the arraylist.sort() method. names.sort(new Comparator<String>(){ @Override public int compare(String name1, String name2){ return name1.compareTo(name2); } }); //the above sort() method call can also be written simply using lambda expression names.sort(Comparator.naturalOrder()); System.out.println("Sorted Names : "+names); } }
1,229
0.567941
0.564687
39
30.512821
26.572466
103
false
false
0
0
0
0
0
0
0.461538
false
false
7
8ffb6d2d626aa61ded1f7cd9461f1de48b5a5a77
24,421,184,053,700
aa50271ac891663cd5607f4536a3d8b71882057f
/Java/src/Simple/Login.java
25025cdd2ac71dd5700f7e68b4492c03b2d0faf1
[]
no_license
gvoicu/coders_ranking
https://github.com/gvoicu/coders_ranking
857526ad152f347c1069df3208f2496dfba94407
8943af25360e1e5028d8ec0438b2f1ae1c0c923b
refs/heads/master
2020-05-17T13:57:58.545000
2013-01-22T09:13:15
2013-01-22T09:13:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Simple; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; public class Login extends HttpServlet { private static final long serialVersionUID = 1L; Statement st, st2, stBanned,st3; Connection con; String query; String parola; String username; ResultSet rs, rsBanned, rsTime,rs2; PreparedStatement ps; String sql = "SELECT CURTIME()"; String crt; public Login() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/coders_ranking", "root", ""); st = con.createStatement(); stBanned = con.createStatement(); st2 = con.createStatement(); st3 = con.createStatement(); ps = con.prepareStatement(sql); rsTime = ps.executeQuery(); username = request.getParameter("user"); query = "SELECT * FROM `user` WHERE `email`='"+ username +"'"+" AND `id`>2"; parola = (String) request.getParameter("password"); parola = Encryption.crypt(parola); rs = st.executeQuery(query); query = "SELECT * FROM `banned_users`"; rsBanned = stBanned.executeQuery(query); if (rs.next()) { while (rsBanned.next()) { if(username.equals(rsBanned.getString("email"))) { while (rsTime.next()) { crt = rsTime.getString(1); query = "SELECT * FROM `banned_users` WHERE (SUBTIME(CURTIME(),`time`)>'00:15:00' OR CURTIME()<`time`)" + " AND `email`='"+username+"'"; rs2 = st3.executeQuery(query); if (rs2.next()) { query = "DELETE FROM `banned_users` WHERE `email` = '" + username +"'"; st2.executeUpdate(query); if (rs.getString("password_hash").equals(parola)) { request.getRequestDispatcher("user_profile.jsp").forward(request, response); return; } else { request.getRequestDispatcher("index.jsp").forward(request, response); return; } } else { request.getRequestDispatcher("index.jsp").forward(request, response); return; } } } } if (rs.getString("password_hash").equals(parola)) { request.getRequestDispatcher("user_profile.jsp").forward(request, response); } else { request.getRequestDispatcher("index.jsp").forward(request, response); } } else { request.getRequestDispatcher("index.jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter p=response.getWriter(); p.println("Success!"); doGet(request,response); } }
UTF-8
Java
3,863
java
Login.java
Java
[ { "context": " if (rs.getString(\"password_hash\").equals(parola)) {\n request.g", "end": 2371, "score": 0.9899107217788696, "start": 2365, "tag": "PASSWORD", "value": "parola" }, { "context": " if (rs.getString(\"password_hash\").equals(parola)) {\n request.getRequestDispatc", "end": 3157, "score": 0.9627465009689331, "start": 3151, "tag": "PASSWORD", "value": "parola" } ]
null
[]
package Simple; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; public class Login extends HttpServlet { private static final long serialVersionUID = 1L; Statement st, st2, stBanned,st3; Connection con; String query; String parola; String username; ResultSet rs, rsBanned, rsTime,rs2; PreparedStatement ps; String sql = "SELECT CURTIME()"; String crt; public Login() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/coders_ranking", "root", ""); st = con.createStatement(); stBanned = con.createStatement(); st2 = con.createStatement(); st3 = con.createStatement(); ps = con.prepareStatement(sql); rsTime = ps.executeQuery(); username = request.getParameter("user"); query = "SELECT * FROM `user` WHERE `email`='"+ username +"'"+" AND `id`>2"; parola = (String) request.getParameter("password"); parola = Encryption.crypt(parola); rs = st.executeQuery(query); query = "SELECT * FROM `banned_users`"; rsBanned = stBanned.executeQuery(query); if (rs.next()) { while (rsBanned.next()) { if(username.equals(rsBanned.getString("email"))) { while (rsTime.next()) { crt = rsTime.getString(1); query = "SELECT * FROM `banned_users` WHERE (SUBTIME(CURTIME(),`time`)>'00:15:00' OR CURTIME()<`time`)" + " AND `email`='"+username+"'"; rs2 = st3.executeQuery(query); if (rs2.next()) { query = "DELETE FROM `banned_users` WHERE `email` = '" + username +"'"; st2.executeUpdate(query); if (rs.getString("password_hash").equals(<PASSWORD>)) { request.getRequestDispatcher("user_profile.jsp").forward(request, response); return; } else { request.getRequestDispatcher("index.jsp").forward(request, response); return; } } else { request.getRequestDispatcher("index.jsp").forward(request, response); return; } } } } if (rs.getString("password_hash").equals(<PASSWORD>)) { request.getRequestDispatcher("user_profile.jsp").forward(request, response); } else { request.getRequestDispatcher("index.jsp").forward(request, response); } } else { request.getRequestDispatcher("index.jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter p=response.getWriter(); p.println("Success!"); doGet(request,response); } }
3,871
0.505825
0.501165
95
39.663158
30.864256
133
false
false
0
0
0
0
0
0
0.757895
false
false
7
164a583fb83f1d6a3e2848b9291434257d55f01a
1,108,101,574,530
0d7aae77cc8b7c2b91d9df3af07c3d7637ce6820
/controllers/ExpenditureAddController.java
6053f81766f531c2d91a5b219deba91f51f867a7
[]
no_license
ponostech/restaurant-app
https://github.com/ponostech/restaurant-app
dbcd7d9e9fd8470a486f2067423e56d6ccbb1c64
b5d8f6ca3d0825cdfa0116bf0b4bb9ed23540062
refs/heads/master
2021-01-18T05:11:47.808000
2017-03-15T15:09:07
2017-03-15T15:09:07
84,278,206
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package restaurant.controllers; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ResourceBundle; import java.util.StringJoiner; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXDatePicker; import com.jfoenix.controls.JFXTextField; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.stage.Stage; import javafx.util.StringConverter; import restaurant.dao.ExpenditureDAO; import restaurant.helpers.Message; import restaurant.helpers.PopupHelper; import restaurant.helpers.ScreenManager; import restaurant.models.Expenditure; public class ExpenditureAddController implements Initializable { @FXML private JFXTextField descText; @FXML private JFXTextField amountText; @FXML private JFXDatePicker dateSelect; @FXML private JFXButton saveButton; @FXML private JFXButton cancelButton; private Executor executor; private ExpenditureDAO expenditureDAO = new ExpenditureDAO(); private PopupHelper ph = new PopupHelper(); private String dateFormat = "dd/MM/yyyy"; private StringConverter<LocalDate> converter; @Override public void initialize(URL location, ResourceBundle resources) { executor = Executors.newCachedThreadPool(runnable -> { Thread t = new Thread(runnable); t.setDaemon(true); return t; }); dateSelect.setValue(LocalDate.now()); converter = new StringConverter<LocalDate>() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat); @Override public LocalDate fromString(String string) { if (string != null && !string.isEmpty()) { return LocalDate.parse(string, formatter); } else { return null; } } @Override public String toString(LocalDate date) { if (date != null) { return formatter.format(date); } else { return ""; } } }; dateSelect.setConverter(converter); } @FXML public void saveAction() throws NoSuchAlgorithmException, NoSuchProviderException { if (validate()) { String desc = descText.getText(); String amount = amountText.getText(); LocalDate date = dateSelect.getValue(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.of(date, time); String dateTimeString = dateTime.toString(); Expenditure expenditure = new Expenditure(0l, ScreenManager.getCurrentUser().getUserId(), desc, Float.parseFloat(amount), dateTimeString); Task<Expenditure> task = new Task<Expenditure>() { @Override protected Expenditure call() throws Exception { return expenditureDAO.save(expenditure); } }; task.setOnSucceeded(e -> { if (task.getValue().getErrorMessage() == null) { clearFields(); ph.showInfo(Message.EXPENDITURE_ADD); descText.requestFocus(); // Added new user to TableView ExpenditureController.addItem(task.getValue()); } else { ph.showError(task.getValue().getErrorMessage()); } }); executor.execute(task); } } @FXML public void cancelAction() { Stage stage = (Stage) cancelButton.getScene().getWindow(); stage.close(); } @FXML public void saveKeyPress(KeyEvent event) throws NoSuchAlgorithmException, NoSuchProviderException { if (event.getCode() == KeyCode.ENTER) { saveAction(); } } @FXML public void cancelKeyPress(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { cancelAction(); } } // Validate User data public boolean validate() { boolean valid = true; StringJoiner errorMessage = new StringJoiner(", "); errorMessage.add("Error: "); if (descText.getText().isEmpty()) { valid = false; errorMessage.add("Description"); } if (amountText.getText().isEmpty()) { valid = false; errorMessage.add("Amount"); } else { try { Float.parseFloat(amountText.getText().trim()); } catch (NumberFormatException e) { valid = false; errorMessage.add("Invalid Amount value"); } } if (dateSelect.getValue() == null) { valid = false; errorMessage.add("Date"); } if (valid) { return true; } else { ph.showError(errorMessage.toString()); return false; } } // Clear user fields public void clearFields() { descText.setText(""); amountText.setText(""); dateSelect.setValue(LocalDate.now()); } }
UTF-8
Java
4,626
java
ExpenditureAddController.java
Java
[]
null
[]
package restaurant.controllers; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ResourceBundle; import java.util.StringJoiner; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXDatePicker; import com.jfoenix.controls.JFXTextField; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.stage.Stage; import javafx.util.StringConverter; import restaurant.dao.ExpenditureDAO; import restaurant.helpers.Message; import restaurant.helpers.PopupHelper; import restaurant.helpers.ScreenManager; import restaurant.models.Expenditure; public class ExpenditureAddController implements Initializable { @FXML private JFXTextField descText; @FXML private JFXTextField amountText; @FXML private JFXDatePicker dateSelect; @FXML private JFXButton saveButton; @FXML private JFXButton cancelButton; private Executor executor; private ExpenditureDAO expenditureDAO = new ExpenditureDAO(); private PopupHelper ph = new PopupHelper(); private String dateFormat = "dd/MM/yyyy"; private StringConverter<LocalDate> converter; @Override public void initialize(URL location, ResourceBundle resources) { executor = Executors.newCachedThreadPool(runnable -> { Thread t = new Thread(runnable); t.setDaemon(true); return t; }); dateSelect.setValue(LocalDate.now()); converter = new StringConverter<LocalDate>() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat); @Override public LocalDate fromString(String string) { if (string != null && !string.isEmpty()) { return LocalDate.parse(string, formatter); } else { return null; } } @Override public String toString(LocalDate date) { if (date != null) { return formatter.format(date); } else { return ""; } } }; dateSelect.setConverter(converter); } @FXML public void saveAction() throws NoSuchAlgorithmException, NoSuchProviderException { if (validate()) { String desc = descText.getText(); String amount = amountText.getText(); LocalDate date = dateSelect.getValue(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.of(date, time); String dateTimeString = dateTime.toString(); Expenditure expenditure = new Expenditure(0l, ScreenManager.getCurrentUser().getUserId(), desc, Float.parseFloat(amount), dateTimeString); Task<Expenditure> task = new Task<Expenditure>() { @Override protected Expenditure call() throws Exception { return expenditureDAO.save(expenditure); } }; task.setOnSucceeded(e -> { if (task.getValue().getErrorMessage() == null) { clearFields(); ph.showInfo(Message.EXPENDITURE_ADD); descText.requestFocus(); // Added new user to TableView ExpenditureController.addItem(task.getValue()); } else { ph.showError(task.getValue().getErrorMessage()); } }); executor.execute(task); } } @FXML public void cancelAction() { Stage stage = (Stage) cancelButton.getScene().getWindow(); stage.close(); } @FXML public void saveKeyPress(KeyEvent event) throws NoSuchAlgorithmException, NoSuchProviderException { if (event.getCode() == KeyCode.ENTER) { saveAction(); } } @FXML public void cancelKeyPress(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { cancelAction(); } } // Validate User data public boolean validate() { boolean valid = true; StringJoiner errorMessage = new StringJoiner(", "); errorMessage.add("Error: "); if (descText.getText().isEmpty()) { valid = false; errorMessage.add("Description"); } if (amountText.getText().isEmpty()) { valid = false; errorMessage.add("Amount"); } else { try { Float.parseFloat(amountText.getText().trim()); } catch (NumberFormatException e) { valid = false; errorMessage.add("Invalid Amount value"); } } if (dateSelect.getValue() == null) { valid = false; errorMessage.add("Date"); } if (valid) { return true; } else { ph.showError(errorMessage.toString()); return false; } } // Clear user fields public void clearFields() { descText.setText(""); amountText.setText(""); dateSelect.setValue(LocalDate.now()); } }
4,626
0.71725
0.717034
194
22.845362
20.629196
100
false
false
0
0
0
0
0
0
2.170103
false
false
7
00a1636f767006a15daa44d9c877621310bba319
19,327,352,874,229
def8f201e52ced99fcf0d3c52aca1ca3c2e51ccd
/app/src/main/java/com/haoxt/agent/util/JsonUtils.java
462490d22c8319bb69056d14ec329d1507f55380
[ "MIT" ]
permissive
shanghaiEast/HaoxtAgent_Android
https://github.com/shanghaiEast/HaoxtAgent_Android
64b22732c65273be9c59234565a516996edc1113
9cd522764771f63fdd58e518176f5765d3aeaa48
refs/heads/master
2020-08-22T18:33:42.322000
2019-10-31T04:02:59
2019-10-31T04:02:59
216,457,955
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.haoxt.agent.util; import com.google.gson.Gson; import com.google.gson.internal.LinkedTreeMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsonUtils { public static String Array2Json(ArrayList<HashMap<String, Object>> ls){ Gson gson = new Gson(); return gson.toJson(ls); } public static String MapObj2Json(Map<String, Object> map){ Gson gson = new Gson(); return gson.toJson(map); } public static String LinkedTreeMap2Json(ArrayList<LinkedTreeMap<String, Object>> map){ Gson gson = new Gson(); return gson.toJson(map); } public static String listBTojson(List<String> list) { StringBuffer json = new StringBuffer(); json.append("{'BinB':["); if (list.size() > 0 && list != null) { for (int i = 0; i < list.size() - 1; i += 2) { json.append("{'" + list.get(i + 1) + "':'" + list.get(i) + "'}"); json.append(","); } json.setCharAt(json.length() - 1, ']'); } json.append("}"); return json.toString(); } public static String listCTojson(List<String> list) { StringBuffer json = new StringBuffer(); json.append("{'BinC':["); if (list.size() > 0 && list != null) { for (int i = 0; i < list.size() - 1; i += 2) { json.append("{'" + list.get(i + 1) + "':'" + list.get(i) + "'}"); json.append(","); } json.setCharAt(json.length() - 1, ']'); } json.append("}"); return json.toString(); } }
UTF-8
Java
1,459
java
JsonUtils.java
Java
[]
null
[]
package com.haoxt.agent.util; import com.google.gson.Gson; import com.google.gson.internal.LinkedTreeMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsonUtils { public static String Array2Json(ArrayList<HashMap<String, Object>> ls){ Gson gson = new Gson(); return gson.toJson(ls); } public static String MapObj2Json(Map<String, Object> map){ Gson gson = new Gson(); return gson.toJson(map); } public static String LinkedTreeMap2Json(ArrayList<LinkedTreeMap<String, Object>> map){ Gson gson = new Gson(); return gson.toJson(map); } public static String listBTojson(List<String> list) { StringBuffer json = new StringBuffer(); json.append("{'BinB':["); if (list.size() > 0 && list != null) { for (int i = 0; i < list.size() - 1; i += 2) { json.append("{'" + list.get(i + 1) + "':'" + list.get(i) + "'}"); json.append(","); } json.setCharAt(json.length() - 1, ']'); } json.append("}"); return json.toString(); } public static String listCTojson(List<String> list) { StringBuffer json = new StringBuffer(); json.append("{'BinC':["); if (list.size() > 0 && list != null) { for (int i = 0; i < list.size() - 1; i += 2) { json.append("{'" + list.get(i + 1) + "':'" + list.get(i) + "'}"); json.append(","); } json.setCharAt(json.length() - 1, ']'); } json.append("}"); return json.toString(); } }
1,459
0.614805
0.604524
62
22.532259
21.999794
87
false
false
0
0
0
0
0
0
1.967742
false
false
7
6020ecd737a97cb7cbed7d0b12370ee57b34d4aa
29,532,195,161,410
b4e14455460ce4e60895c5d8b5b8cf4fccc6a6e7
/src/com/silentmatt/dss/error/PrintStreamErrorReporter.java
f7995e6de7706ec06651e62dc10ed6cc2d128587
[ "MIT" ]
permissive
silentmatt/dss
https://github.com/silentmatt/dss
5f216054841c0f722dc6ac0df0d2df68c14b0158
5e2e5c520f779015aaf7dc441d2e2210dc00aaf3
refs/heads/master
2021-01-23T08:38:31.685000
2015-02-04T06:11:30
2015-02-04T06:11:38
252,458
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.silentmatt.dss.error; import java.io.PrintStream; /** * An {@link ErrorReporter} implementation that writes error messages to a * {@link PrintStream}. If no PrintStream is specified, it defaults to {@link System#err}. * * @author Matthew Crumley */ public class PrintStreamErrorReporter extends AbstractErrorReporter { private int errorCount = 0; private int warningCount = 0; private final java.io.PrintStream errorStream; /** * Constructs a PrintStreamErrorReporter that prints messages to {@link System#err}. */ public PrintStreamErrorReporter() { this(System.err); } /** * Constructs a PrintStreamErrorReporter that prints messages to a specified * {@link PrintStream}. * * @param out The PrintStream to print messages to. */ public PrintStreamErrorReporter(PrintStream out) { super(); errorStream = out; } @Override public int getErrorCount() { return errorCount; } @Override public int getWarningCount() { return warningCount; } @Override public void addError(Message error) { errorStream.println(error); errorCount++; } @Override public void addWarning(Message warning) { errorStream.println(warning); warningCount++; } }
UTF-8
Java
1,345
java
PrintStreamErrorReporter.java
Java
[ { "context": ", it defaults to {@link System#err}.\n *\n * @author Matthew Crumley\n */\npublic class PrintStreamErrorReporter extends", "end": 263, "score": 0.9998778104782104, "start": 248, "tag": "NAME", "value": "Matthew Crumley" } ]
null
[]
package com.silentmatt.dss.error; import java.io.PrintStream; /** * An {@link ErrorReporter} implementation that writes error messages to a * {@link PrintStream}. If no PrintStream is specified, it defaults to {@link System#err}. * * @author <NAME> */ public class PrintStreamErrorReporter extends AbstractErrorReporter { private int errorCount = 0; private int warningCount = 0; private final java.io.PrintStream errorStream; /** * Constructs a PrintStreamErrorReporter that prints messages to {@link System#err}. */ public PrintStreamErrorReporter() { this(System.err); } /** * Constructs a PrintStreamErrorReporter that prints messages to a specified * {@link PrintStream}. * * @param out The PrintStream to print messages to. */ public PrintStreamErrorReporter(PrintStream out) { super(); errorStream = out; } @Override public int getErrorCount() { return errorCount; } @Override public int getWarningCount() { return warningCount; } @Override public void addError(Message error) { errorStream.println(error); errorCount++; } @Override public void addWarning(Message warning) { errorStream.println(warning); warningCount++; } }
1,336
0.655762
0.654275
55
23.454546
23.743952
90
false
false
0
0
0
0
0
0
0.272727
false
false
7
96c24998da9a40f0547808f4e2163774924d4e1d
3,204,045,653,970
43f9130213c8968678ff930a94517a19f772dd7c
/src/Algo_1.java
3b750f3e1464560eff5881e1d782060b4d7ab750
[]
no_license
hardToForget/soongCode
https://github.com/hardToForget/soongCode
0af4ee03cb7ceca718f398c75e36cd9af1ef3f4f
d537f0e8caf44b74ccea62b288c583c3ab6d4c63
refs/heads/master
2019-02-18T04:46:39.994000
2017-11-15T02:21:03
2017-11-15T02:22:47
100,487,130
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Algo_1 { static double minValue = Double.MAX_VALUE; static int startIndex = 0; public static void main(String[] args) { // TODO Auto-generated method stub int[] A = { 4, 2, 2, 5, 1, 5, 8 }; for(int mode = 2; mode<A.length; mode++) solveSlice(A, mode); System.out.println("Result Avg=> " + minValue); System.out.println("Result Index=> " + startIndex); } public static void solveSlice(int[] A, int mode){ for(int i=0; i < A.length - mode + 1; i++){ double tempValue = sumAndAvg(A, i, i+mode-1); //((double)( A[i] + A[i+mode-1] ) / mode); System.out.println(tempValue); if( tempValue < minValue){ minValue = tempValue; startIndex = i; } } } public static double sumAndAvg(int[] array, int start, int end) { double sum = 0; // Array Sum에 대한 DP 시도 for (int i = start; i < end+1; i++){ sum += array[i]; } return sum / (end - start + 1); } }
UTF-8
Java
1,103
java
Algo_1.java
Java
[]
null
[]
public class Algo_1 { static double minValue = Double.MAX_VALUE; static int startIndex = 0; public static void main(String[] args) { // TODO Auto-generated method stub int[] A = { 4, 2, 2, 5, 1, 5, 8 }; for(int mode = 2; mode<A.length; mode++) solveSlice(A, mode); System.out.println("Result Avg=> " + minValue); System.out.println("Result Index=> " + startIndex); } public static void solveSlice(int[] A, int mode){ for(int i=0; i < A.length - mode + 1; i++){ double tempValue = sumAndAvg(A, i, i+mode-1); //((double)( A[i] + A[i+mode-1] ) / mode); System.out.println(tempValue); if( tempValue < minValue){ minValue = tempValue; startIndex = i; } } } public static double sumAndAvg(int[] array, int start, int end) { double sum = 0; // Array Sum에 대한 DP 시도 for (int i = start; i < end+1; i++){ sum += array[i]; } return sum / (end - start + 1); } }
1,103
0.503202
0.487649
41
25.658537
24.005701
100
false
false
0
0
0
0
0
0
0.780488
false
false
7
934ccd874e94ecd3f633ccf0b9c2dfd348037706
30,786,325,609,770
0126032833cab5661f02d98934f476c19bab3d90
/src/com/mani/gayi/threads/NameThreads.java
2a1e9e6408c789c399b977b355ce69dbc0c97980
[]
no_license
kotiprasad1990/ProjectGayi
https://github.com/kotiprasad1990/ProjectGayi
7ee19bf02502206adaca60ddb2f9f9f3083e6f8f
e9b4b048fd86d22fe3062108a9e08de9cc761d2a
refs/heads/master
2021-01-19T04:35:01.551000
2016-08-03T07:09:47
2016-08-03T07:09:47
53,749,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mani.gayi.threads; public class NameThreads extends Thread { public void run() { System.out.println("Running..."); } public static void main(String args[]) { NameThreads t1 = new NameThreads(); NameThreads t2 = new NameThreads(); System.out.println("Name of t1:" + t1.getName()); System.out.println("Name of t2:" + t2.getName()); t1.start(); t2.start(); t1.setName("Sonoo Jaiswal"); System.out.println("After changing name of t1:" + t1.getName()); System.out.println("After changing name of t1:" + t1.getId()); } }
UTF-8
Java
578
java
NameThreads.java
Java
[ { "context": "\r\n\t\tt1.start();\r\n\t\tt2.start();\r\n\t\t\r\n\t\tt1.setName(\"Sonoo Jaiswal\");\r\n\t\tSystem.out.println(\"After changing name of ", "end": 432, "score": 0.9998588562011719, "start": 419, "tag": "NAME", "value": "Sonoo Jaiswal" } ]
null
[]
package com.mani.gayi.threads; public class NameThreads extends Thread { public void run() { System.out.println("Running..."); } public static void main(String args[]) { NameThreads t1 = new NameThreads(); NameThreads t2 = new NameThreads(); System.out.println("Name of t1:" + t1.getName()); System.out.println("Name of t2:" + t2.getName()); t1.start(); t2.start(); t1.setName("<NAME>"); System.out.println("After changing name of t1:" + t1.getName()); System.out.println("After changing name of t1:" + t1.getId()); } }
571
0.641869
0.619377
21
25.523809
21.65667
66
false
false
0
0
0
0
0
0
1.761905
false
false
7
e8e7ab30208c82a5ecb7e6b82a9e52205a97c1dc
2,637,109,952,839
a4f5f4e42ec3d79de808e37205c55b6e5b64d6a5
/removeVowel.java
87a7d34f04ebc35b3c4839744fa86675064f348a
[]
no_license
Muhammadsharifi/java
https://github.com/Muhammadsharifi/java
958fbb917b27b8e140403dd7d90553b75ef69f15
b623d0462923456e531451f8c93dfc1f413afb01
refs/heads/master
2022-11-13T21:45:39.108000
2020-06-29T20:13:21
2020-06-29T20:13:21
275,891,275
0
0
null
false
2020-06-29T20:13:22
2020-06-29T18:08:36
2020-06-29T19:52:09
2020-06-29T20:13:22
0
0
0
0
Java
false
false
import java.util.Scanner; public class removeVowel { public static void main(String [] args) { Scanner scnr = new Scanner(System.in); String userName; String newUserName; System.out.println("Enter a Name "); userName = scnr.nextLine(); newUserName = userName.replaceAll("[aeiouAEIOU]",""); System.out.println("Removing Vowels . . . ."); System.out.println("Name Converted from " + userName + " --> " + newUserName); } }
UTF-8
Java
458
java
removeVowel.java
Java
[]
null
[]
import java.util.Scanner; public class removeVowel { public static void main(String [] args) { Scanner scnr = new Scanner(System.in); String userName; String newUserName; System.out.println("Enter a Name "); userName = scnr.nextLine(); newUserName = userName.replaceAll("[aeiouAEIOU]",""); System.out.println("Removing Vowels . . . ."); System.out.println("Name Converted from " + userName + " --> " + newUserName); } }
458
0.655022
0.655022
15
29.533333
22.808966
82
false
false
0
0
0
0
0
0
0.666667
false
false
7
d873a93c60ad55452ffe1863845eb4abc4573022
1,958,505,145,257
e5472077bc96e981c74b59f440d131e2c65f325b
/Java/20180526 实验3/src/experiment_3/ClashofTitans.java
6a89409f976c585df32be2539f24a1dea872e4b3
[]
no_license
xiamunote/Code
https://github.com/xiamunote/Code
37c6d473d8acfd1f537bcb440f50b82835062358
13bd153408855ed85cd5099e98e8aa63f9dd27eb
refs/heads/master
2020-05-01T00:20:44.435000
2019-03-23T11:32:23
2019-03-23T11:32:23
177,166,776
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package experiment_3; public class ClashofTitans { public static void main(String[] args) { Titan t=new Titan(); //创建泰坦对象 Zues z=new Zues(); //创建宙斯对象 do { t.attack(z); //泰坦攻击宙斯 if(z.getHP()>0) { z.attack(t); //宙斯攻击泰坦 } else { System.out.println("宙斯HP为"+ z.HP + ",已经失败,胜利者是泰坦!"); return; } }while(t.getHP()>0 && z.getHP()>0); System.out.println("泰坦HP为"+ t.HP + ",已经失败,胜利者是宙斯!"); return; } }
GB18030
Java
553
java
ClashofTitans.java
Java
[]
null
[]
package experiment_3; public class ClashofTitans { public static void main(String[] args) { Titan t=new Titan(); //创建泰坦对象 Zues z=new Zues(); //创建宙斯对象 do { t.attack(z); //泰坦攻击宙斯 if(z.getHP()>0) { z.attack(t); //宙斯攻击泰坦 } else { System.out.println("宙斯HP为"+ z.HP + ",已经失败,胜利者是泰坦!"); return; } }while(t.getHP()>0 && z.getHP()>0); System.out.println("泰坦HP为"+ t.HP + ",已经失败,胜利者是宙斯!"); return; } }
553
0.566292
0.557303
25
16.799999
16.651726
56
false
false
0
0
0
0
0
0
2.6
false
false
7
3d88b292bca771f29bdfc82a8ef4f2a70cc9617b
16,887,811,475,428
7479ca4e3b01f74f9e8328820fa013258a3ebd2e
/vehicle/src/test/java/me/ibra/advertiser/vehicle/service/VehicleListingServiceImplGetShouldTest.java
4de5ef56d426bf7c17843a7de53d4077313ebe14
[ "MIT" ]
permissive
ibrahimelhadeg/backend-tech-assignment
https://github.com/ibrahimelhadeg/backend-tech-assignment
7afab37433eba79b313070b51c412d2ec704bdbf
c5ae1c7959f69fa4188bcaec30ea84f9800e8d26
refs/heads/main
2023-05-14T23:39:38.681000
2021-06-13T21:32:45
2021-06-13T21:32:45
376,177,690
0
0
null
true
2021-06-12T01:28:59
2021-06-12T01:28:59
2021-06-02T19:23:04
2021-06-02T19:07:35
3
0
0
0
null
false
false
package me.ibra.advertiser.vehicle.service; import java.time.YearMonth; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import me.ibra.advertiser.vehicle.domain.NewVehicleListing; import me.ibra.advertiser.vehicle.domain.UsedVehicleListing; import me.ibra.advertiser.vehicle.store.VehicleListingStore; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class VehicleListingServiceImplGetShouldTest { private Long newVehicleId; private Long usedVehicleId; private String vehicleType; private String vehicleBrand; private String vehicleModel; private Integer vehicleModelYear; private YearMonth vehicleEntryIntoService; private String vehicleFuel; private String vehicleGearBox; private String vehicleColor; private Integer vehicleHorsePower; private Integer vehicleDoorCount; private Integer vehicleSeatCount; private String vehicleCondition; private Long vehicleMileage; private VehicleListingServiceImpl vehicleListingServiceImpl; @BeforeEach void prepare_vehicles() { newVehicleId = 1L; usedVehicleId = 2L; vehicleType = "CAR"; vehicleBrand = "Renault"; vehicleModel = "Captur"; vehicleModelYear = 2016; vehicleEntryIntoService = YearMonth.of(2016, 10); vehicleFuel = "Gasoline"; vehicleGearBox = "Manual"; vehicleColor = "Black"; vehicleHorsePower = 90; vehicleDoorCount = 5; vehicleSeatCount = 5; vehicleCondition = "Very Good"; vehicleMileage = 30995L; VehicleListingStore vehicleListingStore = mock(VehicleListingStore.class); when(vehicleListingStore.findById(newVehicleId)).thenReturn( NewVehicleListing.builder() .id(newVehicleId).type(vehicleType).brand(vehicleBrand) .model(vehicleModel).modelYear(vehicleModelYear).fuel(vehicleFuel) .gearBox(vehicleGearBox).color(vehicleColor).horsePower(vehicleHorsePower) .doorCount(vehicleDoorCount).seatCount(vehicleSeatCount) .build()); when(vehicleListingStore.findById(usedVehicleId)).thenReturn( UsedVehicleListing.builder() .id(usedVehicleId).type(vehicleType).brand(vehicleBrand) .model(vehicleModel).modelYear(vehicleModelYear) .entryIntoService(vehicleEntryIntoService).fuel(vehicleFuel) .gearBox(vehicleGearBox).color(vehicleColor).horsePower(vehicleHorsePower) .doorCount(vehicleDoorCount).seatCount(vehicleSeatCount) .condition(vehicleCondition).mileage(vehicleMileage) .build()); vehicleListingServiceImpl = new VehicleListingServiceImpl(vehicleListingStore); } @Test void should_get_new_vehicle_by_id() { var vehicleOfIdOne = (NewVehicleListing) vehicleListingServiceImpl.getVehicle(newVehicleId); assertEquals(newVehicleId, vehicleOfIdOne.id()); assertEquals(vehicleType, vehicleOfIdOne.type()); assertEquals(vehicleBrand, vehicleOfIdOne.brand()); assertEquals(vehicleModel, vehicleOfIdOne.model()); assertEquals(vehicleModelYear, vehicleOfIdOne.modelYear()); assertEquals(vehicleFuel, vehicleOfIdOne.fuel()); assertEquals(vehicleGearBox, vehicleOfIdOne.gearBox()); assertEquals(vehicleColor, vehicleOfIdOne.color()); assertEquals(vehicleHorsePower, vehicleOfIdOne.horsePower()); assertEquals(vehicleDoorCount, vehicleOfIdOne.doorCount()); assertEquals(vehicleSeatCount, vehicleOfIdOne.seatCount()); assertNull(vehicleOfIdOne.description()); } @Test void should_get_used_vehicle_by_id() { var vehicleOfIdOne = (UsedVehicleListing) vehicleListingServiceImpl.getVehicle(usedVehicleId); assertEquals(usedVehicleId, vehicleOfIdOne.id()); assertEquals(vehicleType, vehicleOfIdOne.type()); assertEquals(vehicleBrand, vehicleOfIdOne.brand()); assertEquals(vehicleModel, vehicleOfIdOne.model()); assertEquals(vehicleModelYear, vehicleOfIdOne.modelYear()); assertEquals(vehicleEntryIntoService, vehicleOfIdOne.entryIntoService()); assertEquals(vehicleFuel, vehicleOfIdOne.fuel()); assertEquals(vehicleGearBox, vehicleOfIdOne.gearBox()); assertEquals(vehicleColor, vehicleOfIdOne.color()); assertEquals(vehicleHorsePower, vehicleOfIdOne.horsePower()); assertEquals(vehicleDoorCount, vehicleOfIdOne.doorCount()); assertEquals(vehicleSeatCount, vehicleOfIdOne.seatCount()); assertEquals(vehicleCondition, vehicleOfIdOne.condition()); assertEquals(vehicleMileage, vehicleOfIdOne.mileage()); assertNull(vehicleOfIdOne.description()); } }
UTF-8
Java
5,133
java
VehicleListingServiceImplGetShouldTest.java
Java
[]
null
[]
package me.ibra.advertiser.vehicle.service; import java.time.YearMonth; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import me.ibra.advertiser.vehicle.domain.NewVehicleListing; import me.ibra.advertiser.vehicle.domain.UsedVehicleListing; import me.ibra.advertiser.vehicle.store.VehicleListingStore; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class VehicleListingServiceImplGetShouldTest { private Long newVehicleId; private Long usedVehicleId; private String vehicleType; private String vehicleBrand; private String vehicleModel; private Integer vehicleModelYear; private YearMonth vehicleEntryIntoService; private String vehicleFuel; private String vehicleGearBox; private String vehicleColor; private Integer vehicleHorsePower; private Integer vehicleDoorCount; private Integer vehicleSeatCount; private String vehicleCondition; private Long vehicleMileage; private VehicleListingServiceImpl vehicleListingServiceImpl; @BeforeEach void prepare_vehicles() { newVehicleId = 1L; usedVehicleId = 2L; vehicleType = "CAR"; vehicleBrand = "Renault"; vehicleModel = "Captur"; vehicleModelYear = 2016; vehicleEntryIntoService = YearMonth.of(2016, 10); vehicleFuel = "Gasoline"; vehicleGearBox = "Manual"; vehicleColor = "Black"; vehicleHorsePower = 90; vehicleDoorCount = 5; vehicleSeatCount = 5; vehicleCondition = "Very Good"; vehicleMileage = 30995L; VehicleListingStore vehicleListingStore = mock(VehicleListingStore.class); when(vehicleListingStore.findById(newVehicleId)).thenReturn( NewVehicleListing.builder() .id(newVehicleId).type(vehicleType).brand(vehicleBrand) .model(vehicleModel).modelYear(vehicleModelYear).fuel(vehicleFuel) .gearBox(vehicleGearBox).color(vehicleColor).horsePower(vehicleHorsePower) .doorCount(vehicleDoorCount).seatCount(vehicleSeatCount) .build()); when(vehicleListingStore.findById(usedVehicleId)).thenReturn( UsedVehicleListing.builder() .id(usedVehicleId).type(vehicleType).brand(vehicleBrand) .model(vehicleModel).modelYear(vehicleModelYear) .entryIntoService(vehicleEntryIntoService).fuel(vehicleFuel) .gearBox(vehicleGearBox).color(vehicleColor).horsePower(vehicleHorsePower) .doorCount(vehicleDoorCount).seatCount(vehicleSeatCount) .condition(vehicleCondition).mileage(vehicleMileage) .build()); vehicleListingServiceImpl = new VehicleListingServiceImpl(vehicleListingStore); } @Test void should_get_new_vehicle_by_id() { var vehicleOfIdOne = (NewVehicleListing) vehicleListingServiceImpl.getVehicle(newVehicleId); assertEquals(newVehicleId, vehicleOfIdOne.id()); assertEquals(vehicleType, vehicleOfIdOne.type()); assertEquals(vehicleBrand, vehicleOfIdOne.brand()); assertEquals(vehicleModel, vehicleOfIdOne.model()); assertEquals(vehicleModelYear, vehicleOfIdOne.modelYear()); assertEquals(vehicleFuel, vehicleOfIdOne.fuel()); assertEquals(vehicleGearBox, vehicleOfIdOne.gearBox()); assertEquals(vehicleColor, vehicleOfIdOne.color()); assertEquals(vehicleHorsePower, vehicleOfIdOne.horsePower()); assertEquals(vehicleDoorCount, vehicleOfIdOne.doorCount()); assertEquals(vehicleSeatCount, vehicleOfIdOne.seatCount()); assertNull(vehicleOfIdOne.description()); } @Test void should_get_used_vehicle_by_id() { var vehicleOfIdOne = (UsedVehicleListing) vehicleListingServiceImpl.getVehicle(usedVehicleId); assertEquals(usedVehicleId, vehicleOfIdOne.id()); assertEquals(vehicleType, vehicleOfIdOne.type()); assertEquals(vehicleBrand, vehicleOfIdOne.brand()); assertEquals(vehicleModel, vehicleOfIdOne.model()); assertEquals(vehicleModelYear, vehicleOfIdOne.modelYear()); assertEquals(vehicleEntryIntoService, vehicleOfIdOne.entryIntoService()); assertEquals(vehicleFuel, vehicleOfIdOne.fuel()); assertEquals(vehicleGearBox, vehicleOfIdOne.gearBox()); assertEquals(vehicleColor, vehicleOfIdOne.color()); assertEquals(vehicleHorsePower, vehicleOfIdOne.horsePower()); assertEquals(vehicleDoorCount, vehicleOfIdOne.doorCount()); assertEquals(vehicleSeatCount, vehicleOfIdOne.seatCount()); assertEquals(vehicleCondition, vehicleOfIdOne.condition()); assertEquals(vehicleMileage, vehicleOfIdOne.mileage()); assertNull(vehicleOfIdOne.description()); } }
5,133
0.697838
0.693746
113
44.424778
26.290348
102
false
false
0
0
0
0
0
0
0.893805
false
false
7
e09e7e736e7a8bb870ffc2e162f1ad901add9f1d
30,047,591,233,188
f7987df0dc8193c32563f793667e82bfaa29bed2
/src/main/java/com/impltech/chatApp/controller/MessageController.java
12d5291798c408313ad2376f9c06ac2cfce5a0d1
[]
no_license
Reed17/ChatApplication
https://github.com/Reed17/ChatApplication
17a4cc23b867399a79c117e2d006018a55810dc4
5c216f7ca762ba996e767a60e04fcd69dd6fbaeb
refs/heads/master
2020-04-26T19:11:22.854000
2019-03-11T14:15:09
2019-03-11T14:15:09
173,766,050
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.impltech.chatApp.controller; import com.impltech.chatApp.dto.MessageDto; import com.impltech.chatApp.service.MessageService; import com.impltech.chatApp.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class MessageController { private UserService userService; private MessageService messageService; @Autowired public MessageController(UserService userService, MessageService messageService) { this.userService = userService; this.messageService = messageService; } @MessageMapping("/chats") @SendTo("/topic/chats") public MessageDto handleChat(final String message) { //messageService.sendMessage(/*chatRoomId, */messageDto); MessageDto messageDto = new MessageDto(message); System.out.println("received message: " + messageDto); return messageDto; } }
UTF-8
Java
1,095
java
MessageController.java
Java
[]
null
[]
package com.impltech.chatApp.controller; import com.impltech.chatApp.dto.MessageDto; import com.impltech.chatApp.service.MessageService; import com.impltech.chatApp.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class MessageController { private UserService userService; private MessageService messageService; @Autowired public MessageController(UserService userService, MessageService messageService) { this.userService = userService; this.messageService = messageService; } @MessageMapping("/chats") @SendTo("/topic/chats") public MessageDto handleChat(final String message) { //messageService.sendMessage(/*chatRoomId, */messageDto); MessageDto messageDto = new MessageDto(message); System.out.println("received message: " + messageDto); return messageDto; } }
1,095
0.768037
0.768037
31
34.322582
24.802948
86
false
false
0
0
0
0
0
0
0.580645
false
false
7
8376e527c7495088a33be1e5b03df16dd18e009f
32,890,859,616,525
2c12f24988ef9526dde02b0312883270f207b860
/Back-end/FirstSpringProject/src/com/ibm/dao/impl/UserDaoImpl.java
a010f457942f4b35ceb8b836769452bc877f92d7
[]
no_license
bborisov/chat-app
https://github.com/bborisov/chat-app
25c81a474df79d6976ef2eefb23712d6f3f4e83f
c2e7496c551e6acbe39b3f31c117aacbbeb67121
refs/heads/master
2021-09-17T11:20:21.839000
2018-07-01T13:44:32
2018-07-01T13:44:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ibm.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import com.ibm.dao.UserDao; import com.ibm.entities.UserEntity; import com.ibm.entities.wrappers.User; @SuppressWarnings("unchecked") public class UserDaoImpl extends BasicDaoImpl<UserEntity> implements UserDao { @Override public User createUser(String userName, String email, String password, String salt, int statusId) { UserEntity userEntity = new UserEntity(userName, email, password, salt, statusId); Session session = sessionFactory.getCurrentSession(); session.persist(userEntity); return (User) userEntity; } @Override public User getUserByEmail(String email) { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(UserEntity.class); UserEntity userEntity = (UserEntity) criteria.add(Restrictions.eq("email", email)).uniqueResult(); return (User) userEntity; } @Override public List<User> getAllUsers() { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(UserEntity.class); List<User> listOfUsers = (List<User>) criteria.list(); for (User user : listOfUsers) { user.setPassword(null); user.setSalt(null); } // example // List<User> listOfUsers = listOfUserEntities.stream().map(u -> // u.toUser()).collect(Collectors.toList()); return listOfUsers; } @Override public Class<UserEntity> getEntityClass() { return UserEntity.class; } }
UTF-8
Java
1,557
java
UserDaoImpl.java
Java
[ { "context": "erDao {\n\n\t@Override\n\tpublic User createUser(String userName, String email, String password, String salt, int ", "end": 423, "score": 0.6341490149497986, "start": 415, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.ibm.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import com.ibm.dao.UserDao; import com.ibm.entities.UserEntity; import com.ibm.entities.wrappers.User; @SuppressWarnings("unchecked") public class UserDaoImpl extends BasicDaoImpl<UserEntity> implements UserDao { @Override public User createUser(String userName, String email, String password, String salt, int statusId) { UserEntity userEntity = new UserEntity(userName, email, password, salt, statusId); Session session = sessionFactory.getCurrentSession(); session.persist(userEntity); return (User) userEntity; } @Override public User getUserByEmail(String email) { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(UserEntity.class); UserEntity userEntity = (UserEntity) criteria.add(Restrictions.eq("email", email)).uniqueResult(); return (User) userEntity; } @Override public List<User> getAllUsers() { Session session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(UserEntity.class); List<User> listOfUsers = (List<User>) criteria.list(); for (User user : listOfUsers) { user.setPassword(null); user.setSalt(null); } // example // List<User> listOfUsers = listOfUserEntities.stream().map(u -> // u.toUser()).collect(Collectors.toList()); return listOfUsers; } @Override public Class<UserEntity> getEntityClass() { return UserEntity.class; } }
1,557
0.754656
0.754656
60
24.966667
26.670813
100
false
false
0
0
0
0
0
0
1.45
false
false
7
f9f6bfeddee9b7e4aeb4b8d9767d1a553311739a
15,917,148,834,549
877d7022bcc761f9f7c38e13499a1b91c2960579
/LeetCode_Java/src/DP/PaintFence.java
248e225f0b890ccd7952c523bde735bdc7eb4bae
[]
no_license
ChencongDiu/leetcode
https://github.com/ChencongDiu/leetcode
8d59068650e7dc4072ef148159ae4c908fafae4a
df2f61c4da240bceecf4b685dd557761268a9e6d
refs/heads/master
2021-09-14T10:35:02.125000
2018-05-11T22:28:50
2018-05-11T22:28:50
86,833,055
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DP; /* There is a fence with n posts, each post can be painted with one of the k colors. You have to paint all the posts such that no more than two adjacent fence posts have the same color. Return the total number of ways you can paint the fence. */ public class PaintFence { public int numWays(int n, int k) { if (n == 0) {return 0;} if (n == 1) {return k;} int same = k, dif = k * (k - 1); for (int i = 2; i < n; i++) { int temp = same; same = dif * 1; dif = (dif + temp) * (k - 1); } return dif + same; } }
UTF-8
Java
611
java
PaintFence.java
Java
[]
null
[]
package DP; /* There is a fence with n posts, each post can be painted with one of the k colors. You have to paint all the posts such that no more than two adjacent fence posts have the same color. Return the total number of ways you can paint the fence. */ public class PaintFence { public int numWays(int n, int k) { if (n == 0) {return 0;} if (n == 1) {return k;} int same = k, dif = k * (k - 1); for (int i = 2; i < n; i++) { int temp = same; same = dif * 1; dif = (dif + temp) * (k - 1); } return dif + same; } }
611
0.543371
0.531915
22
26.772728
25.919336
100
false
false
0
0
0
0
0
0
0.636364
false
false
7
88ed3c93c28e5804c8ece4b98dc803b56528b8bb
1,451,699,007,703
4c8642dbc1e9e48340b6230551a341c8997e78b2
/src/main/ui/Display.java
c778be643c5300573fac709035e7653c8011b950
[]
no_license
NingyuanXu/ToDo-List
https://github.com/NingyuanXu/ToDo-List
5a47c30214523b298adbafcb771cc683767c8aea
a7867c91754b283a53715e8ba819b9aeba1191fa
refs/heads/master
2020-05-28T05:48:58.780000
2018-11-25T21:03:00
2018-11-25T21:03:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.ui; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import main.model.Assignment; import main.model.TodoList; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; public class Display { private JPanel Display; private JList list1; private JButton saveButton; private JButton returnButton; public Display(TodoList todoList) { JFrame frame = new JFrame("Display"); frame.setContentPane(Display); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); DefaultListModel model = new DefaultListModel(); list1.setModel(model); DefaultListModel<String> listModel = (DefaultListModel) list1.getModel(); for (Assignment a : todoList.getTodoList()) { listModel.addElement(a.toString()); } saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { todoList.save(); } catch (IOException e1) { e1.printStackTrace(); } JOptionPane.showMessageDialog(null, "The Todo List has been saved!"); } }); returnButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.setVisible(false); } }); list1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); } }); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { Display = new JPanel(); Display.setLayout(new GridLayoutManager(4, 1, new Insets(0, 0, 0, 0), -1, -1)); final JLabel label1 = new JLabel(); label1.setText("Show all the assignments in the Todo List"); Display.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); saveButton = new JButton(); saveButton.setText("Save"); Display.add(saveButton, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); returnButton = new JButton(); returnButton.setText("Return"); Display.add(returnButton, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); list1 = new JList(); Display.add(list1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(150, 50), null, 0, false)); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return Display; } }
UTF-8
Java
3,803
java
Display.java
Java
[]
null
[]
package main.ui; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import main.model.Assignment; import main.model.TodoList; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; public class Display { private JPanel Display; private JList list1; private JButton saveButton; private JButton returnButton; public Display(TodoList todoList) { JFrame frame = new JFrame("Display"); frame.setContentPane(Display); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); DefaultListModel model = new DefaultListModel(); list1.setModel(model); DefaultListModel<String> listModel = (DefaultListModel) list1.getModel(); for (Assignment a : todoList.getTodoList()) { listModel.addElement(a.toString()); } saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { todoList.save(); } catch (IOException e1) { e1.printStackTrace(); } JOptionPane.showMessageDialog(null, "The Todo List has been saved!"); } }); returnButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.setVisible(false); } }); list1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); } }); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { Display = new JPanel(); Display.setLayout(new GridLayoutManager(4, 1, new Insets(0, 0, 0, 0), -1, -1)); final JLabel label1 = new JLabel(); label1.setText("Show all the assignments in the Todo List"); Display.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); saveButton = new JButton(); saveButton.setText("Save"); Display.add(saveButton, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); returnButton = new JButton(); returnButton.setText("Return"); Display.add(returnButton, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); list1 = new JList(); Display.add(list1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, new Dimension(150, 50), null, 0, false)); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return Display; } }
3,803
0.645543
0.633973
97
38.206184
48.252758
270
false
false
0
0
0
0
0
0
1.14433
false
false
7
54e13e5d1b803242946cb47b6d99c0468a37e8be
22,376,779,640,826
03402081a0d2c3f219ff0366a39be2de4c01223b
/planering/src/main/java/no/onlevel/micro/code/variable/Variable.java
ed62bd5426dcdbb23388414859e8ae8c944caaba
[]
no_license
warild/micro-programmering
https://github.com/warild/micro-programmering
b79ae0ebc7782b3deb48797d2e3f412e76ea8f9d
96e7c828f8c8fd4ae6b424b3fedf516f1d73d65c
refs/heads/master
2020-06-22T07:26:55.815000
2018-07-31T19:57:31
2018-07-31T19:57:31
74,597,973
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package no.onlevel.micro.code.variable; import java.util.List; import no.onlevel.micro.code.logic.Then; import no.onlevel.micro.subroutine.Div_16_16_8; import no.onlevel.micro.subroutine.Div_16_8_8; public class Variable { List<String> code; private Register register; public Variable(String name, List<String> code){ this.code = code; this.register = new Register(name); } public Register getRegister(){ return register; } // Set public void set(int k) { if (k == 0){ code.add(" clrf " + register.getName()); } else { code.add(" movlw " + toHex(k)); code.add(" movwf " + register.getName()); } } public void set(Register otherRegister) { code.add(" movfw " + otherRegister.getName()); code.add(" movwf " + register.getName()); } public void set(Variable v) { code.add(" movfw " + v.getRegister().getName()); code.add(" movwf " + register.getName()); } // Add public void add(int k) { if (k == 1) { code.add(" incf " + register.getName()); } else { code.add(" movlw " + toHex(k)); code.add(" addwf " + register.getName()); } } public void add(Variable var) { code.add(" movfw " + var.getRegister().getName()); code.add(" addwf " + register.getName()); } public void add(Variable a, Variable b) { code.add(" movfw " + a.getRegister().getName()); code.add(" addwf " + b.getRegister().getName() +",w"); code.add(" movwf " + register.getName()); } // Subtract public void sub(int k) { code.add(" movlw " + toHex(k)); code.add(" subwf " + register.getName()); } public void sub(Variable var) { code.add(" movfw " + var.getRegister().getName()); code.add(" subwf " + register.getName()); } public void sub(Variable a, Variable b) { code.add(" movfw " + b.getRegister().getName()); code.add(" subwf " + a.getRegister().getName() +",w"); code.add(" movwf " + register.getName()); } public void subIsNegThen(int k) { if (k == 0) { code.add(" btfss STATUS,C ; 1=no borrow. Skip to not_negative"); code.add(" clrf "+ register.getName() +" ; Replace neg value with " +k); } else { code.add(" movlw " + toHex(k)); code.add(" btfss STATUS,C ; 1=no borow. Skip to not_negative"); code.add(" movwf "+ register +" ; Replace neg value with " + k); } } // AND public void and(int k) { code.add(" movlw " + toHex(k)); code.add(" andwf " + register.getName()); } public void and(Variable r) { code.add(" movfw " + r.getRegister().getName()); code.add(" andwf " + register.getName()); } // OR public void or(int k) { code.add(" movlw " + toHex(k)); code.add(" iorwf " + register.getName()); } public void or(Variable r) { code.add(" movfw " + r.getRegister().getName()); code.add(" iorwf " + register.getName()); } // XOR public void xor(int k) { code.add(" movlw " + toHex(k)); code.add(" xorwf " + register.getName()); } public void xor(Variable r) { code.add(" movfw " + r.getRegister().getName()); code.add(" xorwf " + register.getName()); } // isBigger // if register is NOT bigger than r then goto OTHER blocklabel // if register is bigger than r then do.. public Then notBiggerThan(Variable r){ code.add(" movfw " + register.getName()); code.add(" subwf " + r.getRegister().getName() + ",w"); // B-A: When A is bigger the result is negative (borrowed: C=0) code.add(" btfsc STATUS,C ; Skip to "+ register.getName() +" is bigger"); return new Then(code); } // Equals // if NOT equals goto OTHER blocklabel // if equals then do... public Then notEquals(int i){ code.add(" movfw " + register.getName()); code.add(" xorlw " + toHex(i) +",w"); code.add(" btfss STATUS,Z ; Skip"); return new Then(code); } // Equals // if NOT equals goto OTHER blocklabel // if equals then do... public Then notEquals(Variable r){ code.add(" movfw " + register.getName()); code.add(" xorwf " + r.getRegister().getName() +",w"); code.add(" btfss STATUS,Z ; Skip to they are equal"); return new Then(code); } /** * Division 16/8=8 */ public void call(Div_16_8_8 div, Variable16 a16, Variable b8) { div.call(a16, b8, this); } public void div_16_8_8(Variable16 a16, Variable b8, Variable bitCounter) { new Div_16_8_8(code).divide(a16, b8, bitCounter, this); } /** * Division 16/16=8 */ public void call(Div_16_16_8 div, Variable16 a16, Variable16 b16) { div.call(a16, b16, this); } public void div_16_16_8(Variable16 a16, Variable16 b16, Variable bitCounter) { new Div_16_16_8(code).divide(a16, b16, bitCounter, this); } // ------------ public RegisterBit bit0 = new RegisterBit(0); public RegisterBit bit1 = new RegisterBit(1); public RegisterBit bit2 = new RegisterBit(2); public RegisterBit bit3 = new RegisterBit(3); public RegisterBit bit4 = new RegisterBit(4); public RegisterBit bit5 = new RegisterBit(5); public RegisterBit bit6 = new RegisterBit(6); public RegisterBit bit7 = new RegisterBit(7); protected String toHex(int value) { if (Integer.toHexString(value).length() == 1) { return "0x0" + Integer.toHexString(value).toString(); } else { return "0x" + Integer.toHexString(value).toString(); } } }
UTF-8
Java
5,224
java
Variable.java
Java
[]
null
[]
package no.onlevel.micro.code.variable; import java.util.List; import no.onlevel.micro.code.logic.Then; import no.onlevel.micro.subroutine.Div_16_16_8; import no.onlevel.micro.subroutine.Div_16_8_8; public class Variable { List<String> code; private Register register; public Variable(String name, List<String> code){ this.code = code; this.register = new Register(name); } public Register getRegister(){ return register; } // Set public void set(int k) { if (k == 0){ code.add(" clrf " + register.getName()); } else { code.add(" movlw " + toHex(k)); code.add(" movwf " + register.getName()); } } public void set(Register otherRegister) { code.add(" movfw " + otherRegister.getName()); code.add(" movwf " + register.getName()); } public void set(Variable v) { code.add(" movfw " + v.getRegister().getName()); code.add(" movwf " + register.getName()); } // Add public void add(int k) { if (k == 1) { code.add(" incf " + register.getName()); } else { code.add(" movlw " + toHex(k)); code.add(" addwf " + register.getName()); } } public void add(Variable var) { code.add(" movfw " + var.getRegister().getName()); code.add(" addwf " + register.getName()); } public void add(Variable a, Variable b) { code.add(" movfw " + a.getRegister().getName()); code.add(" addwf " + b.getRegister().getName() +",w"); code.add(" movwf " + register.getName()); } // Subtract public void sub(int k) { code.add(" movlw " + toHex(k)); code.add(" subwf " + register.getName()); } public void sub(Variable var) { code.add(" movfw " + var.getRegister().getName()); code.add(" subwf " + register.getName()); } public void sub(Variable a, Variable b) { code.add(" movfw " + b.getRegister().getName()); code.add(" subwf " + a.getRegister().getName() +",w"); code.add(" movwf " + register.getName()); } public void subIsNegThen(int k) { if (k == 0) { code.add(" btfss STATUS,C ; 1=no borrow. Skip to not_negative"); code.add(" clrf "+ register.getName() +" ; Replace neg value with " +k); } else { code.add(" movlw " + toHex(k)); code.add(" btfss STATUS,C ; 1=no borow. Skip to not_negative"); code.add(" movwf "+ register +" ; Replace neg value with " + k); } } // AND public void and(int k) { code.add(" movlw " + toHex(k)); code.add(" andwf " + register.getName()); } public void and(Variable r) { code.add(" movfw " + r.getRegister().getName()); code.add(" andwf " + register.getName()); } // OR public void or(int k) { code.add(" movlw " + toHex(k)); code.add(" iorwf " + register.getName()); } public void or(Variable r) { code.add(" movfw " + r.getRegister().getName()); code.add(" iorwf " + register.getName()); } // XOR public void xor(int k) { code.add(" movlw " + toHex(k)); code.add(" xorwf " + register.getName()); } public void xor(Variable r) { code.add(" movfw " + r.getRegister().getName()); code.add(" xorwf " + register.getName()); } // isBigger // if register is NOT bigger than r then goto OTHER blocklabel // if register is bigger than r then do.. public Then notBiggerThan(Variable r){ code.add(" movfw " + register.getName()); code.add(" subwf " + r.getRegister().getName() + ",w"); // B-A: When A is bigger the result is negative (borrowed: C=0) code.add(" btfsc STATUS,C ; Skip to "+ register.getName() +" is bigger"); return new Then(code); } // Equals // if NOT equals goto OTHER blocklabel // if equals then do... public Then notEquals(int i){ code.add(" movfw " + register.getName()); code.add(" xorlw " + toHex(i) +",w"); code.add(" btfss STATUS,Z ; Skip"); return new Then(code); } // Equals // if NOT equals goto OTHER blocklabel // if equals then do... public Then notEquals(Variable r){ code.add(" movfw " + register.getName()); code.add(" xorwf " + r.getRegister().getName() +",w"); code.add(" btfss STATUS,Z ; Skip to they are equal"); return new Then(code); } /** * Division 16/8=8 */ public void call(Div_16_8_8 div, Variable16 a16, Variable b8) { div.call(a16, b8, this); } public void div_16_8_8(Variable16 a16, Variable b8, Variable bitCounter) { new Div_16_8_8(code).divide(a16, b8, bitCounter, this); } /** * Division 16/16=8 */ public void call(Div_16_16_8 div, Variable16 a16, Variable16 b16) { div.call(a16, b16, this); } public void div_16_16_8(Variable16 a16, Variable16 b16, Variable bitCounter) { new Div_16_16_8(code).divide(a16, b16, bitCounter, this); } // ------------ public RegisterBit bit0 = new RegisterBit(0); public RegisterBit bit1 = new RegisterBit(1); public RegisterBit bit2 = new RegisterBit(2); public RegisterBit bit3 = new RegisterBit(3); public RegisterBit bit4 = new RegisterBit(4); public RegisterBit bit5 = new RegisterBit(5); public RegisterBit bit6 = new RegisterBit(6); public RegisterBit bit7 = new RegisterBit(7); protected String toHex(int value) { if (Integer.toHexString(value).length() == 1) { return "0x0" + Integer.toHexString(value).toString(); } else { return "0x" + Integer.toHexString(value).toString(); } } }
5,224
0.624809
0.603561
178
28.348314
22.607347
122
false
false
0
0
0
0
0
0
2.578652
false
false
7
fbdde4d5551ea204992ae8a0b28bfc114e6930be
3,444,563,830,382
f39bbf6225205b7749b1ec315f9d7df16d18aabf
/OSML2/src/main/java/com/oldschoolminecraft/osml/util/ActionPipe.java
39ac6da0969e89b1b81d60afa0d9eaa710bf9cec
[]
no_license
OldSchoolMinecraft/OSML2
https://github.com/OldSchoolMinecraft/OSML2
a1757cde92040e76b4e00e57839bcdbeec22f40b
f5f245cceae8f2777ce3f6640ef9abfa3f21d9f8
refs/heads/master
2022-08-26T20:04:32.148000
2020-12-07T07:03:02
2020-12-07T07:03:02
291,137,351
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oldschoolminecraft.osml.util; public interface ActionPipe { public void fire(); }
UTF-8
Java
105
java
ActionPipe.java
Java
[]
null
[]
package com.oldschoolminecraft.osml.util; public interface ActionPipe { public void fire(); }
105
0.714286
0.714286
6
15.5
15.808753
41
false
false
0
0
0
0
0
0
0.333333
false
false
7
4ea3ad00ccd278b96efe1aa487f80ca9f64e9eb3
1,271,310,382,425
f2a7f5b824b25be6d8c4827754d7da0633115b13
/src/Coordonate.java
654842038578a297ae10e24190045211050b3a33
[]
no_license
dumitrachegeani/Butterfly-Kiodai-v1
https://github.com/dumitrachegeani/Butterfly-Kiodai-v1
9bd89e379dbda403a75269b2cbde9016de5c1377
b7da76a8a316a6cc0651d42228c603a6465fb800
refs/heads/master
2023-06-30T11:09:56.966000
2021-08-06T09:12:42
2021-08-06T09:12:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Coordonate { int i; int j; public Coordonate(int i, int j) { this.i = i; this.j = j; } }
UTF-8
Java
111
java
Coordonate.java
Java
[]
null
[]
public class Coordonate { int i; int j; public Coordonate(int i, int j) { this.i = i; this.j = j; } }
111
0.585586
0.585586
9
11.333333
10.883219
34
false
false
0
0
0
0
0
0
1.444444
false
false
7
0db11b0cc42dafcffa95fe8971fc58fff46e346a
7,232,724,931,326
b7a9998120e8cdcb2648a30f12ca6b80c5cab367
/src/com/harrymanchanda/Main.java
aa92cc33dcac95a584f94d570f0357e3bcdd5c96
[]
no_license
IamManchanda/ByteShortInt
https://github.com/IamManchanda/ByteShortInt
7a7f5b13230c8f6fda2d67e7448d07db11d47d5d
4edb9ba6b20e30e3af30d5490b470e8cd1de9d6e
refs/heads/master
2020-04-02T05:11:12.267000
2018-10-21T22:06:24
2018-10-21T22:09:16
154,056,745
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.harrymanchanda; public class Main { public static void main(String[] args) { // width of 8 bits <==> 1 Byte byte myMinByteValue = -128; // - 2**7 byte myMaxByteValue = +127; // + 2**7 - 1 // width of 16 bits <==> 2 Bytes short myMinShortValue = -32_678; // - 2**15 short myMaxShortValue = +32_677; // + 2**15 - 1 // width of 32 bits <==> 4 Bytes int myMinIntValue = -2_147_483_648; // - 2**31 int myMaxIntValue = +2_147_483_647; // + 2**31 - 1 // width of 64 bits <==> 8 Bytes long myMinLongValue = -9_223_372_036_854_775_808L; // - 2**63 long myMaxLongValue = +9_223_372_036_854_775_807L; // + 2**63 - 1 // width of 32 bits <==> 4 Bytes float myFloatValue = 5.25F; // width of 64 bits <==> 8 Bytes double myDoubleValue = 5.25D; } }
UTF-8
Java
887
java
Main.java
Java
[]
null
[]
package com.harrymanchanda; public class Main { public static void main(String[] args) { // width of 8 bits <==> 1 Byte byte myMinByteValue = -128; // - 2**7 byte myMaxByteValue = +127; // + 2**7 - 1 // width of 16 bits <==> 2 Bytes short myMinShortValue = -32_678; // - 2**15 short myMaxShortValue = +32_677; // + 2**15 - 1 // width of 32 bits <==> 4 Bytes int myMinIntValue = -2_147_483_648; // - 2**31 int myMaxIntValue = +2_147_483_647; // + 2**31 - 1 // width of 64 bits <==> 8 Bytes long myMinLongValue = -9_223_372_036_854_775_808L; // - 2**63 long myMaxLongValue = +9_223_372_036_854_775_807L; // + 2**63 - 1 // width of 32 bits <==> 4 Bytes float myFloatValue = 5.25F; // width of 64 bits <==> 8 Bytes double myDoubleValue = 5.25D; } }
887
0.531003
0.392334
27
31.851852
22.867903
73
false
false
0
0
0
0
0
0
0.407407
false
false
7
0898bf86c7f3e73703b83e51c71a7ab6844d2916
23,338,852,291,375
25d5d90b562d712aa2e5e43f5efddd63a50c5e21
/pic-project/pic-rest/src/main/java/pe/com/bbva/pic/dao/BaseDAO.java
e3153ae4252921e5c1db645c85c835f2e99c5db3
[]
no_license
stormenta/pic
https://github.com/stormenta/pic
f5926dc970a3f858bc7e8793263433e281c9e295
5bd849974ebf2a7d45e04b3f4cac77e37c9ab268
refs/heads/master
2017-05-06T03:22:44.305000
2017-02-24T18:01:03
2017-02-24T18:01:03
35,303,752
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.com.bbva.pic.dao; import java.io.Serializable; import java.util.List; import pe.com.bbva.pic.exception.DAOException; import pe.com.bbva.pic.util.Busqueda; public interface BaseDAO<Entidad, Id extends Serializable> extends Serializable { Entidad crear(Entidad entidad) throws DAOException; List<Entidad> crearEntidades(List<Entidad> entidades) throws DAOException; Entidad obtener(Id id) throws DAOException; Entidad modificar(Entidad entidad) throws DAOException; void eliminar(Id id) throws DAOException; List<Entidad> listar(Busqueda busqueda) throws DAOException; <T> List<T> proyectar(Busqueda busqueda) throws DAOException; Long contar(Busqueda busqueda, String propertyName) throws DAOException; Long maximo(Busqueda busqueda, String propertyName) throws DAOException; }
UTF-8
Java
809
java
BaseDAO.java
Java
[]
null
[]
package pe.com.bbva.pic.dao; import java.io.Serializable; import java.util.List; import pe.com.bbva.pic.exception.DAOException; import pe.com.bbva.pic.util.Busqueda; public interface BaseDAO<Entidad, Id extends Serializable> extends Serializable { Entidad crear(Entidad entidad) throws DAOException; List<Entidad> crearEntidades(List<Entidad> entidades) throws DAOException; Entidad obtener(Id id) throws DAOException; Entidad modificar(Entidad entidad) throws DAOException; void eliminar(Id id) throws DAOException; List<Entidad> listar(Busqueda busqueda) throws DAOException; <T> List<T> proyectar(Busqueda busqueda) throws DAOException; Long contar(Busqueda busqueda, String propertyName) throws DAOException; Long maximo(Busqueda busqueda, String propertyName) throws DAOException; }
809
0.804697
0.804697
28
27.928572
29.061424
81
false
false
0
0
0
0
0
0
0.964286
false
false
7
2b90e075965f0fa7cfdb1a513952a78a9ee8958d
31,894,427,145,777
618c5238de6711c9c7ea8424e47f3611493010cf
/src/main/java/com/aspose/email/cloud/sdk/model/MapiMessageItemBaseDto.java
24186298f0639c9d08da66c832a7bb253bebd41e
[ "MIT" ]
permissive
aspose-email-cloud/aspose-email-cloud-java
https://github.com/aspose-email-cloud/aspose-email-cloud-java
2496ab4ef4cce0ba16744b2b2db2a1d43e3ee325
e567f34bcae8727daafa7538fc9a91fa6b4e8746
refs/heads/master
2023-08-22T15:25:51.045000
2021-09-21T18:40:41
2021-09-21T18:40:41
219,990,008
1
0
MIT
false
2023-05-09T18:57:25
2019-11-06T12:19:30
2021-09-21T18:40:45
2023-05-09T18:57:22
1,874
1
0
3
Java
false
false
/* * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose" file="MapiMessageItemBaseDto.java"> * Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved. * </copyright> * <summary> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ package com.aspose.email.cloud.sdk.model; import org.apache.commons.lang3.ObjectUtils; import java.util.Date; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.*; import com.google.gson.*; import com.google.gson.stream.*; import java.io.*; /** * Base Dto for MapiMessage, MapiCalendar or MapiContact */ public class MapiMessageItemBaseDto { @JsonProperty("attachments") private List<MapiAttachmentDto> attachments = null; @JsonProperty("billing") private String billing = null; @JsonProperty("body") private String body = null; @JsonProperty("bodyHtml") private String bodyHtml = null; @JsonProperty("bodyRtf") private String bodyRtf = null; @JsonProperty("bodyType") private String bodyType = null; @JsonProperty("categories") private List<String> categories = null; @JsonProperty("companies") private List<String> companies = null; @JsonProperty("itemId") private String itemId = null; @JsonProperty("messageClass") private String messageClass = null; @JsonProperty("mileage") private String mileage = null; @JsonProperty("recipients") private List<MapiRecipientDto> recipients = null; @JsonProperty("sensitivity") private String sensitivity = null; @JsonProperty("subject") private String subject = null; @JsonProperty("subjectPrefix") private String subjectPrefix = null; @JsonProperty("properties") private List<MapiPropertyDto> properties = null; @JsonProperty("discriminator") private String discriminator = this.getClass().getSimpleName(); /** * Set attachments and return this. * @param attachments Message item attachments. * @return this **/ public MapiMessageItemBaseDto attachments(List<MapiAttachmentDto> attachments) { this.attachments = attachments; return this; } /** * Add an item to attachments and return this. * @param attachmentsItem An item of: Message item attachments. * @return this **/ public MapiMessageItemBaseDto addAttachmentsItem(MapiAttachmentDto attachmentsItem) { if (this.attachments == null) { this.attachments = new ArrayList<MapiAttachmentDto>(); } this.attachments.add(attachmentsItem); return this; } /** * Message item attachments. * @return attachments **/ public List<MapiAttachmentDto> getAttachments() { return attachments; } /** * Set attachments. * @param attachments Message item attachments. **/ public void setAttachments(List<MapiAttachmentDto> attachments) { this.attachments = attachments; } /** * Set billing and return this. * @param billing Billing information associated with an item. * @return this **/ public MapiMessageItemBaseDto billing(String billing) { this.billing = billing; return this; } /** * Billing information associated with an item. * @return billing **/ public String getBilling() { return billing; } /** * Set billing. * @param billing Billing information associated with an item. **/ public void setBilling(String billing) { this.billing = billing; } /** * Set body and return this. * @param body Message text. * @return this **/ public MapiMessageItemBaseDto body(String body) { this.body = body; return this; } /** * Message text. * @return body **/ public String getBody() { return body; } /** * Set body. * @param body Message text. **/ public void setBody(String body) { this.body = body; } /** * Set bodyHtml and return this. * @param bodyHtml Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. * @return this **/ public MapiMessageItemBaseDto bodyHtml(String bodyHtml) { this.bodyHtml = bodyHtml; return this; } /** * Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. * @return bodyHtml **/ public String getBodyHtml() { return bodyHtml; } /** * Set bodyHtml. * @param bodyHtml Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. **/ public void setBodyHtml(String bodyHtml) { this.bodyHtml = bodyHtml; } /** * Set bodyRtf and return this. * @param bodyRtf RTF formatted message text. * @return this **/ public MapiMessageItemBaseDto bodyRtf(String bodyRtf) { this.bodyRtf = bodyRtf; return this; } /** * RTF formatted message text. * @return bodyRtf **/ public String getBodyRtf() { return bodyRtf; } /** * Set bodyRtf. * @param bodyRtf RTF formatted message text. **/ public void setBodyRtf(String bodyRtf) { this.bodyRtf = bodyRtf; } /** * Set bodyType and return this. * @param bodyType The content type of message body. Enum, available values: PlainText, Html, Rtf * @return this **/ public MapiMessageItemBaseDto bodyType(String bodyType) { this.bodyType = bodyType; return this; } /** * The content type of message body. Enum, available values: PlainText, Html, Rtf * @return bodyType **/ public String getBodyType() { return bodyType; } /** * Set bodyType. * @param bodyType The content type of message body. Enum, available values: PlainText, Html, Rtf **/ public void setBodyType(String bodyType) { this.bodyType = bodyType; } /** * Set categories and return this. * @param categories Contains keywords or categories for the message object. * @return this **/ public MapiMessageItemBaseDto categories(List<String> categories) { this.categories = categories; return this; } /** * Add an item to categories and return this. * @param categoriesItem An item of: Contains keywords or categories for the message object. * @return this **/ public MapiMessageItemBaseDto addCategoriesItem(String categoriesItem) { if (this.categories == null) { this.categories = new ArrayList<String>(); } this.categories.add(categoriesItem); return this; } /** * Contains keywords or categories for the message object. * @return categories **/ public List<String> getCategories() { return categories; } /** * Set categories. * @param categories Contains keywords or categories for the message object. **/ public void setCategories(List<String> categories) { this.categories = categories; } /** * Set companies and return this. * @param companies Contains the names of the companies that are associated with an item. * @return this **/ public MapiMessageItemBaseDto companies(List<String> companies) { this.companies = companies; return this; } /** * Add an item to companies and return this. * @param companiesItem An item of: Contains the names of the companies that are associated with an item. * @return this **/ public MapiMessageItemBaseDto addCompaniesItem(String companiesItem) { if (this.companies == null) { this.companies = new ArrayList<String>(); } this.companies.add(companiesItem); return this; } /** * Contains the names of the companies that are associated with an item. * @return companies **/ public List<String> getCompanies() { return companies; } /** * Set companies. * @param companies Contains the names of the companies that are associated with an item. **/ public void setCompanies(List<String> companies) { this.companies = companies; } /** * Set itemId and return this. * @param itemId The item id, uses with a server. * @return this **/ public MapiMessageItemBaseDto itemId(String itemId) { this.itemId = itemId; return this; } /** * The item id, uses with a server. * @return itemId **/ public String getItemId() { return itemId; } /** * Set itemId. * @param itemId The item id, uses with a server. **/ public void setItemId(String itemId) { this.itemId = itemId; } /** * Set messageClass and return this. * @param messageClass Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. * @return this **/ public MapiMessageItemBaseDto messageClass(String messageClass) { this.messageClass = messageClass; return this; } /** * Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. * @return messageClass **/ public String getMessageClass() { return messageClass; } /** * Set messageClass. * @param messageClass Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. **/ public void setMessageClass(String messageClass) { this.messageClass = messageClass; } /** * Set mileage and return this. * @param mileage Contains the mileage information that is associated with an item. * @return this **/ public MapiMessageItemBaseDto mileage(String mileage) { this.mileage = mileage; return this; } /** * Contains the mileage information that is associated with an item. * @return mileage **/ public String getMileage() { return mileage; } /** * Set mileage. * @param mileage Contains the mileage information that is associated with an item. **/ public void setMileage(String mileage) { this.mileage = mileage; } /** * Set recipients and return this. * @param recipients Recipients of the message. * @return this **/ public MapiMessageItemBaseDto recipients(List<MapiRecipientDto> recipients) { this.recipients = recipients; return this; } /** * Add an item to recipients and return this. * @param recipientsItem An item of: Recipients of the message. * @return this **/ public MapiMessageItemBaseDto addRecipientsItem(MapiRecipientDto recipientsItem) { if (this.recipients == null) { this.recipients = new ArrayList<MapiRecipientDto>(); } this.recipients.add(recipientsItem); return this; } /** * Recipients of the message. * @return recipients **/ public List<MapiRecipientDto> getRecipients() { return recipients; } /** * Set recipients. * @param recipients Recipients of the message. **/ public void setRecipients(List<MapiRecipientDto> recipients) { this.recipients = recipients; } /** * Set sensitivity and return this. * @param sensitivity Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential * @return this **/ public MapiMessageItemBaseDto sensitivity(String sensitivity) { this.sensitivity = sensitivity; return this; } /** * Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential * @return sensitivity **/ public String getSensitivity() { return sensitivity; } /** * Set sensitivity. * @param sensitivity Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential **/ public void setSensitivity(String sensitivity) { this.sensitivity = sensitivity; } /** * Set subject and return this. * @param subject Subject of the message. * @return this **/ public MapiMessageItemBaseDto subject(String subject) { this.subject = subject; return this; } /** * Subject of the message. * @return subject **/ public String getSubject() { return subject; } /** * Set subject. * @param subject Subject of the message. **/ public void setSubject(String subject) { this.subject = subject; } /** * Set subjectPrefix and return this. * @param subjectPrefix Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. * @return this **/ public MapiMessageItemBaseDto subjectPrefix(String subjectPrefix) { this.subjectPrefix = subjectPrefix; return this; } /** * Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. * @return subjectPrefix **/ public String getSubjectPrefix() { return subjectPrefix; } /** * Set subjectPrefix. * @param subjectPrefix Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. **/ public void setSubjectPrefix(String subjectPrefix) { this.subjectPrefix = subjectPrefix; } /** * Set properties and return this. * @param properties List of MAPI properties * @return this **/ public MapiMessageItemBaseDto properties(List<MapiPropertyDto> properties) { this.properties = properties; return this; } /** * Add an item to properties and return this. * @param propertiesItem An item of: List of MAPI properties * @return this **/ public MapiMessageItemBaseDto addPropertiesItem(MapiPropertyDto propertiesItem) { if (this.properties == null) { this.properties = new ArrayList<MapiPropertyDto>(); } this.properties.add(propertiesItem); return this; } /** * List of MAPI properties * @return properties **/ public List<MapiPropertyDto> getProperties() { return properties; } /** * Set properties. * @param properties List of MAPI properties **/ public void setProperties(List<MapiPropertyDto> properties) { this.properties = properties; } /** * Get discriminator * @return discriminator **/ public String getDiscriminator() { return discriminator; } /** * Set discriminator. * @param discriminator **/ public void setDiscriminator(String discriminator) { //do nothing } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MapiMessageItemBaseDto mapiMessageItemBaseDto = (MapiMessageItemBaseDto) o; return ObjectUtils.equals(this.attachments, mapiMessageItemBaseDto.attachments) && ObjectUtils.equals(this.billing, mapiMessageItemBaseDto.billing) && ObjectUtils.equals(this.body, mapiMessageItemBaseDto.body) && ObjectUtils.equals(this.bodyHtml, mapiMessageItemBaseDto.bodyHtml) && ObjectUtils.equals(this.bodyRtf, mapiMessageItemBaseDto.bodyRtf) && ObjectUtils.equals(this.bodyType, mapiMessageItemBaseDto.bodyType) && ObjectUtils.equals(this.categories, mapiMessageItemBaseDto.categories) && ObjectUtils.equals(this.companies, mapiMessageItemBaseDto.companies) && ObjectUtils.equals(this.itemId, mapiMessageItemBaseDto.itemId) && ObjectUtils.equals(this.messageClass, mapiMessageItemBaseDto.messageClass) && ObjectUtils.equals(this.mileage, mapiMessageItemBaseDto.mileage) && ObjectUtils.equals(this.recipients, mapiMessageItemBaseDto.recipients) && ObjectUtils.equals(this.sensitivity, mapiMessageItemBaseDto.sensitivity) && ObjectUtils.equals(this.subject, mapiMessageItemBaseDto.subject) && ObjectUtils.equals(this.subjectPrefix, mapiMessageItemBaseDto.subjectPrefix) && ObjectUtils.equals(this.properties, mapiMessageItemBaseDto.properties) && ObjectUtils.equals(this.discriminator, mapiMessageItemBaseDto.discriminator); } @Override public int hashCode() { return ObjectUtils.hashCodeMulti(attachments, billing, body, bodyHtml, bodyRtf, bodyType, categories, companies, itemId, messageClass, mileage, recipients, sensitivity, subject, subjectPrefix, properties, discriminator); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class MapiMessageItemBaseDto {\n"); sb.append(" attachments: ").append(toIndentedString(getAttachments())).append("\n"); sb.append(" billing: ").append(toIndentedString(getBilling())).append("\n"); sb.append(" body: ").append(toIndentedString(getBody())).append("\n"); sb.append(" bodyHtml: ").append(toIndentedString(getBodyHtml())).append("\n"); sb.append(" bodyRtf: ").append(toIndentedString(getBodyRtf())).append("\n"); sb.append(" bodyType: ").append(toIndentedString(getBodyType())).append("\n"); sb.append(" categories: ").append(toIndentedString(getCategories())).append("\n"); sb.append(" companies: ").append(toIndentedString(getCompanies())).append("\n"); sb.append(" itemId: ").append(toIndentedString(getItemId())).append("\n"); sb.append(" messageClass: ").append(toIndentedString(getMessageClass())).append("\n"); sb.append(" mileage: ").append(toIndentedString(getMileage())).append("\n"); sb.append(" recipients: ").append(toIndentedString(getRecipients())).append("\n"); sb.append(" sensitivity: ").append(toIndentedString(getSensitivity())).append("\n"); sb.append(" subject: ").append(toIndentedString(getSubject())).append("\n"); sb.append(" subjectPrefix: ").append(toIndentedString(getSubjectPrefix())).append("\n"); sb.append(" properties: ").append(toIndentedString(getProperties())).append("\n"); sb.append(" discriminator: ").append(toIndentedString(getDiscriminator())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } public MapiMessageItemBaseDto() { super(); } /** * Initializes a new instance of the MapiMessageItemBaseDto * @param attachments Message item attachments. * @param billing Billing information associated with an item. * @param body Message text. * @param bodyHtml Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. * @param bodyRtf RTF formatted message text. * @param bodyType The content type of message body. Enum, available values: PlainText, Html, Rtf * @param categories Contains keywords or categories for the message object. * @param companies Contains the names of the companies that are associated with an item. * @param itemId The item id, uses with a server. * @param messageClass Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. * @param mileage Contains the mileage information that is associated with an item. * @param recipients Recipients of the message. * @param sensitivity Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential * @param subject Subject of the message. * @param subjectPrefix Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. * @param properties List of MAPI properties */ public MapiMessageItemBaseDto( List<MapiAttachmentDto> attachments, String billing, String body, String bodyHtml, String bodyRtf, String bodyType, List<String> categories, List<String> companies, String itemId, String messageClass, String mileage, List<MapiRecipientDto> recipients, String sensitivity, String subject, String subjectPrefix, List<MapiPropertyDto> properties ) { super(); setAttachments(attachments); setBilling(billing); setBody(body); setBodyHtml(bodyHtml); setBodyRtf(bodyRtf); setBodyType(bodyType); setCategories(categories); setCompanies(companies); setItemId(itemId); setMessageClass(messageClass); setMileage(mileage); setRecipients(recipients); setSensitivity(sensitivity); setSubject(subject); setSubjectPrefix(subjectPrefix); setProperties(properties); } }
UTF-8
Java
22,555
java
MapiMessageItemBaseDto.java
Java
[]
null
[]
/* * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose" file="MapiMessageItemBaseDto.java"> * Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved. * </copyright> * <summary> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ package com.aspose.email.cloud.sdk.model; import org.apache.commons.lang3.ObjectUtils; import java.util.Date; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.*; import com.google.gson.*; import com.google.gson.stream.*; import java.io.*; /** * Base Dto for MapiMessage, MapiCalendar or MapiContact */ public class MapiMessageItemBaseDto { @JsonProperty("attachments") private List<MapiAttachmentDto> attachments = null; @JsonProperty("billing") private String billing = null; @JsonProperty("body") private String body = null; @JsonProperty("bodyHtml") private String bodyHtml = null; @JsonProperty("bodyRtf") private String bodyRtf = null; @JsonProperty("bodyType") private String bodyType = null; @JsonProperty("categories") private List<String> categories = null; @JsonProperty("companies") private List<String> companies = null; @JsonProperty("itemId") private String itemId = null; @JsonProperty("messageClass") private String messageClass = null; @JsonProperty("mileage") private String mileage = null; @JsonProperty("recipients") private List<MapiRecipientDto> recipients = null; @JsonProperty("sensitivity") private String sensitivity = null; @JsonProperty("subject") private String subject = null; @JsonProperty("subjectPrefix") private String subjectPrefix = null; @JsonProperty("properties") private List<MapiPropertyDto> properties = null; @JsonProperty("discriminator") private String discriminator = this.getClass().getSimpleName(); /** * Set attachments and return this. * @param attachments Message item attachments. * @return this **/ public MapiMessageItemBaseDto attachments(List<MapiAttachmentDto> attachments) { this.attachments = attachments; return this; } /** * Add an item to attachments and return this. * @param attachmentsItem An item of: Message item attachments. * @return this **/ public MapiMessageItemBaseDto addAttachmentsItem(MapiAttachmentDto attachmentsItem) { if (this.attachments == null) { this.attachments = new ArrayList<MapiAttachmentDto>(); } this.attachments.add(attachmentsItem); return this; } /** * Message item attachments. * @return attachments **/ public List<MapiAttachmentDto> getAttachments() { return attachments; } /** * Set attachments. * @param attachments Message item attachments. **/ public void setAttachments(List<MapiAttachmentDto> attachments) { this.attachments = attachments; } /** * Set billing and return this. * @param billing Billing information associated with an item. * @return this **/ public MapiMessageItemBaseDto billing(String billing) { this.billing = billing; return this; } /** * Billing information associated with an item. * @return billing **/ public String getBilling() { return billing; } /** * Set billing. * @param billing Billing information associated with an item. **/ public void setBilling(String billing) { this.billing = billing; } /** * Set body and return this. * @param body Message text. * @return this **/ public MapiMessageItemBaseDto body(String body) { this.body = body; return this; } /** * Message text. * @return body **/ public String getBody() { return body; } /** * Set body. * @param body Message text. **/ public void setBody(String body) { this.body = body; } /** * Set bodyHtml and return this. * @param bodyHtml Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. * @return this **/ public MapiMessageItemBaseDto bodyHtml(String bodyHtml) { this.bodyHtml = bodyHtml; return this; } /** * Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. * @return bodyHtml **/ public String getBodyHtml() { return bodyHtml; } /** * Set bodyHtml. * @param bodyHtml Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. **/ public void setBodyHtml(String bodyHtml) { this.bodyHtml = bodyHtml; } /** * Set bodyRtf and return this. * @param bodyRtf RTF formatted message text. * @return this **/ public MapiMessageItemBaseDto bodyRtf(String bodyRtf) { this.bodyRtf = bodyRtf; return this; } /** * RTF formatted message text. * @return bodyRtf **/ public String getBodyRtf() { return bodyRtf; } /** * Set bodyRtf. * @param bodyRtf RTF formatted message text. **/ public void setBodyRtf(String bodyRtf) { this.bodyRtf = bodyRtf; } /** * Set bodyType and return this. * @param bodyType The content type of message body. Enum, available values: PlainText, Html, Rtf * @return this **/ public MapiMessageItemBaseDto bodyType(String bodyType) { this.bodyType = bodyType; return this; } /** * The content type of message body. Enum, available values: PlainText, Html, Rtf * @return bodyType **/ public String getBodyType() { return bodyType; } /** * Set bodyType. * @param bodyType The content type of message body. Enum, available values: PlainText, Html, Rtf **/ public void setBodyType(String bodyType) { this.bodyType = bodyType; } /** * Set categories and return this. * @param categories Contains keywords or categories for the message object. * @return this **/ public MapiMessageItemBaseDto categories(List<String> categories) { this.categories = categories; return this; } /** * Add an item to categories and return this. * @param categoriesItem An item of: Contains keywords or categories for the message object. * @return this **/ public MapiMessageItemBaseDto addCategoriesItem(String categoriesItem) { if (this.categories == null) { this.categories = new ArrayList<String>(); } this.categories.add(categoriesItem); return this; } /** * Contains keywords or categories for the message object. * @return categories **/ public List<String> getCategories() { return categories; } /** * Set categories. * @param categories Contains keywords or categories for the message object. **/ public void setCategories(List<String> categories) { this.categories = categories; } /** * Set companies and return this. * @param companies Contains the names of the companies that are associated with an item. * @return this **/ public MapiMessageItemBaseDto companies(List<String> companies) { this.companies = companies; return this; } /** * Add an item to companies and return this. * @param companiesItem An item of: Contains the names of the companies that are associated with an item. * @return this **/ public MapiMessageItemBaseDto addCompaniesItem(String companiesItem) { if (this.companies == null) { this.companies = new ArrayList<String>(); } this.companies.add(companiesItem); return this; } /** * Contains the names of the companies that are associated with an item. * @return companies **/ public List<String> getCompanies() { return companies; } /** * Set companies. * @param companies Contains the names of the companies that are associated with an item. **/ public void setCompanies(List<String> companies) { this.companies = companies; } /** * Set itemId and return this. * @param itemId The item id, uses with a server. * @return this **/ public MapiMessageItemBaseDto itemId(String itemId) { this.itemId = itemId; return this; } /** * The item id, uses with a server. * @return itemId **/ public String getItemId() { return itemId; } /** * Set itemId. * @param itemId The item id, uses with a server. **/ public void setItemId(String itemId) { this.itemId = itemId; } /** * Set messageClass and return this. * @param messageClass Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. * @return this **/ public MapiMessageItemBaseDto messageClass(String messageClass) { this.messageClass = messageClass; return this; } /** * Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. * @return messageClass **/ public String getMessageClass() { return messageClass; } /** * Set messageClass. * @param messageClass Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. **/ public void setMessageClass(String messageClass) { this.messageClass = messageClass; } /** * Set mileage and return this. * @param mileage Contains the mileage information that is associated with an item. * @return this **/ public MapiMessageItemBaseDto mileage(String mileage) { this.mileage = mileage; return this; } /** * Contains the mileage information that is associated with an item. * @return mileage **/ public String getMileage() { return mileage; } /** * Set mileage. * @param mileage Contains the mileage information that is associated with an item. **/ public void setMileage(String mileage) { this.mileage = mileage; } /** * Set recipients and return this. * @param recipients Recipients of the message. * @return this **/ public MapiMessageItemBaseDto recipients(List<MapiRecipientDto> recipients) { this.recipients = recipients; return this; } /** * Add an item to recipients and return this. * @param recipientsItem An item of: Recipients of the message. * @return this **/ public MapiMessageItemBaseDto addRecipientsItem(MapiRecipientDto recipientsItem) { if (this.recipients == null) { this.recipients = new ArrayList<MapiRecipientDto>(); } this.recipients.add(recipientsItem); return this; } /** * Recipients of the message. * @return recipients **/ public List<MapiRecipientDto> getRecipients() { return recipients; } /** * Set recipients. * @param recipients Recipients of the message. **/ public void setRecipients(List<MapiRecipientDto> recipients) { this.recipients = recipients; } /** * Set sensitivity and return this. * @param sensitivity Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential * @return this **/ public MapiMessageItemBaseDto sensitivity(String sensitivity) { this.sensitivity = sensitivity; return this; } /** * Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential * @return sensitivity **/ public String getSensitivity() { return sensitivity; } /** * Set sensitivity. * @param sensitivity Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential **/ public void setSensitivity(String sensitivity) { this.sensitivity = sensitivity; } /** * Set subject and return this. * @param subject Subject of the message. * @return this **/ public MapiMessageItemBaseDto subject(String subject) { this.subject = subject; return this; } /** * Subject of the message. * @return subject **/ public String getSubject() { return subject; } /** * Set subject. * @param subject Subject of the message. **/ public void setSubject(String subject) { this.subject = subject; } /** * Set subjectPrefix and return this. * @param subjectPrefix Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. * @return this **/ public MapiMessageItemBaseDto subjectPrefix(String subjectPrefix) { this.subjectPrefix = subjectPrefix; return this; } /** * Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. * @return subjectPrefix **/ public String getSubjectPrefix() { return subjectPrefix; } /** * Set subjectPrefix. * @param subjectPrefix Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. **/ public void setSubjectPrefix(String subjectPrefix) { this.subjectPrefix = subjectPrefix; } /** * Set properties and return this. * @param properties List of MAPI properties * @return this **/ public MapiMessageItemBaseDto properties(List<MapiPropertyDto> properties) { this.properties = properties; return this; } /** * Add an item to properties and return this. * @param propertiesItem An item of: List of MAPI properties * @return this **/ public MapiMessageItemBaseDto addPropertiesItem(MapiPropertyDto propertiesItem) { if (this.properties == null) { this.properties = new ArrayList<MapiPropertyDto>(); } this.properties.add(propertiesItem); return this; } /** * List of MAPI properties * @return properties **/ public List<MapiPropertyDto> getProperties() { return properties; } /** * Set properties. * @param properties List of MAPI properties **/ public void setProperties(List<MapiPropertyDto> properties) { this.properties = properties; } /** * Get discriminator * @return discriminator **/ public String getDiscriminator() { return discriminator; } /** * Set discriminator. * @param discriminator **/ public void setDiscriminator(String discriminator) { //do nothing } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MapiMessageItemBaseDto mapiMessageItemBaseDto = (MapiMessageItemBaseDto) o; return ObjectUtils.equals(this.attachments, mapiMessageItemBaseDto.attachments) && ObjectUtils.equals(this.billing, mapiMessageItemBaseDto.billing) && ObjectUtils.equals(this.body, mapiMessageItemBaseDto.body) && ObjectUtils.equals(this.bodyHtml, mapiMessageItemBaseDto.bodyHtml) && ObjectUtils.equals(this.bodyRtf, mapiMessageItemBaseDto.bodyRtf) && ObjectUtils.equals(this.bodyType, mapiMessageItemBaseDto.bodyType) && ObjectUtils.equals(this.categories, mapiMessageItemBaseDto.categories) && ObjectUtils.equals(this.companies, mapiMessageItemBaseDto.companies) && ObjectUtils.equals(this.itemId, mapiMessageItemBaseDto.itemId) && ObjectUtils.equals(this.messageClass, mapiMessageItemBaseDto.messageClass) && ObjectUtils.equals(this.mileage, mapiMessageItemBaseDto.mileage) && ObjectUtils.equals(this.recipients, mapiMessageItemBaseDto.recipients) && ObjectUtils.equals(this.sensitivity, mapiMessageItemBaseDto.sensitivity) && ObjectUtils.equals(this.subject, mapiMessageItemBaseDto.subject) && ObjectUtils.equals(this.subjectPrefix, mapiMessageItemBaseDto.subjectPrefix) && ObjectUtils.equals(this.properties, mapiMessageItemBaseDto.properties) && ObjectUtils.equals(this.discriminator, mapiMessageItemBaseDto.discriminator); } @Override public int hashCode() { return ObjectUtils.hashCodeMulti(attachments, billing, body, bodyHtml, bodyRtf, bodyType, categories, companies, itemId, messageClass, mileage, recipients, sensitivity, subject, subjectPrefix, properties, discriminator); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class MapiMessageItemBaseDto {\n"); sb.append(" attachments: ").append(toIndentedString(getAttachments())).append("\n"); sb.append(" billing: ").append(toIndentedString(getBilling())).append("\n"); sb.append(" body: ").append(toIndentedString(getBody())).append("\n"); sb.append(" bodyHtml: ").append(toIndentedString(getBodyHtml())).append("\n"); sb.append(" bodyRtf: ").append(toIndentedString(getBodyRtf())).append("\n"); sb.append(" bodyType: ").append(toIndentedString(getBodyType())).append("\n"); sb.append(" categories: ").append(toIndentedString(getCategories())).append("\n"); sb.append(" companies: ").append(toIndentedString(getCompanies())).append("\n"); sb.append(" itemId: ").append(toIndentedString(getItemId())).append("\n"); sb.append(" messageClass: ").append(toIndentedString(getMessageClass())).append("\n"); sb.append(" mileage: ").append(toIndentedString(getMileage())).append("\n"); sb.append(" recipients: ").append(toIndentedString(getRecipients())).append("\n"); sb.append(" sensitivity: ").append(toIndentedString(getSensitivity())).append("\n"); sb.append(" subject: ").append(toIndentedString(getSubject())).append("\n"); sb.append(" subjectPrefix: ").append(toIndentedString(getSubjectPrefix())).append("\n"); sb.append(" properties: ").append(toIndentedString(getProperties())).append("\n"); sb.append(" discriminator: ").append(toIndentedString(getDiscriminator())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } public MapiMessageItemBaseDto() { super(); } /** * Initializes a new instance of the MapiMessageItemBaseDto * @param attachments Message item attachments. * @param billing Billing information associated with an item. * @param body Message text. * @param bodyHtml Gets the BodyRtf of the message converted to HTML, if present, otherwise an empty string. * @param bodyRtf RTF formatted message text. * @param bodyType The content type of message body. Enum, available values: PlainText, Html, Rtf * @param categories Contains keywords or categories for the message object. * @param companies Contains the names of the companies that are associated with an item. * @param itemId The item id, uses with a server. * @param messageClass Case-sensitive string that identifies the sender-defined message class, such as IPM.Note. The message class specifies the type, purpose, or content of the message. * @param mileage Contains the mileage information that is associated with an item. * @param recipients Recipients of the message. * @param sensitivity Contains values that indicate the message sensitivity. Enum, available values: None, Personal, Private, CompanyConfidential * @param subject Subject of the message. * @param subjectPrefix Subject prefix that typically indicates some action on a message, such as \&quot;FW: \&quot; for forwarding. * @param properties List of MAPI properties */ public MapiMessageItemBaseDto( List<MapiAttachmentDto> attachments, String billing, String body, String bodyHtml, String bodyRtf, String bodyType, List<String> categories, List<String> companies, String itemId, String messageClass, String mileage, List<MapiRecipientDto> recipients, String sensitivity, String subject, String subjectPrefix, List<MapiPropertyDto> properties ) { super(); setAttachments(attachments); setBilling(billing); setBody(body); setBodyHtml(bodyHtml); setBodyRtf(bodyRtf); setBodyType(bodyType); setCategories(categories); setCompanies(companies); setItemId(itemId); setMessageClass(messageClass); setMileage(mileage); setRecipients(recipients); setSensitivity(sensitivity); setSubject(subject); setSubjectPrefix(subjectPrefix); setProperties(properties); } }
22,555
0.664332
0.663888
723
30.195021
33.463043
224
false
false
0
0
0
0
0
0
0.405256
false
false
7
ff4ca564f7bfa3e273d85d9f9893b4af27659ea0
33,105,607,927,217
d6e2631364c9a9181712491f589b00a4a8d4b430
/src/main/java/mycompany/api/image/api/domain/ImageResponse.java
5a1a405473bfebd35669cdb58bdbd4f3cb7f92b0
[]
no_license
Anatolijs/image.api
https://github.com/Anatolijs/image.api
24abd479ee57e93d07740dfeb48958e0eb822490
3e2aa2d5ce87858ac941a48ffb0c2761ba132c2e
refs/heads/master
2020-03-15T00:24:49.369000
2018-05-24T09:25:24
2018-05-24T09:25:24
131,867,741
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mycompany.api.image.api.domain; import java.util.List; public class ImageResponse { public Integer id; public String name; public List<String> tags; }
UTF-8
Java
173
java
ImageResponse.java
Java
[]
null
[]
package mycompany.api.image.api.domain; import java.util.List; public class ImageResponse { public Integer id; public String name; public List<String> tags; }
173
0.728324
0.728324
9
18.222221
13.56284
39
false
false
0
0
0
0
0
0
0.555556
false
false
7
4a6e0f9f42179bbb180cda45bec4cfdae220860a
6,674,379,188,873
bd0dce309fb916c78e98b5cb55b954e571a0af8e
/src/main/java/com/wxy/dg/modules/controller/NoticeAction.java
d2a3374f0b6e3bbd9692a931f6343eaa294c7e80
[]
no_license
942391815/kycws
https://github.com/942391815/kycws
3242a16ab714574f2c991245e78f4ed5cc9ce844
12d45a332f691b2a4bc5e5d30c20501aac31afdb
refs/heads/master
2021-04-27T00:11:56.256000
2018-06-09T08:21:12
2018-06-09T08:21:12
123,768,370
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wxy.dg.modules.controller; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.wxy.dg.common.base.BaseAction; import com.wxy.dg.common.util.CommonUtil; import com.wxy.dg.common.util.DateUtils; import com.wxy.dg.common.util.Page; import com.wxy.dg.modules.model.Notice; import com.wxy.dg.modules.model.Organization; import com.wxy.dg.modules.model.User; import com.wxy.dg.modules.service.NoticeService; import com.wxy.dg.modules.service.OrgService; import com.wxy.dg.modules.service.UserService; /** * 通知管理 */ @Controller public class NoticeAction extends BaseAction { @Autowired private NoticeService noticeService; @Autowired private UserService userService; @Autowired private OrgService orgService; @ModelAttribute public Notice get(@RequestParam(required=false) String id) { if (StringUtils.isNotBlank(id) && !"0".equals(id)){ return noticeService.getById(Integer.parseInt(id)); }else{ return new Notice(); } } @RequestMapping("/noticelist") public String list(HttpServletRequest request, HttpServletResponse response, Model model) { Page<Notice> page = noticeService.findNotice(new Page<Notice>(request, response)); model.addAttribute("page", page); return "modules/noticeList"; } @RequestMapping("/notice/manage") public String form(Model model) { List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); List<Organization> list = orgService.getAllValid(); for (int i=0; i<list.size(); i++){ Organization e = list.get(i); Map<String, Object> map = new HashMap<String, Object> (); map.put("id", e.getId()); map.put("pId", e.getParent() != null ? e.getParent().getId() : 0); map.put("name", e.getName()); map.put("isParent", true); mapList.add(map); } model.addAttribute("orglist",mapList); return "modules/noticeManage"; } @RequestMapping("/notice/push") public String push(Notice notice, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, notice)) { return form(model); } String objIds = notice.getObjIds(); String[] obj = objIds.split(","); List<User> pushUsers = new ArrayList<User>(); for(int i=0;i<obj.length;i++) { int userId = Integer.valueOf(obj[i]); User user = userService.getUser(userId); pushUsers.add(user); } // 通知推送 CommonUtil.pushMsg(notice.getTitle(), notice.getContent(), pushUsers); notice.setSend_time(new Date()); notice.setObjIds(","+objIds+","); noticeService.save(notice); addMessage(redirectAttributes, "通知已发布,发送对象"+pushUsers.size()+"人!"); return "redirect:/noticelist"; } @RequestMapping("/notice/delete") public String delete(String id, RedirectAttributes redirectAttributes) { noticeService.delete(noticeService.getById(Integer.valueOf(id))); addMessage(redirectAttributes,"删除通知成功"); return "redirect:/noticelist"; } @RequestMapping("/mobile/notice") public void getNoticeList(@RequestParam Integer userId, HttpServletResponse response) { List<Notice> noticeList = noticeService.getUserNotices(userId); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for(Notice notice:noticeList) { Map<String, Object> noticeMap = new HashMap<String, Object>(); noticeMap.put("title", notice.getTitle()); noticeMap.put("content", notice.getContent()); noticeMap.put("date", DateUtils.formatDate(notice.getSend_time())); list.add(noticeMap); } Map<String, Object> map = new HashMap<String, Object>(); map.put("response", "notice"); map.put("notice", list); toJsonString(response, map); } }
UTF-8
Java
4,267
java
NoticeAction.java
Java
[]
null
[]
package com.wxy.dg.modules.controller; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.wxy.dg.common.base.BaseAction; import com.wxy.dg.common.util.CommonUtil; import com.wxy.dg.common.util.DateUtils; import com.wxy.dg.common.util.Page; import com.wxy.dg.modules.model.Notice; import com.wxy.dg.modules.model.Organization; import com.wxy.dg.modules.model.User; import com.wxy.dg.modules.service.NoticeService; import com.wxy.dg.modules.service.OrgService; import com.wxy.dg.modules.service.UserService; /** * 通知管理 */ @Controller public class NoticeAction extends BaseAction { @Autowired private NoticeService noticeService; @Autowired private UserService userService; @Autowired private OrgService orgService; @ModelAttribute public Notice get(@RequestParam(required=false) String id) { if (StringUtils.isNotBlank(id) && !"0".equals(id)){ return noticeService.getById(Integer.parseInt(id)); }else{ return new Notice(); } } @RequestMapping("/noticelist") public String list(HttpServletRequest request, HttpServletResponse response, Model model) { Page<Notice> page = noticeService.findNotice(new Page<Notice>(request, response)); model.addAttribute("page", page); return "modules/noticeList"; } @RequestMapping("/notice/manage") public String form(Model model) { List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); List<Organization> list = orgService.getAllValid(); for (int i=0; i<list.size(); i++){ Organization e = list.get(i); Map<String, Object> map = new HashMap<String, Object> (); map.put("id", e.getId()); map.put("pId", e.getParent() != null ? e.getParent().getId() : 0); map.put("name", e.getName()); map.put("isParent", true); mapList.add(map); } model.addAttribute("orglist",mapList); return "modules/noticeManage"; } @RequestMapping("/notice/push") public String push(Notice notice, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, notice)) { return form(model); } String objIds = notice.getObjIds(); String[] obj = objIds.split(","); List<User> pushUsers = new ArrayList<User>(); for(int i=0;i<obj.length;i++) { int userId = Integer.valueOf(obj[i]); User user = userService.getUser(userId); pushUsers.add(user); } // 通知推送 CommonUtil.pushMsg(notice.getTitle(), notice.getContent(), pushUsers); notice.setSend_time(new Date()); notice.setObjIds(","+objIds+","); noticeService.save(notice); addMessage(redirectAttributes, "通知已发布,发送对象"+pushUsers.size()+"人!"); return "redirect:/noticelist"; } @RequestMapping("/notice/delete") public String delete(String id, RedirectAttributes redirectAttributes) { noticeService.delete(noticeService.getById(Integer.valueOf(id))); addMessage(redirectAttributes,"删除通知成功"); return "redirect:/noticelist"; } @RequestMapping("/mobile/notice") public void getNoticeList(@RequestParam Integer userId, HttpServletResponse response) { List<Notice> noticeList = noticeService.getUserNotices(userId); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for(Notice notice:noticeList) { Map<String, Object> noticeMap = new HashMap<String, Object>(); noticeMap.put("title", notice.getTitle()); noticeMap.put("content", notice.getContent()); noticeMap.put("date", DateUtils.formatDate(notice.getSend_time())); list.add(noticeMap); } Map<String, Object> map = new HashMap<String, Object>(); map.put("response", "notice"); map.put("notice", list); toJsonString(response, map); } }
4,267
0.735008
0.733823
124
33.032257
23.642477
92
false
false
0
0
0
0
0
0
2.104839
false
false
7
263faba26ec4bc1a7669920f29e7c960f47f829b
20,495,583,946,551
ae9c41bd9d9499debf864546068de9e1d1627b2a
/LeetCode/Problem654.java
64cf41e0c61bbd88d78767da96786704b1d456ba
[]
no_license
wangzaiaaa/implement-some-algorithms-and-data-structure
https://github.com/wangzaiaaa/implement-some-algorithms-and-data-structure
8b31418e4b7e9d7fde30d6ca71ec8ed95947b5cf
b8d934cb8e8337762323020f9f25dad535c74996
refs/heads/master
2020-04-17T17:26:24.687000
2019-07-20T09:14:48
2019-07-20T09:14:48
166,782,131
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; } * } */ class Problem654 { public TreeNode constructMaximumBinaryTree(int[] nums) { if(nums==null||nums.length<1) return null; return constructMaximumBinaryTree(nums,0,nums.length-1); } public TreeNode constructMaximumBinaryTree(int [] nums,int start,int end){ if(start>end) return null; int index = maxindex(nums,start,end); TreeNode node = new TreeNode(nums[index]); node.left = constructMaximumBinaryTree(nums,start,index-1); node.right = constructMaximumBinaryTree(nums,index+1,end); return node; } public int maxindex(int [] nums,int start,int end){ int index = start,max_value = nums[start]; for(int i = start;i<=end;i++){ if(nums[i]>max_value){ max_value = nums[i]; index = i; } } return index; } }
UTF-8
Java
1,048
java
Problem654.java
Java
[]
null
[]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Problem654 { public TreeNode constructMaximumBinaryTree(int[] nums) { if(nums==null||nums.length<1) return null; return constructMaximumBinaryTree(nums,0,nums.length-1); } public TreeNode constructMaximumBinaryTree(int [] nums,int start,int end){ if(start>end) return null; int index = maxindex(nums,start,end); TreeNode node = new TreeNode(nums[index]); node.left = constructMaximumBinaryTree(nums,start,index-1); node.right = constructMaximumBinaryTree(nums,index+1,end); return node; } public int maxindex(int [] nums,int start,int end){ int index = start,max_value = nums[start]; for(int i = start;i<=end;i++){ if(nums[i]>max_value){ max_value = nums[i]; index = i; } } return index; } }
1,048
0.584924
0.57729
33
30.787878
21.719643
78
false
false
0
0
0
0
0
0
1
false
false
7
353e90860688d32c4d1a2df7fde2db9d44d47c15
8,907,762,182,256
62a5c16ee723aabf754f7095d09b49bbc4614f37
/src/de/cachehound/imp/mail/DummyGCMailHandler.java
9de8ca5cb17911fa26370c26762dc992b231ac6a
[]
no_license
arbor95/cachehound
https://github.com/arbor95/cachehound
84c278d0da519fb4573877114445122c1cfc9aa7
fc9a5ac05eedb9ae9b87af502913c820e852f0d0
refs/heads/master
2021-01-19T07:49:24.027000
2010-01-21T20:59:39
2010-01-21T20:59:39
40,202,642
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.cachehound.imp.mail; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.MimeBodyPart; public class DummyGCMailHandler implements IGCMailHandler { /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#archived(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean archived(String gcNumber, Message message, String subject, String text) { System.out.println("archived " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#published(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean published(String gcNumber, Message message, String subject, String text) { System.out.println("published " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#enabled(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean enabled(String gcNumber, Message message, String subject, String text) { System.out.println("enabled " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#unarchived(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean unarchived(String gcNumber, Message message, String subject, String text) { System.out.println("unarchived " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#retracted(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean retracted(String gcNumber, Message message, String subject, String text) { System.out.println("retracted " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#disabled(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean disabled(String gcNumber, Message message, String subject, String text) { System.out.println("disabled " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#found(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean found(String gcNumber, Message message, String subject, String text) { System.out.println("found " + gcNumber); return false; } /* * (non-Javadoc) * * @see * de.flopl.geocaching.mail.IGCMailHandler#didNotFound(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean didNotFound(String gcNumber, Message message, String subject, String text) { System.out.println("didNotFound " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#updated(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean updated(String gcNumber, Message message, String subject, String text) { System.out.println("updated " + gcNumber); return false; } /* * (non-Javadoc) * * @see * de.flopl.geocaching.mail.IGCMailHandler#needMaintenance(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean needMaintenance(String gcNumber, Message message, String subject, String text) { System.out.println("needMaintenance " + gcNumber); return false; } /* * (non-Javadoc) * * @see * de.flopl.geocaching.mail.IGCMailHandler#handlePocketQuery(javax.mail. * Message, java.lang.String) */ public boolean handlePocketQuery(Message message, String subject) throws MessagingException, IOException { Multipart mp = (Multipart) message.getContent(); for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mimePart = (MimeBodyPart) part; System.out.println("PQuery " + j + ": " + mimePart.getContentType()); // if (mimePart.isMimeType("text/plain")) { // BufferedReader in = new BufferedReader( // new InputStreamReader(mimePart.getInputStream())); // // for (String line; (line = in.readLine()) != null;) // System.out.println(" " + line); // } if (mimePart.isMimeType("APPLICATION/ZIP")) { InputStream in = mimePart.getInputStream(); ZipInputStream zipIn = new ZipInputStream(in); System.out.println("Found ZIP"); ZipEntry entry; while (null != (entry = zipIn.getNextEntry())) { System.out.println(" Dateiname: " + entry.getName()); } } } } System.out.println("PPQ: " + subject); return false; } @Override public boolean maintenancePerformed(String gcNumber, Message message, String subject, String text) { System.out.println("performed Maintenance " + gcNumber); return false; } }
UTF-8
Java
5,150
java
DummyGCMailHandler.java
Java
[]
null
[]
package de.cachehound.imp.mail; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.MimeBodyPart; public class DummyGCMailHandler implements IGCMailHandler { /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#archived(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean archived(String gcNumber, Message message, String subject, String text) { System.out.println("archived " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#published(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean published(String gcNumber, Message message, String subject, String text) { System.out.println("published " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#enabled(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean enabled(String gcNumber, Message message, String subject, String text) { System.out.println("enabled " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#unarchived(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean unarchived(String gcNumber, Message message, String subject, String text) { System.out.println("unarchived " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#retracted(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean retracted(String gcNumber, Message message, String subject, String text) { System.out.println("retracted " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#disabled(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean disabled(String gcNumber, Message message, String subject, String text) { System.out.println("disabled " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#found(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean found(String gcNumber, Message message, String subject, String text) { System.out.println("found " + gcNumber); return false; } /* * (non-Javadoc) * * @see * de.flopl.geocaching.mail.IGCMailHandler#didNotFound(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean didNotFound(String gcNumber, Message message, String subject, String text) { System.out.println("didNotFound " + gcNumber); return false; } /* * (non-Javadoc) * * @see de.flopl.geocaching.mail.IGCMailHandler#updated(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean updated(String gcNumber, Message message, String subject, String text) { System.out.println("updated " + gcNumber); return false; } /* * (non-Javadoc) * * @see * de.flopl.geocaching.mail.IGCMailHandler#needMaintenance(java.lang.String, * javax.mail.Message, java.lang.String, java.lang.String) */ public boolean needMaintenance(String gcNumber, Message message, String subject, String text) { System.out.println("needMaintenance " + gcNumber); return false; } /* * (non-Javadoc) * * @see * de.flopl.geocaching.mail.IGCMailHandler#handlePocketQuery(javax.mail. * Message, java.lang.String) */ public boolean handlePocketQuery(Message message, String subject) throws MessagingException, IOException { Multipart mp = (Multipart) message.getContent(); for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mimePart = (MimeBodyPart) part; System.out.println("PQuery " + j + ": " + mimePart.getContentType()); // if (mimePart.isMimeType("text/plain")) { // BufferedReader in = new BufferedReader( // new InputStreamReader(mimePart.getInputStream())); // // for (String line; (line = in.readLine()) != null;) // System.out.println(" " + line); // } if (mimePart.isMimeType("APPLICATION/ZIP")) { InputStream in = mimePart.getInputStream(); ZipInputStream zipIn = new ZipInputStream(in); System.out.println("Found ZIP"); ZipEntry entry; while (null != (entry = zipIn.getNextEntry())) { System.out.println(" Dateiname: " + entry.getName()); } } } } System.out.println("PPQ: " + subject); return false; } @Override public boolean maintenancePerformed(String gcNumber, Message message, String subject, String text) { System.out.println("performed Maintenance " + gcNumber); return false; } }
5,150
0.69534
0.695146
188
26.393618
25.465963
77
false
false
0
0
0
0
0
0
2.117021
false
false
7
9a8e92eea93a6583d8d22328e848d22b37dc66d5
20,186,346,303,532
e58375bdc94b48f828b7f8ded6cd0d4174216918
/java/codejam/y2012/round1c/C.java
990a145382ff0d1084237be6b8c8cbc336223c37
[]
no_license
tedkim81/algorithm-study
https://github.com/tedkim81/algorithm-study
eb43ffaf9b072c98910fee6e34ed528397d989f7
541115544dea589c9c5226eccd96e1f39bef1dfb
refs/heads/master
2021-06-05T10:45:39.240000
2021-05-01T16:09:20
2021-05-01T16:09:20
133,684,139
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gcj.y2012.round1c; import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; /** * Problem C. Box Factory * * 타입이 일치하는 경우 포장을 하고 재귀호출, 그렇지 않은 경우 A타입을 버리거나, B타입을 버리고 재귀호출하여 * 결과들 중 최대값을 리턴하는 방식으로 구현했는데 오답처리되었다. * 문제는 메모이제이션에 있었다. a, b 가 전역변수이면서 변경되고 있기 때문에 관련하여 적용해야 하는데 이것이 꽤 어려웠다. * 메모이제이션을 빼고, 타입이 일치하는 경우는 무조건 포장을 한다고 가정을 하니 small input은 풀렸다. * 다시 말해서, 타입이 일치하는데 박스나 토이를 그냥 버리는 경우에는 최대값이 나올 수 없다는 것이다. * * 이제 large input을 해결하기 위해서는 메모이제이션이 필요하다. analysis를 확인해보자. * analysis 누가 썼는지.. 참.. 별로다. 어찌됐건 Longest Common Subsequence 문제의 변형이라는 정도(?)는 알았다. * 내가 사용한 알고리즘과 크게 다르지 않다. 그렇다면 다시.. 내 알고리즘 안에서 문제를 해결해보자. * 현재 solve()의 문제는 memo[ab][change][aidx][bidx] 에서 서로 다른 경우인데 4개의 값이 모두 같은 경우가 존재한다는 것이다. * 타입이 일치하지 않을때 change값을 다음으로 넘기기 때문에 change값이 같지만 실제로 a[aidx]( 또는 b[bidx] )가 다른 경우가 있을 수 있다. * solution 을 확인해보자. * * analysis와 solution을 여러차례 하루종일 들여다보면서 간신히 해법을 이해할 수 있었다. * 역시.. 그림을 그려서 간단히 시뮬레이션을 해보는게 굉장히 중요하다는 것을 새삼 깨달았다. * 두 라인의 타입이 같은 경우 단순히 다음으로 넘길 수 없다는 것을 깨달아야 한다. * 다행히 두 라인의 물건 개수가 같다면 다음으로 바로 넘길 수 있겠지만 그렇지 않은 경우들을 모두 포괄하는 일반적인 알고리즘을 만들어야 한다. * 두 라인 물건의 개수가 다르다면 적은 개수만큼 완성하고 남은 개수를 버릴지 다른 라인에서 같은 타입이 나올때까지 기다려야 할지에 따라 다양한 경우의 수가 발생한다. * A[aidx]==B[bidx]==T 라고 한다면, aidx<aidx2, bidx<bidx2 인 모든 aidx2,bidx2에 대하여 aidx~aidx2, bidx~bidx2구간에서 T타입인 완성품수와 * 그 다음 구간에 대한 부분문제 호출결과의 합의 최대값을 구하면 되는 것이다. * 여기서 이해하기 어려웠던 부분은 왜 모든 구간에 대해 T타입인 완성품수만 구하느냐는 것이었다. 이것은 귀류법으로 설명이 가능하다. * T타입이 아닌 U타입에 대해서도 완성품수를 계산하도록 하는 경우는, U타입으로 시작하는 부분문제와 그 이전에 대해서는 T타입의 완성품수를 합하는 경우와 같다. * 따라서 T타입에 대해서만 완성품수를 구하도록 하고 다음 부분문제를 호출하도록 하면 모든 경우를 일반화 할 수 있는 것이다. * * TODO: 아직 반복적 동적계획법이 익숙하지가 않다. 이 문제의 solution들도 모두 반복적 동적계획법을 사용했다. * 반복적 동적계획법으로 풀어볼 필요가 있으나 일단 이 문제에 너무 많은 시간을 소비했고 지쳤기 때문에 다음으로 미룬다. */ public class C { private int N,M; private long[] a,b; private int[] A,B; private long[][][][] memo; private long[][] memo2; private void goodluck() throws Exception { // ready variables String path = "/Users/teuskim/Documents/workspace/android-src/CodeJam/src/"; int numberOfCases; // get file Scanner sc = new Scanner(new File(path+"C-large-practice.in.txt")); numberOfCases = sc.nextInt(); // make output File file = new File(path+"C-large-practice.out.txt"); if(file.exists() == false) file.createNewFile(); FileWriter fw = new FileWriter(file); for(int casenum=0; casenum<numberOfCases; casenum++){ N = sc.nextInt(); M = sc.nextInt(); a = new long[N]; A = new int[N]; for(int i=0; i<N; i++){ a[i] = sc.nextLong(); A[i] = sc.nextInt(); } b = new long[M]; B = new int[M]; for(int i=0; i<M; i++){ b[i] = sc.nextLong(); B[i] = sc.nextInt(); } // memo = new long[3][100][N][M]; // for(int k=0; k<3; k++) for(int j=0; j<100; j++) for(int i=0; i<N; i++) Arrays.fill(memo[k][j][i], -1); // String result = ""+solve(0,0,0,0); memo2 = new long[N][M]; for(int i=0; i<N; i++) Arrays.fill(memo2[i], -1); String result = ""+solve2(0,0); fw.write("Case #"+(casenum+1)+": "+result+"\n"); print("Case #"+(casenum+1)+": "+result); } fw.close(); } private long solve2(int aidx, int bidx){ if(aidx==N || bidx==M) return 0; if(memo2[aidx][bidx] >= 0) return memo2[aidx][bidx]; long result = 0; if(A[aidx] == B[bidx]){ long asum = a[aidx]; long bsum = b[bidx]; for(int i=aidx+1; i<=N; i++){ for(int j=bidx+1; j<=M; j++){ result = Math.max(result, solve2(i,j) + Math.min(asum, bsum)); if(j<M && B[j] == B[bidx]) bsum += b[j]; } if(i<N && A[i] == A[aidx]) asum += a[i]; bsum = b[bidx]; } } else{ result = Math.max(solve2(aidx+1, bidx), solve2(aidx, bidx+1)); } memo2[aidx][bidx] = result; return result; } private long solve(int ab, int change, int aidx, int bidx){ if(aidx==N || bidx==M) return 0; if(memo[ab][change][aidx][bidx] >= 0) return memo[ab][change][aidx][bidx]; long result = 0; if(A[aidx] == B[bidx]){ if(a[aidx] > b[bidx]){ a[aidx] -= b[bidx]; result = b[bidx] + solve(1, (ab==1 ? change+1 : 1), aidx, bidx+1); a[aidx] += b[bidx]; } else if(a[aidx] < b[bidx]){ b[bidx] -= a[aidx]; result = a[aidx] + solve(2, (ab==2 ? change+1 : 1), aidx+1, bidx); b[bidx] += a[aidx]; } else{ result = a[aidx] + solve(0, 0, aidx+1, bidx+1); } } else{ result = Math.max(solve((ab==2 ? ab : 0), (ab==2 ? change : 0), aidx+1, bidx) , solve((ab==1 ? ab : 0), (ab==1 ? change : 0), aidx, bidx+1)); } // result = Math.max(result, solve(0, bchange, aidx+1, bidx)); // result = Math.max(result, solve(achange, 0, aidx, bidx+1)); // 여기가 문제였다. 타입이 일치하면 무조건 포장을 하는게 상책이다. memo[ab][change][aidx][bidx] = result; return result; } public static void main(String[] args){ print("start!"); try{ new C().goodluck(); }catch(Exception e){ e.printStackTrace(); } print("end!"); } /********************** * code for debugging * **********************/ public void check(boolean isRight, String log){ if(isRight == false){ print("exit: "+log); System.exit(0); } } public static void print(String str){ System.out.println(str); } public static void print(int[] arr){ if(arr == null) print("null"); else{ String str = "["; if(arr.length > 0){ for(int i=0; i<arr.length; i++) str += arr[i]+","; str = str.substring(0, str.length()-1); } str += "]"; print(str); } } }
UTF-8
Java
7,336
java
C.java
Java
[ { "context": "on {\n\t\t// ready variables\n\t\tString path = \"/Users/teuskim/Documents/workspace/android-src/CodeJam/src/\";\n\t\t", "end": 2004, "score": 0.9993475079536438, "start": 1997, "tag": "USERNAME", "value": "teuskim" } ]
null
[]
package gcj.y2012.round1c; import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; /** * Problem C. Box Factory * * 타입이 일치하는 경우 포장을 하고 재귀호출, 그렇지 않은 경우 A타입을 버리거나, B타입을 버리고 재귀호출하여 * 결과들 중 최대값을 리턴하는 방식으로 구현했는데 오답처리되었다. * 문제는 메모이제이션에 있었다. a, b 가 전역변수이면서 변경되고 있기 때문에 관련하여 적용해야 하는데 이것이 꽤 어려웠다. * 메모이제이션을 빼고, 타입이 일치하는 경우는 무조건 포장을 한다고 가정을 하니 small input은 풀렸다. * 다시 말해서, 타입이 일치하는데 박스나 토이를 그냥 버리는 경우에는 최대값이 나올 수 없다는 것이다. * * 이제 large input을 해결하기 위해서는 메모이제이션이 필요하다. analysis를 확인해보자. * analysis 누가 썼는지.. 참.. 별로다. 어찌됐건 Longest Common Subsequence 문제의 변형이라는 정도(?)는 알았다. * 내가 사용한 알고리즘과 크게 다르지 않다. 그렇다면 다시.. 내 알고리즘 안에서 문제를 해결해보자. * 현재 solve()의 문제는 memo[ab][change][aidx][bidx] 에서 서로 다른 경우인데 4개의 값이 모두 같은 경우가 존재한다는 것이다. * 타입이 일치하지 않을때 change값을 다음으로 넘기기 때문에 change값이 같지만 실제로 a[aidx]( 또는 b[bidx] )가 다른 경우가 있을 수 있다. * solution 을 확인해보자. * * analysis와 solution을 여러차례 하루종일 들여다보면서 간신히 해법을 이해할 수 있었다. * 역시.. 그림을 그려서 간단히 시뮬레이션을 해보는게 굉장히 중요하다는 것을 새삼 깨달았다. * 두 라인의 타입이 같은 경우 단순히 다음으로 넘길 수 없다는 것을 깨달아야 한다. * 다행히 두 라인의 물건 개수가 같다면 다음으로 바로 넘길 수 있겠지만 그렇지 않은 경우들을 모두 포괄하는 일반적인 알고리즘을 만들어야 한다. * 두 라인 물건의 개수가 다르다면 적은 개수만큼 완성하고 남은 개수를 버릴지 다른 라인에서 같은 타입이 나올때까지 기다려야 할지에 따라 다양한 경우의 수가 발생한다. * A[aidx]==B[bidx]==T 라고 한다면, aidx<aidx2, bidx<bidx2 인 모든 aidx2,bidx2에 대하여 aidx~aidx2, bidx~bidx2구간에서 T타입인 완성품수와 * 그 다음 구간에 대한 부분문제 호출결과의 합의 최대값을 구하면 되는 것이다. * 여기서 이해하기 어려웠던 부분은 왜 모든 구간에 대해 T타입인 완성품수만 구하느냐는 것이었다. 이것은 귀류법으로 설명이 가능하다. * T타입이 아닌 U타입에 대해서도 완성품수를 계산하도록 하는 경우는, U타입으로 시작하는 부분문제와 그 이전에 대해서는 T타입의 완성품수를 합하는 경우와 같다. * 따라서 T타입에 대해서만 완성품수를 구하도록 하고 다음 부분문제를 호출하도록 하면 모든 경우를 일반화 할 수 있는 것이다. * * TODO: 아직 반복적 동적계획법이 익숙하지가 않다. 이 문제의 solution들도 모두 반복적 동적계획법을 사용했다. * 반복적 동적계획법으로 풀어볼 필요가 있으나 일단 이 문제에 너무 많은 시간을 소비했고 지쳤기 때문에 다음으로 미룬다. */ public class C { private int N,M; private long[] a,b; private int[] A,B; private long[][][][] memo; private long[][] memo2; private void goodluck() throws Exception { // ready variables String path = "/Users/teuskim/Documents/workspace/android-src/CodeJam/src/"; int numberOfCases; // get file Scanner sc = new Scanner(new File(path+"C-large-practice.in.txt")); numberOfCases = sc.nextInt(); // make output File file = new File(path+"C-large-practice.out.txt"); if(file.exists() == false) file.createNewFile(); FileWriter fw = new FileWriter(file); for(int casenum=0; casenum<numberOfCases; casenum++){ N = sc.nextInt(); M = sc.nextInt(); a = new long[N]; A = new int[N]; for(int i=0; i<N; i++){ a[i] = sc.nextLong(); A[i] = sc.nextInt(); } b = new long[M]; B = new int[M]; for(int i=0; i<M; i++){ b[i] = sc.nextLong(); B[i] = sc.nextInt(); } // memo = new long[3][100][N][M]; // for(int k=0; k<3; k++) for(int j=0; j<100; j++) for(int i=0; i<N; i++) Arrays.fill(memo[k][j][i], -1); // String result = ""+solve(0,0,0,0); memo2 = new long[N][M]; for(int i=0; i<N; i++) Arrays.fill(memo2[i], -1); String result = ""+solve2(0,0); fw.write("Case #"+(casenum+1)+": "+result+"\n"); print("Case #"+(casenum+1)+": "+result); } fw.close(); } private long solve2(int aidx, int bidx){ if(aidx==N || bidx==M) return 0; if(memo2[aidx][bidx] >= 0) return memo2[aidx][bidx]; long result = 0; if(A[aidx] == B[bidx]){ long asum = a[aidx]; long bsum = b[bidx]; for(int i=aidx+1; i<=N; i++){ for(int j=bidx+1; j<=M; j++){ result = Math.max(result, solve2(i,j) + Math.min(asum, bsum)); if(j<M && B[j] == B[bidx]) bsum += b[j]; } if(i<N && A[i] == A[aidx]) asum += a[i]; bsum = b[bidx]; } } else{ result = Math.max(solve2(aidx+1, bidx), solve2(aidx, bidx+1)); } memo2[aidx][bidx] = result; return result; } private long solve(int ab, int change, int aidx, int bidx){ if(aidx==N || bidx==M) return 0; if(memo[ab][change][aidx][bidx] >= 0) return memo[ab][change][aidx][bidx]; long result = 0; if(A[aidx] == B[bidx]){ if(a[aidx] > b[bidx]){ a[aidx] -= b[bidx]; result = b[bidx] + solve(1, (ab==1 ? change+1 : 1), aidx, bidx+1); a[aidx] += b[bidx]; } else if(a[aidx] < b[bidx]){ b[bidx] -= a[aidx]; result = a[aidx] + solve(2, (ab==2 ? change+1 : 1), aidx+1, bidx); b[bidx] += a[aidx]; } else{ result = a[aidx] + solve(0, 0, aidx+1, bidx+1); } } else{ result = Math.max(solve((ab==2 ? ab : 0), (ab==2 ? change : 0), aidx+1, bidx) , solve((ab==1 ? ab : 0), (ab==1 ? change : 0), aidx, bidx+1)); } // result = Math.max(result, solve(0, bchange, aidx+1, bidx)); // result = Math.max(result, solve(achange, 0, aidx, bidx+1)); // 여기가 문제였다. 타입이 일치하면 무조건 포장을 하는게 상책이다. memo[ab][change][aidx][bidx] = result; return result; } public static void main(String[] args){ print("start!"); try{ new C().goodluck(); }catch(Exception e){ e.printStackTrace(); } print("end!"); } /********************** * code for debugging * **********************/ public void check(boolean isRight, String log){ if(isRight == false){ print("exit: "+log); System.exit(0); } } public static void print(String str){ System.out.println(str); } public static void print(int[] arr){ if(arr == null) print("null"); else{ String str = "["; if(arr.length > 0){ for(int i=0; i<arr.length; i++) str += arr[i]+","; str = str.substring(0, str.length()-1); } str += "]"; print(str); } } }
7,336
0.592891
0.576218
182
28.989012
26.17964
113
false
false
0
0
0
0
0
0
2.747253
false
false
7
742cbf73e1531efe5af30c3560a97d1cda4efedd
13,469,017,451,597
478d05607f26446bde03948ab284a65058009b19
/projetof1TCC/BASE-modulo/src/qcs/persistence/rhdefensoria/transformer/StatusBrinquedoTransformer.java
0e5b5705756f0ae7b5e709d276ca8bf898c58183
[]
no_license
herberton/projetof1
https://github.com/herberton/projetof1
865ed0a6ab54ecf6ffe177162933c946ddc724b8
00e27e7a1bc77a7c2ece7f326279858fc35b1b22
refs/heads/master
2021-01-22T06:54:39.320000
2010-12-04T22:57:38
2010-12-04T22:57:38
33,141,526
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package qcs.persistence.rhdefensoria.transformer; import java.util.List; import org.hibernate.transform.ResultTransformer; import qcs.persistence.rhdefensoria.view.StatusBrinquedoView; public class StatusBrinquedoTransformer implements ResultTransformer{ private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override public List transformList(List list) { return list; } @Override public Object transformTuple(Object[] values, String[] aliases) { StatusBrinquedoView view = new StatusBrinquedoView(); view.setIdStatusBrinquedo((Long) values[0]); view.setDescricao((String) values[1]); return view; } }
UTF-8
Java
681
java
StatusBrinquedoTransformer.java
Java
[]
null
[]
package qcs.persistence.rhdefensoria.transformer; import java.util.List; import org.hibernate.transform.ResultTransformer; import qcs.persistence.rhdefensoria.view.StatusBrinquedoView; public class StatusBrinquedoTransformer implements ResultTransformer{ private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override public List transformList(List list) { return list; } @Override public Object transformTuple(Object[] values, String[] aliases) { StatusBrinquedoView view = new StatusBrinquedoView(); view.setIdStatusBrinquedo((Long) values[0]); view.setDescricao((String) values[1]); return view; } }
681
0.759178
0.754772
26
24.192308
24.124706
69
false
false
0
0
0
0
0
0
1.115385
false
false
7
9bc6c191c23be634ba997b56c884509f1aaba5c8
26,061,861,564,450
1e346f7c7b0e391824b624875eb6807bb132f478
/csc107-110/PineAdamLab_10/src/Song.java
a51d9748d772e5352c845581b4029694a40b7817
[]
no_license
Adondriel/CollegePortfolio
https://github.com/Adondriel/CollegePortfolio
b7097635709407aa9ec645d6cc03d9290fb91a3d
0dca2bb0a75225b69aca6b9234e80cedfe19d0d1
refs/heads/master
2021-01-21T14:07:55.940000
2016-03-24T16:52:37
2016-03-24T16:52:37
38,413,224
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @author Adam Pine * The Song class */ public class Song { private int duration; private String title; /** * @param title * @param duration * initialize our song object. */ public Song(String title, int duration) { this.duration = duration; this.title = title; } /** * @return duration of the song. */ public int getDuration() { return duration; } /** * @return title of the song */ public String getTitle() { return title; } /** * @return the string that should be printed out for this object. */ public String toString() { String finalString = null; int minutes = duration / 60; int seconds = duration % 60; if (seconds >= 10) { finalString = title + ": " + minutes + ":" + seconds; } else { finalString = title + ": " + minutes + ":0" + seconds; } return finalString; } /** * @return the substring of the toString method, but just the numbers, and not the song title. */ public String getDurationMinAndSec() { String finalString = toString(); finalString = finalString.substring(finalString.length()-5); return finalString; } }
UTF-8
Java
1,135
java
Song.java
Java
[ { "context": "/**\n * @author Adam Pine\n * The Song class\n */\npublic class Song\n{\n\tprivat", "end": 24, "score": 0.9998320937156677, "start": 15, "tag": "NAME", "value": "Adam Pine" } ]
null
[]
/** * @author <NAME> * The Song class */ public class Song { private int duration; private String title; /** * @param title * @param duration * initialize our song object. */ public Song(String title, int duration) { this.duration = duration; this.title = title; } /** * @return duration of the song. */ public int getDuration() { return duration; } /** * @return title of the song */ public String getTitle() { return title; } /** * @return the string that should be printed out for this object. */ public String toString() { String finalString = null; int minutes = duration / 60; int seconds = duration % 60; if (seconds >= 10) { finalString = title + ": " + minutes + ":" + seconds; } else { finalString = title + ": " + minutes + ":0" + seconds; } return finalString; } /** * @return the substring of the toString method, but just the numbers, and not the song title. */ public String getDurationMinAndSec() { String finalString = toString(); finalString = finalString.substring(finalString.length()-5); return finalString; } }
1,132
0.630837
0.623789
67
15.940298
18.902641
95
false
false
0
0
0
0
0
0
1.402985
false
false
7
2a1e1dc656e2df6583263a927687dd1e752ba8f4
30,734,785,980,454
628e441eb9de420a912e2e1dbb84fb913f0aa08f
/demo-1/src/main/java/com/shubham/demo1/UserResource.java
7b65c6c28192fbbfe956751283cd6f09703dbec1
[]
no_license
Shub2798/JavaTrain
https://github.com/Shub2798/JavaTrain
29b0feb575547796d51fabcd3bac0005dc136dc8
449a828fa0208696ee06006247eb01ca151431da
refs/heads/master
2020-12-23T00:13:25.675000
2020-01-29T12:04:05
2020-01-29T12:04:05
236,972,947
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shubham.demo1; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; @RestController public class UserResource { @Autowired UserDaoService obj=new UserDaoService(); @GetMapping("/Users") public ArrayList<User> retreiveAllUser(ArrayList<User> arr){ return obj.findAll(arr); } @GetMapping("/Users/{id}") public User retrieveUser(@PathVariable int id) { return obj.findOne(id); } }
UTF-8
Java
621
java
UserResource.java
Java
[]
null
[]
package com.shubham.demo1; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; @RestController public class UserResource { @Autowired UserDaoService obj=new UserDaoService(); @GetMapping("/Users") public ArrayList<User> retreiveAllUser(ArrayList<User> arr){ return obj.findAll(arr); } @GetMapping("/Users/{id}") public User retrieveUser(@PathVariable int id) { return obj.findOne(id); } }
621
0.800322
0.798712
29
20.413794
22.556469
62
false
false
0
0
0
0
0
0
0.310345
false
false
7
b2ce7b04ec7b68e98a44ae34fc6a5b5897c62b38
1,640,677,524,583
237e3bd44953a1ea2b38427fa25a0ca52d1fcfdc
/src/test/java/com/band/api/UserMutationTest.java
9aa4ce74b1d89d54a129068a595c290b336ed987
[]
no_license
band-together/api
https://github.com/band-together/api
3184c0383b71655fe9f83b8375fd5f7fc9737475
29f53883724fc346bd528d30cc584e882a8dc03a
refs/heads/dev
2020-05-01T07:18:45.238000
2019-05-12T03:50:09
2019-05-12T03:50:09
177,349,425
0
3
null
false
2019-05-12T05:18:30
2019-03-23T23:10:50
2019-05-12T03:50:12
2019-05-12T03:50:10
20
0
3
1
Java
false
false
package com.band.api; import com.band.api.domain.User; import com.band.api.exceptions.BaseGraphQLException; import com.band.api.exceptions.InvalidInputException; import com.band.api.resolvers.UserMutation; import com.band.api.services.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.dao.DataAccessResourceFailureException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; class UserMutationTest { private UserService mockUserService; private UserMutation userMutation; @BeforeEach void setup() { mockUserService = Mockito.mock(UserService.class); userMutation = new UserMutation(mockUserService); } @Test void createUserDuplicateUsernameOrEmail() { String username = "myUsername"; String password = "myPassword"; String name = "myName"; String email = "myEmail@gmail.com"; doThrow(InvalidInputException.class).when(mockUserService).verifyNewUser(username, email); assertThrows(NullPointerException.class, () -> userMutation.createUser(email, username, password, name)); } @Test void createUserSuccess() { String username = "myUsername"; String password = "myPassword"; String name = "myName"; String email = "myEmail@gmail.com"; when(mockUserService.createUser(email, username, password, name)).thenReturn( User.builder() .id(1) .username(username) .email(email) .emailSearch(email.toLowerCase()) .name(name) .passwordHash("TestHash") .build() ); User u = userMutation.createUser(email, username, password, name); assertThat(u.getUsername(), is(username)); assertThat(u.getName(), is(name)); assertThat(u.getEmail(), is(email)); assertThat(u.getPasswordHash(), is("TestHash")); } @Test void createUserDatabaseUnavailable() { String username = "myUsername"; String password = "myPassword"; String name = "myName"; String email = "myEmail@gmail.com"; doThrow(DataAccessResourceFailureException.class).when(mockUserService).verifyNewUser(any(String.class), any(String.class)); assertThrows(BaseGraphQLException.class, () -> userMutation.createUser(email, username, password, name)); } }
UTF-8
Java
2,765
java
UserMutationTest.java
Java
[ { "context": "ateUsernameOrEmail() {\n String username = \"myUsername\";\n String password = \"myPassword\";\n ", "end": 1068, "score": 0.9995535612106323, "start": 1058, "tag": "USERNAME", "value": "myUsername" }, { "context": "ername = \"myUsername\";\n String password = \"myPassword\";\n String name = \"myName\";\n String ", "end": 1108, "score": 0.9994398355484009, "start": 1098, "tag": "PASSWORD", "value": "myPassword" }, { "context": " String name = \"myName\";\n String email = \"myEmail@gmail.com\";\n doThrow(InvalidInputException.class).wh", "end": 1184, "score": 0.9999178051948547, "start": 1167, "tag": "EMAIL", "value": "myEmail@gmail.com" }, { "context": " createUserSuccess() {\n String username = \"myUsername\";\n String password = \"myPassword\";\n ", "end": 1485, "score": 0.9995676279067993, "start": 1475, "tag": "USERNAME", "value": "myUsername" }, { "context": "ername = \"myUsername\";\n String password = \"myPassword\";\n String name = \"myName\";\n String ", "end": 1525, "score": 0.9994497299194336, "start": 1515, "tag": "PASSWORD", "value": "myPassword" }, { "context": " String name = \"myName\";\n String email = \"myEmail@gmail.com\";\n when(mockUserService.createUser(email, ", "end": 1601, "score": 0.9999112486839294, "start": 1584, "tag": "EMAIL", "value": "myEmail@gmail.com" }, { "context": " .id(1)\n .username(username)\n .email(email)\n ", "end": 1794, "score": 0.9924858212471008, "start": 1786, "tag": "USERNAME", "value": "username" }, { "context": "name(name)\n .passwordHash(\"TestHash\")\n .build()\n );\n\n ", "end": 1975, "score": 0.9993565082550049, "start": 1967, "tag": "PASSWORD", "value": "TestHash" }, { "context": "atabaseUnavailable() {\n String username = \"myUsername\";\n String password = \"myPassword\";\n ", "end": 2391, "score": 0.9994823932647705, "start": 2381, "tag": "USERNAME", "value": "myUsername" }, { "context": "ername = \"myUsername\";\n String password = \"myPassword\";\n String name = \"myName\";\n String ", "end": 2431, "score": 0.9991973638534546, "start": 2421, "tag": "PASSWORD", "value": "myPassword" }, { "context": " String name = \"myName\";\n String email = \"myEmail@gmail.com\";\n doThrow(DataAccessResourceFailureExcept", "end": 2507, "score": 0.9999229311943054, "start": 2490, "tag": "EMAIL", "value": "myEmail@gmail.com" } ]
null
[]
package com.band.api; import com.band.api.domain.User; import com.band.api.exceptions.BaseGraphQLException; import com.band.api.exceptions.InvalidInputException; import com.band.api.resolvers.UserMutation; import com.band.api.services.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.dao.DataAccessResourceFailureException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; class UserMutationTest { private UserService mockUserService; private UserMutation userMutation; @BeforeEach void setup() { mockUserService = Mockito.mock(UserService.class); userMutation = new UserMutation(mockUserService); } @Test void createUserDuplicateUsernameOrEmail() { String username = "myUsername"; String password = "<PASSWORD>"; String name = "myName"; String email = "<EMAIL>"; doThrow(InvalidInputException.class).when(mockUserService).verifyNewUser(username, email); assertThrows(NullPointerException.class, () -> userMutation.createUser(email, username, password, name)); } @Test void createUserSuccess() { String username = "myUsername"; String password = "<PASSWORD>"; String name = "myName"; String email = "<EMAIL>"; when(mockUserService.createUser(email, username, password, name)).thenReturn( User.builder() .id(1) .username(username) .email(email) .emailSearch(email.toLowerCase()) .name(name) .passwordHash("<PASSWORD>") .build() ); User u = userMutation.createUser(email, username, password, name); assertThat(u.getUsername(), is(username)); assertThat(u.getName(), is(name)); assertThat(u.getEmail(), is(email)); assertThat(u.getPasswordHash(), is("TestHash")); } @Test void createUserDatabaseUnavailable() { String username = "myUsername"; String password = "<PASSWORD>"; String name = "myName"; String email = "<EMAIL>"; doThrow(DataAccessResourceFailureException.class).when(mockUserService).verifyNewUser(any(String.class), any(String.class)); assertThrows(BaseGraphQLException.class, () -> userMutation.createUser(email, username, password, name)); } }
2,737
0.666546
0.666184
74
36.364864
27.258806
132
false
false
0
0
0
0
0
0
0.837838
false
false
7
5fc8f70914583fba56efe499e80e0cf4de8a3d5f
30,597,347,037,406
9f9d3d0d732ca9958725b5c125e37f32a1a197fe
/app/src/main/java/ir/mahoorsoft/app/stationsfanclub/view/activity_ticket/ticket/fragment_ticket_list/FragmentTicketList.java
4ce83237cf86b88aa1bff095628d4a312995cb78
[]
no_license
MostafaGhanbari9176/customer-club-demo
https://github.com/MostafaGhanbari9176/customer-club-demo
7b29d55d1682907a139c302d56fe8af435e41b27
01a44cce039477ce60e5124816c81fa89b036038
refs/heads/master
2023-05-22T01:44:39.050000
2020-10-29T18:15:33
2020-10-29T18:15:33
374,602,187
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ir.mahoorsoft.app.stationsfanclub.view.activity_ticket.ticket.fragment_ticket_list; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import ir.mahoorsoft.app.stationsfanclub.G; import ir.mahoorsoft.app.stationsfanclub.R; import ir.mahoorsoft.app.stationsfanclub.model.struct.StTicket; import ir.mahoorsoft.app.stationsfanclub.presenter.PresentTicket; import ir.mahoorsoft.app.stationsfanclub.view.activity_ticket.ActivityTicket; import ir.mahoorsoft.app.stationsfanclub.view.activity_ticket.ticket.fragment_ticket_massage.FragmentTicketMessage; import ir.mahoorsoft.app.stationsfanclub.view.date.DateCreator; /** * Created by M-gh on 01-Aug-18. */ public class FragmentTicketList extends Fragment implements PresentTicket.OnPresentTicketResponseListener, AdapterTicketList.OnTicketItemClick { View view; RecyclerView list; ArrayList<StTicket> source = new ArrayList<>(); AdapterTicketList adapterTicketList; FloatingActionButton fab; public static int position = 0; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_ticket_list, container, false); init(); return view; } private void init() { pointer(); getDataFromServer(); } private void getDataFromServer() { (new PresentTicket(this)).getTicket(); } private void pointer() { ((FloatingActionButton) view.findViewById(R.id.fabFragmentTicketList)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialogAddTicket(); } }); list = (RecyclerView) view.findViewById(R.id.RVTicketList); } private void showDialogAddTicket() { final Dialog dialog = new Dialog(G.context); LayoutInflater li = (LayoutInflater) G.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = li.inflate(R.layout.dialog_get_ticket_data, null, false); final TextView txtSubject = (TextView) view.findViewById(R.id.txtSubjectTicketDialog); final TextView txtQuestion = (TextView) view.findViewById(R.id.txtQuestioDialogTicket); Button btnConfirm = (Button) view.findViewById(R.id.btnConfirmDialogTicket); Button btnCancel = (Button) view.findViewById(R.id.btnCancelDialogTicket); btnConfirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String subject = txtSubject.getText().toString().trim(); String question = txtQuestion.getText().toString().trim(); if (checkTicketData(subject, txtSubject, question, txtQuestion)) { addTicket(subject, question); dialog.cancel(); } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.cancel(); } }); dialog.setContentView(view); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } private boolean checkTicketData(String subject, TextView txtSubject, String question, TextView txtquestion) { if (TextUtils.isEmpty(subject)) { txtSubject.setError("لطفا یک عنوان وارد کنید"); return false; } else if (TextUtils.isEmpty(question)) { txtquestion.setError("لطفا متن سوال خودرا وارد کنید"); return false; } return true; } private void addTicket(String subject, String question) { StTicket stTicket = new StTicket(); stTicket.subject = subject; stTicket.tiDate = DateCreator.todayDate(); source.add(stTicket); adapterTicketList.notifyItemInserted(source.size() - 1); adapterTicketList.notifyItemRangeChanged(source.size() - 1, adapterTicketList.getItemCount()); list.scrollToPosition(source.size() - 1); } @Override public void messageFromTicket(String message) { } @Override public void flagFromTicket(boolean flag) { } @Override public void dataFromTicket(ArrayList<StTicket> tickets) { source.clear(); source.addAll(tickets); adapterTicketList = new AdapterTicketList(G.context, source, this); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(G.context, LinearLayout.VERTICAL, false); list.setLayoutManager(layoutManager); list.setAdapter(adapterTicketList); adapterTicketList.notifyDataSetChanged(); list.scrollToPosition(position); } @Override public void clickedTicket(int position) { ((ActivityTicket) (G.context)).replaceView(new FragmentTicketMessage(), source.get(position).subject); FragmentTicketList.position = position; } }
UTF-8
Java
5,727
java
FragmentTicketList.java
Java
[ { "context": "sfanclub.view.date.DateCreator;\n\n/**\n * Created by M-gh on 01-Aug-18.\n */\n\npublic class FragmentTicketLis", "end": 1271, "score": 0.9953182339668274, "start": 1267, "tag": "USERNAME", "value": "M-gh" } ]
null
[]
package ir.mahoorsoft.app.stationsfanclub.view.activity_ticket.ticket.fragment_ticket_list; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import ir.mahoorsoft.app.stationsfanclub.G; import ir.mahoorsoft.app.stationsfanclub.R; import ir.mahoorsoft.app.stationsfanclub.model.struct.StTicket; import ir.mahoorsoft.app.stationsfanclub.presenter.PresentTicket; import ir.mahoorsoft.app.stationsfanclub.view.activity_ticket.ActivityTicket; import ir.mahoorsoft.app.stationsfanclub.view.activity_ticket.ticket.fragment_ticket_massage.FragmentTicketMessage; import ir.mahoorsoft.app.stationsfanclub.view.date.DateCreator; /** * Created by M-gh on 01-Aug-18. */ public class FragmentTicketList extends Fragment implements PresentTicket.OnPresentTicketResponseListener, AdapterTicketList.OnTicketItemClick { View view; RecyclerView list; ArrayList<StTicket> source = new ArrayList<>(); AdapterTicketList adapterTicketList; FloatingActionButton fab; public static int position = 0; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_ticket_list, container, false); init(); return view; } private void init() { pointer(); getDataFromServer(); } private void getDataFromServer() { (new PresentTicket(this)).getTicket(); } private void pointer() { ((FloatingActionButton) view.findViewById(R.id.fabFragmentTicketList)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialogAddTicket(); } }); list = (RecyclerView) view.findViewById(R.id.RVTicketList); } private void showDialogAddTicket() { final Dialog dialog = new Dialog(G.context); LayoutInflater li = (LayoutInflater) G.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = li.inflate(R.layout.dialog_get_ticket_data, null, false); final TextView txtSubject = (TextView) view.findViewById(R.id.txtSubjectTicketDialog); final TextView txtQuestion = (TextView) view.findViewById(R.id.txtQuestioDialogTicket); Button btnConfirm = (Button) view.findViewById(R.id.btnConfirmDialogTicket); Button btnCancel = (Button) view.findViewById(R.id.btnCancelDialogTicket); btnConfirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String subject = txtSubject.getText().toString().trim(); String question = txtQuestion.getText().toString().trim(); if (checkTicketData(subject, txtSubject, question, txtQuestion)) { addTicket(subject, question); dialog.cancel(); } } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.cancel(); } }); dialog.setContentView(view); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } private boolean checkTicketData(String subject, TextView txtSubject, String question, TextView txtquestion) { if (TextUtils.isEmpty(subject)) { txtSubject.setError("لطفا یک عنوان وارد کنید"); return false; } else if (TextUtils.isEmpty(question)) { txtquestion.setError("لطفا متن سوال خودرا وارد کنید"); return false; } return true; } private void addTicket(String subject, String question) { StTicket stTicket = new StTicket(); stTicket.subject = subject; stTicket.tiDate = DateCreator.todayDate(); source.add(stTicket); adapterTicketList.notifyItemInserted(source.size() - 1); adapterTicketList.notifyItemRangeChanged(source.size() - 1, adapterTicketList.getItemCount()); list.scrollToPosition(source.size() - 1); } @Override public void messageFromTicket(String message) { } @Override public void flagFromTicket(boolean flag) { } @Override public void dataFromTicket(ArrayList<StTicket> tickets) { source.clear(); source.addAll(tickets); adapterTicketList = new AdapterTicketList(G.context, source, this); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(G.context, LinearLayout.VERTICAL, false); list.setLayoutManager(layoutManager); list.setAdapter(adapterTicketList); adapterTicketList.notifyDataSetChanged(); list.scrollToPosition(position); } @Override public void clickedTicket(int position) { ((ActivityTicket) (G.context)).replaceView(new FragmentTicketMessage(), source.get(position).subject); FragmentTicketList.position = position; } }
5,727
0.695109
0.693702
160
34.525002
32.298595
144
false
false
0
0
0
0
0
0
0.63125
false
false
7
47d8e707cd3bd71032c372edfe52d41ddd015c2c
5,299,989,668,175
f63b96b541dcd4c3eabb422b14093ce227cbe1db
/demo-biz/src/main/java/com/maitianer/demo/biz/utils/SpringContextUtils.java
5bfec033ca2af009e57cb6869464786d7be6607d
[]
no_license
kuangzhan2014/demo
https://github.com/kuangzhan2014/demo
a735c62b7beedeea344eb58d3ab31fa2f0942967
1cda68236c122d1b83eebf293a82f12841e37549
refs/heads/master
2022-08-10T22:48:28.765000
2019-09-10T02:35:04
2019-09-10T02:35:04
206,702,924
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maitianer.demo.biz.utils; import com.maitianer.demo.common.utils.lang.StringUtils; import com.maitianer.demo.core.filesystem.spring.FSProviderSpringFacade; import com.maitianer.demo.model.ApplicationData; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.util.Locale; /** * @Author Chen * @Date 2018/11/29 17:02 */ @Component public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext context = null; /* (non Javadoc) * @Title: setApplicationContext * @Description: spring获取bean工具类 * @param applicationContext * @throws BeansException * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } // 传入线程中 public static <T> T getBean(String beanName) { return (T) context.getBean(beanName); } // 国际化使用 public static String getMessage(String key) { return context.getMessage(key, null, Locale.getDefault()); } /// 获取当前环境 public static String getActiveProfile() { return context.getEnvironment().getActiveProfiles()[0]; } // public static String getRealAmount(){ // String profile = getActiveProfile(); // if(StringUtils.isNoneBlank(profile)){ // return profile; // }else { // return null; // } // } @Bean(name = "aliyunFSProvider") public FSProviderSpringFacade condition(){ String profile = getActiveProfile(); FSProviderSpringFacade fsProviderSpringFacade = new FSProviderSpringFacade(); fsProviderSpringFacade.setProvider("aliyun"); fsProviderSpringFacade.setPrivated(false); fsProviderSpringFacade.setEndpoint("oss-cn-hangzhou.aliyuncs.com"); if("prod".equals(profile)) { }else { //测试环境 fsProviderSpringFacade.setUrlPrefix("http://rpfc-library-prod.oss-cn-hangzhou.aliyuncs.com"); fsProviderSpringFacade.setSecretKey("pnzdAs4PDbE67JBKbbj2HII9HlB4Ir"); fsProviderSpringFacade.setGroupName("rpfc-library-prod"); fsProviderSpringFacade.setAccessKey("LTAIPfUeH458kDCg"); } // 设置进全局便于获取资源路径 ApplicationData.get().setFsProviderSpringFacade(fsProviderSpringFacade); return fsProviderSpringFacade; } }
UTF-8
Java
2,859
java
SpringContextUtils.java
Java
[ { "context": "gDecimal;\nimport java.util.Locale;\n\n/**\n * @Author Chen\n * @Date 2018/11/29 17:02\n */\n@Component\npublic c", "end": 558, "score": 0.9962509274482727, "start": 554, "tag": "NAME", "value": "Chen" }, { "context": "\n fsProviderSpringFacade.setSecretKey(\"pnzdAs4PDbE67JBKbbj2HII9HlB4Ir\");\n fsProviderSpringFacade.setGroupNam", "end": 2475, "score": 0.9996499419212341, "start": 2445, "tag": "KEY", "value": "pnzdAs4PDbE67JBKbbj2HII9HlB4Ir" }, { "context": "\n fsProviderSpringFacade.setAccessKey(\"LTAIPfUeH458kDCg\");\n }\n // 设置进全局便于获取资源路径\n App", "end": 2614, "score": 0.9996448755264282, "start": 2598, "tag": "KEY", "value": "LTAIPfUeH458kDCg" } ]
null
[]
package com.maitianer.demo.biz.utils; import com.maitianer.demo.common.utils.lang.StringUtils; import com.maitianer.demo.core.filesystem.spring.FSProviderSpringFacade; import com.maitianer.demo.model.ApplicationData; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.util.Locale; /** * @Author Chen * @Date 2018/11/29 17:02 */ @Component public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext context = null; /* (non Javadoc) * @Title: setApplicationContext * @Description: spring获取bean工具类 * @param applicationContext * @throws BeansException * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } // 传入线程中 public static <T> T getBean(String beanName) { return (T) context.getBean(beanName); } // 国际化使用 public static String getMessage(String key) { return context.getMessage(key, null, Locale.getDefault()); } /// 获取当前环境 public static String getActiveProfile() { return context.getEnvironment().getActiveProfiles()[0]; } // public static String getRealAmount(){ // String profile = getActiveProfile(); // if(StringUtils.isNoneBlank(profile)){ // return profile; // }else { // return null; // } // } @Bean(name = "aliyunFSProvider") public FSProviderSpringFacade condition(){ String profile = getActiveProfile(); FSProviderSpringFacade fsProviderSpringFacade = new FSProviderSpringFacade(); fsProviderSpringFacade.setProvider("aliyun"); fsProviderSpringFacade.setPrivated(false); fsProviderSpringFacade.setEndpoint("oss-cn-hangzhou.aliyuncs.com"); if("prod".equals(profile)) { }else { //测试环境 fsProviderSpringFacade.setUrlPrefix("http://rpfc-library-prod.oss-cn-hangzhou.aliyuncs.com"); fsProviderSpringFacade.setSecretKey("<KEY>"); fsProviderSpringFacade.setGroupName("rpfc-library-prod"); fsProviderSpringFacade.setAccessKey("<KEY>"); } // 设置进全局便于获取资源路径 ApplicationData.get().setFsProviderSpringFacade(fsProviderSpringFacade); return fsProviderSpringFacade; } }
2,823
0.708588
0.700683
81
33.358025
28.060476
133
false
false
0
0
0
0
0
0
0.395062
false
false
7
26b5d434e202e5c8dba019c7eee1796c06037faa
23,441,931,516,595
2d8d6e84a01e291b5c04b4404469749753e125e6
/microcloud-provider-dept/src/main/java/cn/hlxd/microcloud/rest/DeptRest.java
01936bdf098488f8c6aec2ab2b2836785aff183d
[]
no_license
ZacharyGg/microcloud
https://github.com/ZacharyGg/microcloud
5a3e4a627fda41592a826d52e5ea987d09bc3136
ff4111ffbbada7a45b3df642593f01f36f4495a0
refs/heads/master
2020-03-22T06:50:17.503000
2018-07-04T03:00:34
2018-07-04T03:00:34
139,661,383
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.hlxd.microcloud.rest; import cn.hlxd.microcloud.service.IDeptService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * Created with IntelliJ IDEA. * * @Program:{microcloud} * @Author:Zachary * @Version:V1.0 * @Date: 2018-06-07-13:33 * @Description: **/ @RestController public class DeptRest { @Resource private IDeptService deptService; @RequestMapping(value = "/dept/list",method = RequestMethod.GET) public Object list(){ return this.deptService.list(); } }
UTF-8
Java
703
java
DeptRest.java
Java
[ { "context": "lliJ IDEA.\n *\n * @Program:{microcloud}\n * @Author:Zachary\n * @Version:V1.0\n * @Date: 2018-06-07-13:33\n * @D", "end": 387, "score": 0.9997009634971619, "start": 380, "tag": "NAME", "value": "Zachary" } ]
null
[]
package cn.hlxd.microcloud.rest; import cn.hlxd.microcloud.service.IDeptService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * Created with IntelliJ IDEA. * * @Program:{microcloud} * @Author:Zachary * @Version:V1.0 * @Date: 2018-06-07-13:33 * @Description: **/ @RestController public class DeptRest { @Resource private IDeptService deptService; @RequestMapping(value = "/dept/list",method = RequestMethod.GET) public Object list(){ return this.deptService.list(); } }
703
0.738817
0.718615
31
21.354839
21.021568
68
false
false
0
0
0
0
0
0
0.290323
false
false
7
2d3eacdf8a6210a3e93d3b84e49cf469e82b0106
13,726,715,502,539
b7e9e501f2c142fa3fd0288f75b29a102084ed75
/src/main/java/com/tstar/ssm/service/impl/JobServiceImpl.java
da83279fee08f228b65dad7ed08f9802ea499e55
[]
no_license
MichaelYuan2538/web-ssm
https://github.com/MichaelYuan2538/web-ssm
51eca5247e2d3584542ac03d9084837ada3098c7
ea754c73afddd91b1e55f4590d49ca790e997234
refs/heads/master
2017-12-02T13:54:19.125000
2017-03-18T11:29:30
2017-03-18T11:29:30
85,388,666
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tstar.ssm.service.impl; import com.tstar.ssm.dao.JobMapper; import com.tstar.ssm.model.Job; import com.tstar.ssm.service.JobService; import com.tstar.ssm.utils.tag.PageModel; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by 005423 on 2017/2/17. */ @Service @Transactional(rollbackFor = Exception.class) public class JobServiceImpl implements JobService { @Resource private JobMapper jobMapper; @Override public List<Job> selectByPage(Job job, PageModel pageModel) { /** 当前需要分页的总数据条数 */ Map<String,Object> params = new HashMap<>(); if (job.getName() == "") { //如果搜索条件为空,则全选 job.setName(null); } params.put("job", job); int recordCount = jobMapper.count(params); pageModel.setRecordCount(recordCount); if(recordCount > 0){ /** 开始分页查询数据:查询第几页的数据 */ params.put("pageModel", pageModel); } List<Job> jobs = jobMapper.selectByPage(params); return jobs; } @Override public int deleteByPrimaryKey(Integer jobId) { return jobMapper.deleteByPrimaryKey(jobId); } @Override public int updateByPrimaryKey(Job job) { return jobMapper.updateByPrimaryKey(job); } @Override public int insert(Job job) { return jobMapper.insert(job); } @Override public Job selectByPrimaryKey(Integer jobId) { return jobMapper.selectByPrimaryKey(jobId); } @Override public List<Job> selectAll() { return jobMapper.selectAll(); } }
UTF-8
Java
1,851
java
JobServiceImpl.java
Java
[ { "context": "il.List;\nimport java.util.Map;\n\n/**\n * Created by 005423 on 2017/2/17.\n */\n@Service\n@Transactional(rollbac", "end": 431, "score": 0.9936172366142273, "start": 425, "tag": "USERNAME", "value": "005423" } ]
null
[]
package com.tstar.ssm.service.impl; import com.tstar.ssm.dao.JobMapper; import com.tstar.ssm.model.Job; import com.tstar.ssm.service.JobService; import com.tstar.ssm.utils.tag.PageModel; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by 005423 on 2017/2/17. */ @Service @Transactional(rollbackFor = Exception.class) public class JobServiceImpl implements JobService { @Resource private JobMapper jobMapper; @Override public List<Job> selectByPage(Job job, PageModel pageModel) { /** 当前需要分页的总数据条数 */ Map<String,Object> params = new HashMap<>(); if (job.getName() == "") { //如果搜索条件为空,则全选 job.setName(null); } params.put("job", job); int recordCount = jobMapper.count(params); pageModel.setRecordCount(recordCount); if(recordCount > 0){ /** 开始分页查询数据:查询第几页的数据 */ params.put("pageModel", pageModel); } List<Job> jobs = jobMapper.selectByPage(params); return jobs; } @Override public int deleteByPrimaryKey(Integer jobId) { return jobMapper.deleteByPrimaryKey(jobId); } @Override public int updateByPrimaryKey(Job job) { return jobMapper.updateByPrimaryKey(job); } @Override public int insert(Job job) { return jobMapper.insert(job); } @Override public Job selectByPrimaryKey(Integer jobId) { return jobMapper.selectByPrimaryKey(jobId); } @Override public List<Job> selectAll() { return jobMapper.selectAll(); } }
1,851
0.656303
0.648389
69
24.637682
19.147007
65
false
false
0
0
0
0
0
0
0.42029
false
false
7
270137ef91c847550a4661ae7350738702835cc2
22,230,750,748,275
e346ee2be249752daf478476b17fc1d86dc2ae17
/MeiTuan/app/src/main/java/com/qf/meituan/AnnouncedDetailActivity.java
386ac841cd16168c51289822212210517486ba9a
[]
no_license
stjw7098/my-repository
https://github.com/stjw7098/my-repository
63238d686d41111265be9d7fa57db6ee6e57b1db
e82a2b371f83a785a68a6af049f490a32042e68e
refs/heads/master
2020-07-14T15:52:41.203000
2016-11-16T02:57:25
2016-11-16T02:57:25
73,873,498
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qf.meituan; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.facebook.drawee.view.SimpleDraweeView; import com.qf.meituan.beans.AnnouncedDetailBean; import com.qf.meituan.utils.HttpUtil; import com.qf.meituan.utils.JsonUtil; import com.qf.meituan.utils.ThreadUtil; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class AnnouncedDetailActivity extends AppCompatActivity { @BindView(R.id.tv_home_sort) TextView tvHomeSort; @BindView(R.id.tv_home_search) TextView tvHomeSearch; // @BindView(R.id.vp_home_slide) // ViewPager vpHomeSlide; @BindView(R.id.iv_goods) ImageView iv_goods; @BindView(R.id.tvDetail) TextView tvDetail; @BindView(R.id.sdv_head) SimpleDraweeView sdvHead; @BindView(R.id.tv_win) TextView tvWin; @BindView(R.id.tv_win2) TextView tvWin2; @BindView(R.id.tv_join) TextView tvJoin; @BindView(R.id.tv_join2) TextView tvJoin2; @BindView(R.id.tv_result) TextView tvResult; @BindView(R.id.tv_result2) TextView tvResult2; @BindView(R.id.tv_win_num) TextView tvWinNum; @BindView(R.id.btn_buy) Button btnBuy; private static final int ANNOUNCED_DETAIL_BEAN = 1; private AnnouncedDetailBean announcedDetailBean; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case ANNOUNCED_DETAIL_BEAN: announcedDetailBean = ((AnnouncedDetailBean) msg.obj); if(announcedDetailBean.getData().getPhotos().size()>0){ photos = announcedDetailBean.getData().getPhotos().get(0); } String name = announcedDetailBean.getData().getName(); String nper = announcedDetailBean.getData().getNper(); String month = nper.substring(0, 2); String day = nper.substring(2, 4); String hour = nper.substring(4, 6); String minute = nper.substring(6, 8); if(announcedDetailBean.getData().getWinner_info()!=null){ win_nickname = announcedDetailBean.getData().getWinner_info().getWin_nickname(); } if(announcedDetailBean.getData().getBuyCount()!=null){ buyCount = announcedDetailBean.getData().getBuyCount(); } if(announcedDetailBean.getData().getWinnumber()!=null){ winnumber = announcedDetailBean.getData().getWinnumber(); } Glide.with(AnnouncedDetailActivity.this).load(Uri.parse(photos)).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_goods); tvDetail.setText(name); tvWin2.setText(win_nickname); tvJoin2.setText(buyCount); tvResult2.setText(month+"-"+day+" "+hour+":"+minute); tvWinNum.setText(winnumber); break; } } }; private String win_nickname; private String buyCount; private String winnumber; private String photos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_announced_detail); ButterKnife.bind(this); String sid = getIntent().getStringExtra("id"); final int id = Integer.parseInt(sid); ThreadUtil.execute(new Runnable() { @Override public void run() { String detail = HttpUtil.getIndianaDetail(id,AnnouncedDetailActivity.this); AnnouncedDetailBean announcedDetailBean = JsonUtil.parseToAnnouncedDetailBean(detail); Message message = handler.obtainMessage(); message.what= ANNOUNCED_DETAIL_BEAN; message.obj=announcedDetailBean; handler.sendMessage(message); } }); } @OnClick(R.id.tv_home_sort) public void onClickBack(View v) { finish(); } @OnClick(R.id.btn_buy) public void onClickBuy(View v) { finish(); if(mgoToDuoBao!=null){ mgoToDuoBao.setDuoBao(); } } static GoToDuoBao mgoToDuoBao; public static void setGoToDuoBao(GoToDuoBao goToDuoBao) { mgoToDuoBao = goToDuoBao; } public interface GoToDuoBao{ void setDuoBao(); } }
UTF-8
Java
4,909
java
AnnouncedDetailActivity.java
Java
[]
null
[]
package com.qf.meituan; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.facebook.drawee.view.SimpleDraweeView; import com.qf.meituan.beans.AnnouncedDetailBean; import com.qf.meituan.utils.HttpUtil; import com.qf.meituan.utils.JsonUtil; import com.qf.meituan.utils.ThreadUtil; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class AnnouncedDetailActivity extends AppCompatActivity { @BindView(R.id.tv_home_sort) TextView tvHomeSort; @BindView(R.id.tv_home_search) TextView tvHomeSearch; // @BindView(R.id.vp_home_slide) // ViewPager vpHomeSlide; @BindView(R.id.iv_goods) ImageView iv_goods; @BindView(R.id.tvDetail) TextView tvDetail; @BindView(R.id.sdv_head) SimpleDraweeView sdvHead; @BindView(R.id.tv_win) TextView tvWin; @BindView(R.id.tv_win2) TextView tvWin2; @BindView(R.id.tv_join) TextView tvJoin; @BindView(R.id.tv_join2) TextView tvJoin2; @BindView(R.id.tv_result) TextView tvResult; @BindView(R.id.tv_result2) TextView tvResult2; @BindView(R.id.tv_win_num) TextView tvWinNum; @BindView(R.id.btn_buy) Button btnBuy; private static final int ANNOUNCED_DETAIL_BEAN = 1; private AnnouncedDetailBean announcedDetailBean; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case ANNOUNCED_DETAIL_BEAN: announcedDetailBean = ((AnnouncedDetailBean) msg.obj); if(announcedDetailBean.getData().getPhotos().size()>0){ photos = announcedDetailBean.getData().getPhotos().get(0); } String name = announcedDetailBean.getData().getName(); String nper = announcedDetailBean.getData().getNper(); String month = nper.substring(0, 2); String day = nper.substring(2, 4); String hour = nper.substring(4, 6); String minute = nper.substring(6, 8); if(announcedDetailBean.getData().getWinner_info()!=null){ win_nickname = announcedDetailBean.getData().getWinner_info().getWin_nickname(); } if(announcedDetailBean.getData().getBuyCount()!=null){ buyCount = announcedDetailBean.getData().getBuyCount(); } if(announcedDetailBean.getData().getWinnumber()!=null){ winnumber = announcedDetailBean.getData().getWinnumber(); } Glide.with(AnnouncedDetailActivity.this).load(Uri.parse(photos)).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_goods); tvDetail.setText(name); tvWin2.setText(win_nickname); tvJoin2.setText(buyCount); tvResult2.setText(month+"-"+day+" "+hour+":"+minute); tvWinNum.setText(winnumber); break; } } }; private String win_nickname; private String buyCount; private String winnumber; private String photos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_announced_detail); ButterKnife.bind(this); String sid = getIntent().getStringExtra("id"); final int id = Integer.parseInt(sid); ThreadUtil.execute(new Runnable() { @Override public void run() { String detail = HttpUtil.getIndianaDetail(id,AnnouncedDetailActivity.this); AnnouncedDetailBean announcedDetailBean = JsonUtil.parseToAnnouncedDetailBean(detail); Message message = handler.obtainMessage(); message.what= ANNOUNCED_DETAIL_BEAN; message.obj=announcedDetailBean; handler.sendMessage(message); } }); } @OnClick(R.id.tv_home_sort) public void onClickBack(View v) { finish(); } @OnClick(R.id.btn_buy) public void onClickBuy(View v) { finish(); if(mgoToDuoBao!=null){ mgoToDuoBao.setDuoBao(); } } static GoToDuoBao mgoToDuoBao; public static void setGoToDuoBao(GoToDuoBao goToDuoBao) { mgoToDuoBao = goToDuoBao; } public interface GoToDuoBao{ void setDuoBao(); } }
4,909
0.618863
0.614585
150
31.726667
24.95727
141
false
false
0
0
0
0
0
0
0.546667
false
false
7
def6d116c36d4c4f97a9e03fe988b872c90c333d
9,363,028,746,443
d2d52196d0d27383bd7725341550f094fd90475f
/src/main/java/com/halx/spring/SportController.java
14abef61fa1a8f82d6f788b0f1492658e7e40542
[]
no_license
AlexandreBarbez/SpringHibernateUdemy
https://github.com/AlexandreBarbez/SpringHibernateUdemy
a25eb5e7648ac1e10c4003a6ce4f536ebf72ad25
73567084b3b650a158f4ca6f0c0f98691b3b180f
refs/heads/master
2021-07-11T06:47:52.690000
2019-01-07T19:55:45
2019-01-07T19:55:45
134,763,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.halx.spring; import com.halx.AppConfig; import com.halx.spring.coach.Coach; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class SportController { /** * Mapping for Coach exercise on IoC and DI * @return the message to be printed when visiting "/coach" url on server */ @RequestMapping("/coach") @ResponseBody public String printCoachOrder(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); Coach theFirstBBCoach = applicationContext.getBean("baseballCoach", Coach.class); Coach theSecondBBCoach = applicationContext.getBean("baseballCoach", Coach.class); String firstBBCoachOrder = "Object reference : "+theFirstBBCoach+" : <br> Workout of the day : "+theFirstBBCoach.getDailyWorkout()+" Fortune of the day :"+theFirstBBCoach.getDailyFortune(); String secondBBCoachOrder = "Object reference : "+theSecondBBCoach+" : <br> Workout of the day : "+theSecondBBCoach.getDailyWorkout()+" Fortune of the day :"+theSecondBBCoach.getDailyFortune(); Coach theFirstTCoach = applicationContext.getBean("trackCoach", Coach.class); Coach theSecondTCoach = applicationContext.getBean("trackCoach", Coach.class); String firstTCoachOrder = "Object reference : "+theFirstTCoach+" : <br> Workout of the day : "+theFirstTCoach.getDailyWorkout()+" Fortune of the day :"+theFirstTCoach.getDailyFortune(); String secondTCoachOrder = "Object reference : "+theSecondTCoach+" : <br> Workout of the day : "+theSecondTCoach.getDailyWorkout()+" Fortune of the day :"+theSecondTCoach.getDailyFortune(); applicationContext.close(); return "<h2>Two different objects because of the prototype scope of the Spring bean :</h2>"+firstBBCoachOrder+"<br><br>"+secondBBCoachOrder+"<br><br><h2>Two time calling the same object because basic scope setting is Singleton : </h2>"+firstTCoachOrder+"<br><br>"+secondTCoachOrder; } }
UTF-8
Java
2,226
java
SportController.java
Java
[]
null
[]
package com.halx.spring; import com.halx.AppConfig; import com.halx.spring.coach.Coach; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class SportController { /** * Mapping for Coach exercise on IoC and DI * @return the message to be printed when visiting "/coach" url on server */ @RequestMapping("/coach") @ResponseBody public String printCoachOrder(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); Coach theFirstBBCoach = applicationContext.getBean("baseballCoach", Coach.class); Coach theSecondBBCoach = applicationContext.getBean("baseballCoach", Coach.class); String firstBBCoachOrder = "Object reference : "+theFirstBBCoach+" : <br> Workout of the day : "+theFirstBBCoach.getDailyWorkout()+" Fortune of the day :"+theFirstBBCoach.getDailyFortune(); String secondBBCoachOrder = "Object reference : "+theSecondBBCoach+" : <br> Workout of the day : "+theSecondBBCoach.getDailyWorkout()+" Fortune of the day :"+theSecondBBCoach.getDailyFortune(); Coach theFirstTCoach = applicationContext.getBean("trackCoach", Coach.class); Coach theSecondTCoach = applicationContext.getBean("trackCoach", Coach.class); String firstTCoachOrder = "Object reference : "+theFirstTCoach+" : <br> Workout of the day : "+theFirstTCoach.getDailyWorkout()+" Fortune of the day :"+theFirstTCoach.getDailyFortune(); String secondTCoachOrder = "Object reference : "+theSecondTCoach+" : <br> Workout of the day : "+theSecondTCoach.getDailyWorkout()+" Fortune of the day :"+theSecondTCoach.getDailyFortune(); applicationContext.close(); return "<h2>Two different objects because of the prototype scope of the Spring bean :</h2>"+firstBBCoachOrder+"<br><br>"+secondBBCoachOrder+"<br><br><h2>Two time calling the same object because basic scope setting is Singleton : </h2>"+firstTCoachOrder+"<br><br>"+secondTCoachOrder; } }
2,226
0.749326
0.747529
39
56.076923
70.453979
290
false
false
0
0
0
0
0
0
0.564103
false
false
7
2ad12f2ed53e2610cec8f84dff6a88d158d38a5f
33,672,543,635,231
15219fc782efe711f78fc0f1a2e754289c3274f2
/src/main/java/mapMaker/Progressive.java
aca55a01c03d0c5e985444d99906ebbf5c681775
[]
no_license
JedrzejBronislaw/MapMaker
https://github.com/JedrzejBronislaw/MapMaker
3bd067ac6b21f1a046bf51aca4625a9c6f54f176
47882a7de6d3b34d32afdecf7d8a2986d9096da2
refs/heads/master
2020-09-14T05:25:10.721000
2019-12-16T22:56:09
2019-12-16T22:56:09
223,032,432
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mapMaker; import java.util.function.Consumer; public interface Progressive { void setProgressListiner(Consumer<Float> progressListiner); }
UTF-8
Java
150
java
Progressive.java
Java
[]
null
[]
package mapMaker; import java.util.function.Consumer; public interface Progressive { void setProgressListiner(Consumer<Float> progressListiner); }
150
0.82
0.82
7
20.428572
21.022825
60
false
false
0
0
0
0
0
0
0.571429
false
false
7
8c95aaf80d4dfd5b0b451e13a60c1bb148533636
30,605,937,000,217
64d15f9f6e0fe697fdf3974abafb70fdc0755d91
/src/rfiw/data/BillData.java
a352b02f420a3edfae67a0e9e5ad072b596bf1dc
[]
no_license
Bluedz/RFIW_SGM
https://github.com/Bluedz/RFIW_SGM
81c09294d317274399012cfc6c63da70ca4db7e9
bc94154ff531f3403b6d950c9ece5741a7635e8d
refs/heads/master
2020-08-14T23:39:50.588000
2019-10-15T08:37:22
2019-10-15T08:37:22
215,247,473
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 rfiw.data; /** * * @author Zyh */ public class BillData { public static String billOwnerID = "0011609586"; //0000666666 not default public static int tagsEndBit = 0; public static String[][] billList = new String[100][4]; private static String[][] billLsit0 = new String [][] { {"code", "mat", "batch", "stock"} }; // 执行写入时检测是否物料已被计入结算列表,有效的新增数据则更新列表 public static boolean appendLine(String[] str){ boolean flg = true; int length, length2; for(int i=0; i < tagsEndBit ; i++){ if ((billList[i][0]).equals(str[0])){ if((billList[i][1]).equals(str[1])){ if((billList[i][2]).equals(str[2])){ if((billList[i][3]).equals(str[3])){ flg = false; } } } } } if (flg){ length = billList[tagsEndBit].length; length2 = str.length; System.arraycopy(str, 0, billList[tagsEndBit], 0, length); tagsEndBit++; }else{ // 提示重复扫描或已存在与列表内 System.out.println("本条标签数据重复扫描或已存在与列表内"); } return flg; } public static void main(String args[]){ } }
UTF-8
Java
1,611
java
BillData.java
Java
[ { "context": " editor.\n */\npackage rfiw.data;\n\n/**\n *\n * @author Zyh\n */\npublic class BillData {\n public static Str", "end": 227, "score": 0.9941921830177307, "start": 224, "tag": "USERNAME", "value": "Zyh" } ]
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 rfiw.data; /** * * @author Zyh */ public class BillData { public static String billOwnerID = "0011609586"; //0000666666 not default public static int tagsEndBit = 0; public static String[][] billList = new String[100][4]; private static String[][] billLsit0 = new String [][] { {"code", "mat", "batch", "stock"} }; // 执行写入时检测是否物料已被计入结算列表,有效的新增数据则更新列表 public static boolean appendLine(String[] str){ boolean flg = true; int length, length2; for(int i=0; i < tagsEndBit ; i++){ if ((billList[i][0]).equals(str[0])){ if((billList[i][1]).equals(str[1])){ if((billList[i][2]).equals(str[2])){ if((billList[i][3]).equals(str[3])){ flg = false; } } } } } if (flg){ length = billList[tagsEndBit].length; length2 = str.length; System.arraycopy(str, 0, billList[tagsEndBit], 0, length); tagsEndBit++; }else{ // 提示重复扫描或已存在与列表内 System.out.println("本条标签数据重复扫描或已存在与列表内"); } return flg; } public static void main(String args[]){ } }
1,611
0.518543
0.492245
59
24.135593
21.737617
79
false
false
0
0
0
0
0
0
0.457627
false
false
7
5152b439b8fc08907120ebf2da6609f37eb78d1b
27,255,862,499,796
398656566680fca0013b87ec673f8e99893f28d1
/2-queues/Deque.java
e1f36ac576e47a68003df660f261a5dd65fb3a3a
[]
no_license
JiangYuYan/algs4-assignments
https://github.com/JiangYuYan/algs4-assignments
393ca8069cb2bb4daa20e63e0c87799c072506c1
24623c074634783152c85568629b818957850847
refs/heads/main
2023-02-09T14:14:29.062000
2021-01-06T12:02:14
2021-01-06T12:05:13
324,085,782
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Iterator; import edu.princeton.cs.algs4.StdOut; import java.util.NoSuchElementException; public class Deque<Item> implements Iterable<Item> { // use linked list ADT private Node thisFirst; private Node thisLast; private int thisN; private class Node { Item item; Node next; Node prev; } // construct an empty deque public Deque() { thisFirst = null; thisLast = null; thisN = 0; } // is the deque empty? public boolean isEmpty() { return thisN == 0; } // return the number of items on the deque public int size() { return thisN; } // add the item to the front public void addFirst(Item item) { if (item == null) throw new IllegalArgumentException("addFirst argument can't be null"); Node oldFirst = thisFirst; thisFirst = new Node(); thisFirst.item = item; thisFirst.next = oldFirst; if (isEmpty()) thisLast = thisFirst; else oldFirst.prev = thisFirst; ++thisN; } // add the item to the back public void addLast(Item item) { if (item == null) throw new IllegalArgumentException("addLast argument can't be null."); Node oldLast = thisLast; thisLast = new Node(); thisLast.item = item; thisLast.prev = oldLast; if (isEmpty()) thisFirst = thisLast; else oldLast.next = thisLast; ++thisN; } // remove and return the item from the front public Item removeFirst() { if (isEmpty()) throw new NoSuchElementException("Deque underflow front."); Item item = thisFirst.item; thisFirst = thisFirst.next; --thisN; if (isEmpty()) thisLast = null; else thisFirst.prev = null; return item; } // remove and return the item from the back public Item removeLast() { if (isEmpty()) throw new NoSuchElementException("Deque underflow back."); Item item = thisLast.item; thisLast = thisLast.prev; --thisN; if (isEmpty()) thisFirst = null; else thisLast.next = null; return item; } // return an iterator over items in order from front to back public Iterator<Item> iterator() { return new DequeIterator(); } private class DequeIterator implements Iterator<Item> { private Node current = thisFirst; public boolean hasNext() { return current != null; } public Item next() { if (!hasNext()) throw new NoSuchElementException("No more item in iterator."); Item item = current.item; current = current.next; return item; } public void remove() { throw new UnsupportedOperationException("No remove in Iterator."); } } // unit testing (required) public static void main(String[] args) { int n = 5; Deque<Integer> queue = new Deque<Integer>(); StdOut.println(queue.isEmpty()); for (int i = 0; i < n; i++) { queue.addFirst(i); } for (int a : queue) { StdOut.print(a + " "); } StdOut.println(); for (int i = 0; i < n; i++) { queue.addLast(i); } for (int a : queue) { StdOut.print(a + " "); } StdOut.println(queue.size()); StdOut.println(queue.removeFirst()); StdOut.println(queue.removeLast()); for (int a : queue) { StdOut.print(a + " "); } StdOut.println(queue.size()); } }
UTF-8
Java
3,744
java
Deque.java
Java
[]
null
[]
import java.util.Iterator; import edu.princeton.cs.algs4.StdOut; import java.util.NoSuchElementException; public class Deque<Item> implements Iterable<Item> { // use linked list ADT private Node thisFirst; private Node thisLast; private int thisN; private class Node { Item item; Node next; Node prev; } // construct an empty deque public Deque() { thisFirst = null; thisLast = null; thisN = 0; } // is the deque empty? public boolean isEmpty() { return thisN == 0; } // return the number of items on the deque public int size() { return thisN; } // add the item to the front public void addFirst(Item item) { if (item == null) throw new IllegalArgumentException("addFirst argument can't be null"); Node oldFirst = thisFirst; thisFirst = new Node(); thisFirst.item = item; thisFirst.next = oldFirst; if (isEmpty()) thisLast = thisFirst; else oldFirst.prev = thisFirst; ++thisN; } // add the item to the back public void addLast(Item item) { if (item == null) throw new IllegalArgumentException("addLast argument can't be null."); Node oldLast = thisLast; thisLast = new Node(); thisLast.item = item; thisLast.prev = oldLast; if (isEmpty()) thisFirst = thisLast; else oldLast.next = thisLast; ++thisN; } // remove and return the item from the front public Item removeFirst() { if (isEmpty()) throw new NoSuchElementException("Deque underflow front."); Item item = thisFirst.item; thisFirst = thisFirst.next; --thisN; if (isEmpty()) thisLast = null; else thisFirst.prev = null; return item; } // remove and return the item from the back public Item removeLast() { if (isEmpty()) throw new NoSuchElementException("Deque underflow back."); Item item = thisLast.item; thisLast = thisLast.prev; --thisN; if (isEmpty()) thisFirst = null; else thisLast.next = null; return item; } // return an iterator over items in order from front to back public Iterator<Item> iterator() { return new DequeIterator(); } private class DequeIterator implements Iterator<Item> { private Node current = thisFirst; public boolean hasNext() { return current != null; } public Item next() { if (!hasNext()) throw new NoSuchElementException("No more item in iterator."); Item item = current.item; current = current.next; return item; } public void remove() { throw new UnsupportedOperationException("No remove in Iterator."); } } // unit testing (required) public static void main(String[] args) { int n = 5; Deque<Integer> queue = new Deque<Integer>(); StdOut.println(queue.isEmpty()); for (int i = 0; i < n; i++) { queue.addFirst(i); } for (int a : queue) { StdOut.print(a + " "); } StdOut.println(); for (int i = 0; i < n; i++) { queue.addLast(i); } for (int a : queue) { StdOut.print(a + " "); } StdOut.println(queue.size()); StdOut.println(queue.removeFirst()); StdOut.println(queue.removeLast()); for (int a : queue) { StdOut.print(a + " "); } StdOut.println(queue.size()); } }
3,744
0.547276
0.545673
135
26.733334
19.176065
82
false
false
0
0
0
0
0
0
0.511111
false
false
7
857bb43f9c9120807fe544756355029098196e28
10,256,381,920,776
0756e9bbc386aa802d8141fb9e7a77e005378399
/src/ProblemsIn_Java/NoteBook/StringFactoring.java
b6537c6072f33fc8e6e96c43a6f0452260aa4a4e
[]
no_license
dayepesb/OnlineJudges
https://github.com/dayepesb/OnlineJudges
85eae4de8a5c6c74cd7419bc314410b478dcbb6b
0069c8aa644e6952348b7bf903ddd50f19b4e8e7
refs/heads/master
2021-07-15T06:49:35.228000
2020-05-10T07:33:46
2020-05-10T07:33:46
133,302,544
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ProblemsIn_Java.NoteBook; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class StringFactoring { static long memo[][]; static char [] s; static final int INF = Integer.MAX_VALUE; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); memo = new long[110][110]; String line; while (true) { if ((line = in.readLine().trim()).equals("*")) break; int len = line.length(); s = new char[len]; for (int i = 0 ; i < len ; i++)s[i]=line.charAt(i); for (int i = 0; i < 85; i++) { Arrays.fill(memo[i],0); } out.println(dfs(0, len-1)); } out.close(); in.close(); } static long dfs(int l, int r) { if(l == r) return 1; if(memo[l][r]>0) return memo[l][r]; int i, j, k; long ret = memo[l][r]; ret = 0xfffffff; for(i = l; i < r; i++) ret = Math.min(ret, dfs(l, i) + dfs(i+1, r)); int sublen = r-l+1; for(i = 1; i <= sublen; i++) { if(sublen%i == 0) { for(k = l, j = 0; k <= r; k++) { if(s[k] != s[j+l]) break; j++; if(j >= i) j = 0; } if(k == r+1 && r != l+i-1) ret = Math.min(ret, dfs(l, l+i-1)); } } return ret; } }
UTF-8
Java
1,704
java
StringFactoring.java
Java
[]
null
[]
package ProblemsIn_Java.NoteBook; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class StringFactoring { static long memo[][]; static char [] s; static final int INF = Integer.MAX_VALUE; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); memo = new long[110][110]; String line; while (true) { if ((line = in.readLine().trim()).equals("*")) break; int len = line.length(); s = new char[len]; for (int i = 0 ; i < len ; i++)s[i]=line.charAt(i); for (int i = 0; i < 85; i++) { Arrays.fill(memo[i],0); } out.println(dfs(0, len-1)); } out.close(); in.close(); } static long dfs(int l, int r) { if(l == r) return 1; if(memo[l][r]>0) return memo[l][r]; int i, j, k; long ret = memo[l][r]; ret = 0xfffffff; for(i = l; i < r; i++) ret = Math.min(ret, dfs(l, i) + dfs(i+1, r)); int sublen = r-l+1; for(i = 1; i <= sublen; i++) { if(sublen%i == 0) { for(k = l, j = 0; k <= r; k++) { if(s[k] != s[j+l]) break; j++; if(j >= i) j = 0; } if(k == r+1 && r != l+i-1) ret = Math.min(ret, dfs(l, l+i-1)); } } return ret; } }
1,704
0.441315
0.426643
60
27.4
18.168839
81
false
false
0
0
0
0
0
0
0.883333
false
false
7
12f6dfea7421d743cb02f70fcdd678f18d60e455
17,721,035,096,872
62d7001e9991e8d8cfa08612a02b5a96cb867248
/reveno-core/src/main/java/org/reveno/atp/core/engine/components/CommandsManager.java
ad0990f55c66c2b1a685f9a6a661e53b6ba44d10
[ "Apache-2.0" ]
permissive
ulwfcyvi791837060/reveno
https://github.com/ulwfcyvi791837060/reveno
b12610fd45e162b0c7fd2d76d6722f23cb72388f
ecbf6ebcbf2966e989fe5cd50b76c4efa23758aa
refs/heads/master
2020-08-28T08:43:55.851000
2019-10-27T14:49:51
2019-10-27T14:49:51
217,652,488
0
0
Apache-2.0
true
2019-10-26T03:50:14
2019-10-26T03:50:14
2019-10-24T02:18:31
2019-06-04T06:16:59
1,350
0
0
0
null
false
false
package org.reveno.atp.core.engine.components; import org.reveno.atp.api.commands.CommandContext; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.BiFunction; public class CommandsManager { protected Map<Class<?>, CommandWithResult<?, ?>> commandsHandlers = new HashMap<>(); public <T, U> void register(Class<T> command, Class<U> result, BiFunction<T, CommandContext, U> handler) { commandsHandlers.put(command, new CommandWithResult<T, U>(result, handler)); } public <T> void register(Class<T> command, BiConsumer<T, CommandContext> handler) { commandsHandlers.put(command, new CommandWithResult<T, Void>(handler)); } @SuppressWarnings({"rawtypes", "unchecked"}) public Object execute(Object command, CommandContext context) { CommandWithResult cmd = commandsHandlers.get(command.getClass()); if (cmd == null) throw new RuntimeException(String.format("Can't find handler for command [type:%s, cmd:%s]", command.getClass(), command)); if (cmd.handler != null) return cmd.handler.apply(command, context); else { cmd.emptyHandler.accept(command, context); return null; } } protected static class CommandWithResult<T, U> { public final BiFunction<T, CommandContext, U> handler; public final BiConsumer<T, CommandContext> emptyHandler; public final Class<?> resultType; public CommandWithResult(Class<U> result, BiFunction<T, CommandContext, U> handler) { this.handler = handler; this.resultType = result; this.emptyHandler = null; } public CommandWithResult(BiConsumer<T, CommandContext> emptyHandler) { this.handler = null; this.resultType = null; this.emptyHandler = emptyHandler; } } }
UTF-8
Java
1,953
java
CommandsManager.java
Java
[]
null
[]
package org.reveno.atp.core.engine.components; import org.reveno.atp.api.commands.CommandContext; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.BiFunction; public class CommandsManager { protected Map<Class<?>, CommandWithResult<?, ?>> commandsHandlers = new HashMap<>(); public <T, U> void register(Class<T> command, Class<U> result, BiFunction<T, CommandContext, U> handler) { commandsHandlers.put(command, new CommandWithResult<T, U>(result, handler)); } public <T> void register(Class<T> command, BiConsumer<T, CommandContext> handler) { commandsHandlers.put(command, new CommandWithResult<T, Void>(handler)); } @SuppressWarnings({"rawtypes", "unchecked"}) public Object execute(Object command, CommandContext context) { CommandWithResult cmd = commandsHandlers.get(command.getClass()); if (cmd == null) throw new RuntimeException(String.format("Can't find handler for command [type:%s, cmd:%s]", command.getClass(), command)); if (cmd.handler != null) return cmd.handler.apply(command, context); else { cmd.emptyHandler.accept(command, context); return null; } } protected static class CommandWithResult<T, U> { public final BiFunction<T, CommandContext, U> handler; public final BiConsumer<T, CommandContext> emptyHandler; public final Class<?> resultType; public CommandWithResult(Class<U> result, BiFunction<T, CommandContext, U> handler) { this.handler = handler; this.resultType = result; this.emptyHandler = null; } public CommandWithResult(BiConsumer<T, CommandContext> emptyHandler) { this.handler = null; this.resultType = null; this.emptyHandler = emptyHandler; } } }
1,953
0.653354
0.653354
55
34.50909
31.311266
110
false
false
0
0
0
0
0
0
0.945455
false
false
7
630a29ac5196f2c1f57a84699aa73890f53718df
6,614,249,653,005
f969036a225bf6f7ded2261b7176cf704bec8095
/src/main/java/be/comicsdownloader/gui/action/RefreshActionListener.java
be2247d15a036a736df168ed3e1b4c8915b79880
[ "Unlicense" ]
permissive
normegil/comicsdownloader
https://github.com/normegil/comicsdownloader
4212d375f7dbdb1f3a14b7263ec8ae8fbec221da
5cd9104a1bb918c2c451d479276f64b6f0b32be4
refs/heads/master
2021-05-28T06:58:28.770000
2013-11-22T09:50:06
2013-11-22T09:50:06
14,259,326
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.comicsdownloader.gui.action; import be.comicsdownloader.model.Model; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class RefreshActionListener implements ActionListener { private Model model; public RefreshActionListener(Model model) { this.model = model; } @Override public void actionPerformed(final ActionEvent ae) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { actionPerformed(ae); } }); } else { model.refreshData(); } } }
UTF-8
Java
737
java
RefreshActionListener.java
Java
[]
null
[]
package be.comicsdownloader.gui.action; import be.comicsdownloader.model.Model; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class RefreshActionListener implements ActionListener { private Model model; public RefreshActionListener(Model model) { this.model = model; } @Override public void actionPerformed(final ActionEvent ae) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { actionPerformed(ae); } }); } else { model.refreshData(); } } }
737
0.61194
0.61194
30
23.566668
19.335087
62
false
false
0
0
0
0
0
0
0.333333
false
false
7
fd987a30cd91a5e7dd945ecac5eba16b215ca30f
2,147,483,677,389
40c9a219a82638942601983d83ffcf48ebe94b3f
/QCloudCosXml/cosxml/src/androidTest/java/com/tencent/cos/xml/transfer/COSXMLCopyTaskTest.java
e5cfc440d2da776e937b5beb70dd15e2a36b6338
[ "MIT" ]
permissive
carolsuo/qcloud-sdk-android
https://github.com/carolsuo/qcloud-sdk-android
cf762f809f75347dd75b0047ff41ff568b2cc4ea
d2692edbdb78a99b1e279328d01f987053244d02
refs/heads/master
2023-06-10T05:18:47.275000
2019-12-05T12:38:41
2019-12-05T12:38:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package com.tencent.cos.xml.transfer; // //import android.support.test.InstrumentationRegistry; //import android.support.test.runner.AndroidJUnit4; //import android.util.Log; // //import com.tencent.cos.xml.CosXmlSimpleService; //import com.tencent.cos.xml.QServer; //import com.tencent.cos.xml.exception.CosXmlClientException; //import com.tencent.cos.xml.exception.CosXmlServiceException; //import com.tencent.cos.xml.listener.CosXmlResultListener; //import com.tencent.cos.xml.model.CosXmlRequest; //import com.tencent.cos.xml.model.CosXmlResult; //import com.tencent.cos.xml.model.object.CopyObjectRequest; //import com.tencent.cos.xml.model.object.PutObjectRequest; // //import org.junit.Assert; //import org.junit.Before; //import org.junit.Test; //import org.junit.runner.RunWith; // //import static com.tencent.cos.xml.QServer.TAG; // ///** // * Created by bradyxiao on 2018/9/26. // * Copyright 2010-2018 Tencent Cloud. All Rights Reserved. // */ //@RunWith(AndroidJUnit4.class) //public class COSXMLCopyTaskTest { // // TransferManager transferManager; // @Before // public void init() throws Exception{ // QServer.init(InstrumentationRegistry.getContext()); // } // // @Test // public void pause() throws Exception{ // String sourceCosPath = "upload_rn"; // String srcPath = QServer.createFile(InstrumentationRegistry.getContext(), 1024 * 1024); // PutObjectRequest putObjectRequest = new PutObjectRequest(QServer.persistBucket, sourceCosPath, srcPath); // QServer.cosXml.putObject(putObjectRequest); // QServer.deleteLocalFile(srcPath); // transferManager = new TransferManager((CosXmlSimpleService) QServer.cosXml, new TransferConfig.Builder(). // setDividsionForCopy(20*1024 * 1024).setSliceSizeForCopy(1024*1024).build()); // String cosPath = "upload_rn.copy"; // CopyObjectRequest.CopySourceStruct copySourceStruct = new CopyObjectRequest.CopySourceStruct( // QServer.appid, QServer.persistBucket, QServer.region, sourceCosPath); // COSXMLCopyTask cosxmlCopyTask = transferManager.copy(QServer.persistBucket, cosPath, copySourceStruct); // cosxmlCopyTask.setCosXmlProgressListener(null); // cosxmlCopyTask.setTransferStateListener(new TransferStateListener() { // @Override // public void onStateChanged(TransferState state) { // Log.d(TAG, state.name()); // } // }); // cosxmlCopyTask.setCosXmlResultListener(new CosXmlResultListener() { // @Override // public void onSuccess(CosXmlRequest request, CosXmlResult result) { // Log.d(TAG, result.printResult()); // } // // @Override // public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) { // Log.d(TAG, exception == null ? serviceException.getMessage() : exception.toString()); // } // }); // // while (cosxmlCopyTask.getTaskState() != TransferState.IN_PROGRESS){ // Thread.sleep(100); // } // cosxmlCopyTask.pause(); // Thread.sleep(1000); // Assert.assertEquals(cosxmlCopyTask.getTaskState(), TransferState.PAUSED); // } // // @Test // public void cancel() throws Exception{ // String sourceCosPath = "upload_rn"; // String srcPath = QServer.createFile(InstrumentationRegistry.getContext(), 1024 * 1024); // PutObjectRequest putObjectRequest = new PutObjectRequest(QServer.persistBucket, sourceCosPath, srcPath); // QServer.cosXml.putObject(putObjectRequest); // QServer.deleteLocalFile(srcPath); // transferManager = new TransferManager((CosXmlSimpleService) QServer.cosXml, new TransferConfig.Builder(). // setDividsionForCopy(20*1024 * 1024).setSliceSizeForCopy(1024*1024).build()); // String cosPath = "upload_rn.copy"; // CopyObjectRequest.CopySourceStruct copySourceStruct = new CopyObjectRequest.CopySourceStruct( // QServer.appid, QServer.persistBucket, QServer.region, sourceCosPath); // COSXMLCopyTask cosxmlCopyTask = transferManager.copy(QServer.persistBucket, cosPath, copySourceStruct); // cosxmlCopyTask.setCosXmlProgressListener(null); // cosxmlCopyTask.setTransferStateListener(new TransferStateListener() { // @Override // public void onStateChanged(TransferState state) { // Log.d(TAG, state.name()); // } // }); // cosxmlCopyTask.setCosXmlResultListener(new CosXmlResultListener() { // @Override // public void onSuccess(CosXmlRequest request, CosXmlResult result) { // Log.d(TAG, result.printResult()); // } // // @Override // public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) { // Log.d(TAG, exception == null ? serviceException.getMessage() : exception.toString()); // } // }); // while (cosxmlCopyTask.getTaskState() != TransferState.IN_PROGRESS){ // Thread.sleep(100); // } // cosxmlCopyTask.cancel(); // Thread.sleep(1000); // Assert.assertEquals(cosxmlCopyTask.getTaskState(), TransferState.CANCELED); // } // // @Test // public void resume() throws Exception{ // String sourceCosPath = "upload_rn"; // String srcPath = QServer.createFile(InstrumentationRegistry.getContext(), 1024 * 1024); // PutObjectRequest putObjectRequest = new PutObjectRequest(QServer.persistBucket, sourceCosPath, srcPath); // QServer.cosXml.putObject(putObjectRequest); // QServer.deleteLocalFile(srcPath); // transferManager = new TransferManager((CosXmlSimpleService) QServer.cosXml, new TransferConfig.Builder(). // setDividsionForCopy(1024 * 1024).setSliceSizeForCopy(1024*1024).build()); // String cosPath = "upload_rn.copy"; // // CopyObjectRequest.CopySourceStruct copySourceStruct = new CopyObjectRequest.CopySourceStruct( // QServer.appid, QServer.persistBucket, QServer.region, sourceCosPath); // COSXMLCopyTask cosxmlCopyTask = transferManager.copy(QServer.persistBucket, cosPath, copySourceStruct); // cosxmlCopyTask.setCosXmlProgressListener(null); // cosxmlCopyTask.setTransferStateListener(new TransferStateListener() { // @Override // public void onStateChanged(TransferState state) { // Log.d(TAG, state.name()); // } // }); // cosxmlCopyTask.setCosXmlResultListener(new CosXmlResultListener() { // @Override // public void onSuccess(CosXmlRequest request, CosXmlResult result) { // Log.d(TAG, result.printResult()); // } // // @Override // public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) { // Log.d(TAG, exception == null ? serviceException.getMessage() : exception.toString()); // } // }); // // while (cosxmlCopyTask.getTaskState() != TransferState.IN_PROGRESS){ // Thread.sleep(100); // } // cosxmlCopyTask.pause(); // Thread.sleep(500); // cosxmlCopyTask.resume(); // Assert.assertTrue(cosxmlCopyTask.getTaskState() == TransferState.RESUMED_WAITING); // Thread.sleep(500); // Assert.assertTrue(cosxmlCopyTask.getTaskState() == TransferState.IN_PROGRESS || // cosxmlCopyTask.getTaskState() == TransferState.COMPLETED || // cosxmlCopyTask.getTaskState() == TransferState.FAILED); // } // //}
UTF-8
Java
7,841
java
COSXMLCopyTaskTest.java
Java
[ { "context": "cent.cos.xml.QServer.TAG;\n//\n///**\n// * Created by bradyxiao on 2018/9/26.\n// * Copyright 2010-2018 Tencent Cl", "end": 876, "score": 0.9985594153404236, "start": 867, "tag": "USERNAME", "value": "bradyxiao" } ]
null
[]
//package com.tencent.cos.xml.transfer; // //import android.support.test.InstrumentationRegistry; //import android.support.test.runner.AndroidJUnit4; //import android.util.Log; // //import com.tencent.cos.xml.CosXmlSimpleService; //import com.tencent.cos.xml.QServer; //import com.tencent.cos.xml.exception.CosXmlClientException; //import com.tencent.cos.xml.exception.CosXmlServiceException; //import com.tencent.cos.xml.listener.CosXmlResultListener; //import com.tencent.cos.xml.model.CosXmlRequest; //import com.tencent.cos.xml.model.CosXmlResult; //import com.tencent.cos.xml.model.object.CopyObjectRequest; //import com.tencent.cos.xml.model.object.PutObjectRequest; // //import org.junit.Assert; //import org.junit.Before; //import org.junit.Test; //import org.junit.runner.RunWith; // //import static com.tencent.cos.xml.QServer.TAG; // ///** // * Created by bradyxiao on 2018/9/26. // * Copyright 2010-2018 Tencent Cloud. All Rights Reserved. // */ //@RunWith(AndroidJUnit4.class) //public class COSXMLCopyTaskTest { // // TransferManager transferManager; // @Before // public void init() throws Exception{ // QServer.init(InstrumentationRegistry.getContext()); // } // // @Test // public void pause() throws Exception{ // String sourceCosPath = "upload_rn"; // String srcPath = QServer.createFile(InstrumentationRegistry.getContext(), 1024 * 1024); // PutObjectRequest putObjectRequest = new PutObjectRequest(QServer.persistBucket, sourceCosPath, srcPath); // QServer.cosXml.putObject(putObjectRequest); // QServer.deleteLocalFile(srcPath); // transferManager = new TransferManager((CosXmlSimpleService) QServer.cosXml, new TransferConfig.Builder(). // setDividsionForCopy(20*1024 * 1024).setSliceSizeForCopy(1024*1024).build()); // String cosPath = "upload_rn.copy"; // CopyObjectRequest.CopySourceStruct copySourceStruct = new CopyObjectRequest.CopySourceStruct( // QServer.appid, QServer.persistBucket, QServer.region, sourceCosPath); // COSXMLCopyTask cosxmlCopyTask = transferManager.copy(QServer.persistBucket, cosPath, copySourceStruct); // cosxmlCopyTask.setCosXmlProgressListener(null); // cosxmlCopyTask.setTransferStateListener(new TransferStateListener() { // @Override // public void onStateChanged(TransferState state) { // Log.d(TAG, state.name()); // } // }); // cosxmlCopyTask.setCosXmlResultListener(new CosXmlResultListener() { // @Override // public void onSuccess(CosXmlRequest request, CosXmlResult result) { // Log.d(TAG, result.printResult()); // } // // @Override // public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) { // Log.d(TAG, exception == null ? serviceException.getMessage() : exception.toString()); // } // }); // // while (cosxmlCopyTask.getTaskState() != TransferState.IN_PROGRESS){ // Thread.sleep(100); // } // cosxmlCopyTask.pause(); // Thread.sleep(1000); // Assert.assertEquals(cosxmlCopyTask.getTaskState(), TransferState.PAUSED); // } // // @Test // public void cancel() throws Exception{ // String sourceCosPath = "upload_rn"; // String srcPath = QServer.createFile(InstrumentationRegistry.getContext(), 1024 * 1024); // PutObjectRequest putObjectRequest = new PutObjectRequest(QServer.persistBucket, sourceCosPath, srcPath); // QServer.cosXml.putObject(putObjectRequest); // QServer.deleteLocalFile(srcPath); // transferManager = new TransferManager((CosXmlSimpleService) QServer.cosXml, new TransferConfig.Builder(). // setDividsionForCopy(20*1024 * 1024).setSliceSizeForCopy(1024*1024).build()); // String cosPath = "upload_rn.copy"; // CopyObjectRequest.CopySourceStruct copySourceStruct = new CopyObjectRequest.CopySourceStruct( // QServer.appid, QServer.persistBucket, QServer.region, sourceCosPath); // COSXMLCopyTask cosxmlCopyTask = transferManager.copy(QServer.persistBucket, cosPath, copySourceStruct); // cosxmlCopyTask.setCosXmlProgressListener(null); // cosxmlCopyTask.setTransferStateListener(new TransferStateListener() { // @Override // public void onStateChanged(TransferState state) { // Log.d(TAG, state.name()); // } // }); // cosxmlCopyTask.setCosXmlResultListener(new CosXmlResultListener() { // @Override // public void onSuccess(CosXmlRequest request, CosXmlResult result) { // Log.d(TAG, result.printResult()); // } // // @Override // public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) { // Log.d(TAG, exception == null ? serviceException.getMessage() : exception.toString()); // } // }); // while (cosxmlCopyTask.getTaskState() != TransferState.IN_PROGRESS){ // Thread.sleep(100); // } // cosxmlCopyTask.cancel(); // Thread.sleep(1000); // Assert.assertEquals(cosxmlCopyTask.getTaskState(), TransferState.CANCELED); // } // // @Test // public void resume() throws Exception{ // String sourceCosPath = "upload_rn"; // String srcPath = QServer.createFile(InstrumentationRegistry.getContext(), 1024 * 1024); // PutObjectRequest putObjectRequest = new PutObjectRequest(QServer.persistBucket, sourceCosPath, srcPath); // QServer.cosXml.putObject(putObjectRequest); // QServer.deleteLocalFile(srcPath); // transferManager = new TransferManager((CosXmlSimpleService) QServer.cosXml, new TransferConfig.Builder(). // setDividsionForCopy(1024 * 1024).setSliceSizeForCopy(1024*1024).build()); // String cosPath = "upload_rn.copy"; // // CopyObjectRequest.CopySourceStruct copySourceStruct = new CopyObjectRequest.CopySourceStruct( // QServer.appid, QServer.persistBucket, QServer.region, sourceCosPath); // COSXMLCopyTask cosxmlCopyTask = transferManager.copy(QServer.persistBucket, cosPath, copySourceStruct); // cosxmlCopyTask.setCosXmlProgressListener(null); // cosxmlCopyTask.setTransferStateListener(new TransferStateListener() { // @Override // public void onStateChanged(TransferState state) { // Log.d(TAG, state.name()); // } // }); // cosxmlCopyTask.setCosXmlResultListener(new CosXmlResultListener() { // @Override // public void onSuccess(CosXmlRequest request, CosXmlResult result) { // Log.d(TAG, result.printResult()); // } // // @Override // public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) { // Log.d(TAG, exception == null ? serviceException.getMessage() : exception.toString()); // } // }); // // while (cosxmlCopyTask.getTaskState() != TransferState.IN_PROGRESS){ // Thread.sleep(100); // } // cosxmlCopyTask.pause(); // Thread.sleep(500); // cosxmlCopyTask.resume(); // Assert.assertTrue(cosxmlCopyTask.getTaskState() == TransferState.RESUMED_WAITING); // Thread.sleep(500); // Assert.assertTrue(cosxmlCopyTask.getTaskState() == TransferState.IN_PROGRESS || // cosxmlCopyTask.getTaskState() == TransferState.COMPLETED || // cosxmlCopyTask.getTaskState() == TransferState.FAILED); // } // //}
7,841
0.660247
0.645453
162
47.407406
35.327492
131
false
false
0
0
0
0
0
0
0.808642
false
false
7
fb25cb95bcb415a92c7e80ca4079d05d0d97f32c
6,786,048,365,266
7f8568471fafb2ee5dea2171950284c078d6bae5
/src/test/java/com/referenceit/otherprintsource/dictorinaryencyclopaedia/DictAndEncyServiceTest.java
d7af40d87686926117fd95e127d31ec68962f5a8
[]
no_license
spazzola/ReferenceIt
https://github.com/spazzola/ReferenceIt
4ca74edce5f60c79e5df35b13b35f676d7780605
309a9e3a4447edde43d463caf825f9448ded682d
refs/heads/master
2023-01-10T23:15:26.586000
2020-10-31T21:02:41
2020-10-31T21:02:41
271,102,634
0
0
null
false
2020-06-09T20:39:05
2020-06-09T20:25:10
2020-06-09T20:38:28
2020-06-09T20:39:04
0
0
0
1
JavaScript
false
false
package com.referenceit.otherprintsource.dictorinaryencyclopaedia; import com.referenceit.otherprintsource.dictionaryencyclopaedia.DictAndEncyDto; import com.referenceit.otherprintsource.dictionaryencyclopaedia.DictAndEncyService; import com.referenceit.reference.Author; import com.referenceit.reference.Editor; import com.referenceit.reference.ReferenceResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest @RunWith(SpringRunner.class) public class DictAndEncyServiceTest { @Autowired private DictAndEncyService dictAndEncyService; @Test public void shouldPassReferencingDictionaryOrEncyclopaediasWithoutEditionWithVolumeNumber() { //given List<Author> authors = Arrays.asList(new Author("Raul", "Paul", "Kesner")); List<Editor> editors = Arrays.asList(new Editor("Vinc", "Synt", "Ramachandran")); DictAndEncyDto dictAndEncyDto = DictAndEncyDto.builder() .authors(authors) .editors(editors) .title("Encyclopedia of the human brain") .chapterTitle("Memory neurobiology") .year("2002") .publicationPlace("San Diego") .publisher("Academic Press") .volumeNumber("2") .pages("783-796") .build(); //when ReferenceResponse referenceResponse = dictAndEncyService.generateReference(dictAndEncyDto); //then String expectedResult = "KESNER, R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) " + "Encyclopedia of the human brain, Vol. 2. San Diego: Academic Press, pp. 783-796."; assertEquals(expectedResult, referenceResponse.toString()); } @Test public void shouldPassReferencingDictionaryOrEncyclopaediasWithVolumeNumberEdition() { //given List<Author> authors = Arrays.asList(new Author("Raul", "Paul", "Kesner")); List<Editor> editors = Arrays.asList(new Editor("Vinc", "Synt", "Ramachandran")); DictAndEncyDto dictAndEncyDto = DictAndEncyDto.builder() .authors(authors) .editors(editors) .title("Encyclopedia of the human brain") .chapterTitle("Memory neurobiology") .year("2002") .publicationPlace("San Diego") .publisher("Academic Press") .edition("3") .volumeNumber("2") .pages("783-796") .build(); //when ReferenceResponse referenceResponse = dictAndEncyService.generateReference(dictAndEncyDto); //then String expectedResult = "KESNER, R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) " + "Encyclopedia of the human brain, Vol. 2. 3rd ed. San Diego: Academic Press, pp. 783-796."; assertEquals(expectedResult, referenceResponse.toString()); } @Test public void shouldPassReferencingDictionaryOrEncyclopaediasWithoutEditionAndVolumeNumber() { //given List<Author> authors = Arrays.asList(new Author("Raul", "Paul", "Kesner")); List<Editor> editors = Arrays.asList(new Editor("Vinc", "Synt", "Ramachandran")); DictAndEncyDto dictAndEncyDto = DictAndEncyDto.builder() .authors(authors) .editors(editors) .title("Encyclopedia of the human brain") .chapterTitle("Memory neurobiology") .year("2002") .publicationPlace("San Diego") .publisher("Academic Press") .pages("783-796") .build(); //when ReferenceResponse referenceResponse = dictAndEncyService.generateReference(dictAndEncyDto); //then String expectedResult = "KESNER, R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) " + "Encyclopedia of the human brain. San Diego: Academic Press, pp. 783-796."; assertEquals(expectedResult, referenceResponse.toString()); } }
UTF-8
Java
4,383
java
DictAndEncyServiceTest.java
Java
[ { "context": " List<Author> authors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editor", "end": 1056, "score": 0.9998713731765747, "start": 1052, "tag": "NAME", "value": "Raul" }, { "context": "thor> authors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editors = Arra", "end": 1064, "score": 0.9998393058776855, "start": 1060, "tag": "NAME", "value": "Paul" }, { "context": "thors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editors = Arrays.asList(", "end": 1074, "score": 0.9998290538787842, "start": 1068, "tag": "NAME", "value": "Kesner" }, { "context": " List<Editor> editors = Arrays.asList(new Editor(\"Vinc\", \"Synt\", \"Ramachandran\"));\n DictAndEnc", "end": 1137, "score": 0.6284109950065613, "start": 1136, "tag": "NAME", "value": "V" }, { "context": "itor> editors = Arrays.asList(new Editor(\"Vinc\", \"Synt\", \"Ramachandran\"));\n DictAndEncyDto dictAn", "end": 1148, "score": 0.6053445339202881, "start": 1144, "tag": "NAME", "value": "Synt" }, { "context": "itors = Arrays.asList(new Editor(\"Vinc\", \"Synt\", \"Ramachandran\"));\n DictAndEncyDto dictAndEncyDto = DictA", "end": 1164, "score": 0.8468238711357117, "start": 1152, "tag": "NAME", "value": "Ramachandran" }, { "context": "\n\n //then\n String expectedResult = \"KESNER, R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.", "end": 1806, "score": 0.9440325498580933, "start": 1795, "tag": "NAME", "value": "KESNER, R.P" }, { "context": " List<Author> authors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editor", "end": 2223, "score": 0.9998309016227722, "start": 2219, "tag": "NAME", "value": "Raul" }, { "context": "thor> authors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editors = Arra", "end": 2231, "score": 0.9998451471328735, "start": 2227, "tag": "NAME", "value": "Paul" }, { "context": "thors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editors = Arrays.asList(", "end": 2241, "score": 0.9997962117195129, "start": 2235, "tag": "NAME", "value": "Kesner" }, { "context": "List<Editor> editors = Arrays.asList(new Editor(\"Vinc\", \"Synt\", \"Ramachandran\"));\n DictAndEncyDt", "end": 2307, "score": 0.5735974907875061, "start": 2304, "tag": "NAME", "value": "inc" }, { "context": "itor> editors = Arrays.asList(new Editor(\"Vinc\", \"Synt\", \"Ramachandran\"));\n DictAndEncyDto dictAn", "end": 2315, "score": 0.720015287399292, "start": 2311, "tag": "NAME", "value": "Synt" }, { "context": "\n\n //then\n String expectedResult = \"KESNER, R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.", "end": 3003, "score": 0.8995231986045837, "start": 2992, "tag": "NAME", "value": "KESNER, R.P" }, { "context": " List<Author> authors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editor", "end": 3434, "score": 0.9998579025268555, "start": 3430, "tag": "NAME", "value": "Raul" }, { "context": "thor> authors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editors = Arra", "end": 3442, "score": 0.9998530149459839, "start": 3438, "tag": "NAME", "value": "Paul" }, { "context": "thors = Arrays.asList(new Author(\"Raul\", \"Paul\", \"Kesner\"));\n List<Editor> editors = Arrays.asList(", "end": 3452, "score": 0.9998300671577454, "start": 3446, "tag": "NAME", "value": "Kesner" }, { "context": "itor> editors = Arrays.asList(new Editor(\"Vinc\", \"Synt\", \"Ramachandran\"));\n DictAndEncyDto dictAn", "end": 3526, "score": 0.6886346340179443, "start": 3522, "tag": "NAME", "value": "Synt" }, { "context": "itors = Arrays.asList(new Editor(\"Vinc\", \"Synt\", \"Ramachandran\"));\n DictAndEncyDto dictAndEncyDto = Di", "end": 3539, "score": 0.6008796095848083, "start": 3530, "tag": "NAME", "value": "Ramachand" }, { "context": "\n\n //then\n String expectedResult = \"KESNER, R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.", "end": 4150, "score": 0.9995995759963989, "start": 4139, "tag": "NAME", "value": "KESNER, R.P" }, { "context": "lt = \"KESNER, R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) \" +\n \"Encyclopedia of ", "end": 4196, "score": 0.9533452391624451, "start": 4184, "tag": "NAME", "value": "RAMACHANDRAN" }, { "context": "R.P. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) \" +\n \"Encyclopedia of the h", "end": 4201, "score": 0.7285929322242737, "start": 4198, "tag": "NAME", "value": "V.S" } ]
null
[]
package com.referenceit.otherprintsource.dictorinaryencyclopaedia; import com.referenceit.otherprintsource.dictionaryencyclopaedia.DictAndEncyDto; import com.referenceit.otherprintsource.dictionaryencyclopaedia.DictAndEncyService; import com.referenceit.reference.Author; import com.referenceit.reference.Editor; import com.referenceit.reference.ReferenceResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest @RunWith(SpringRunner.class) public class DictAndEncyServiceTest { @Autowired private DictAndEncyService dictAndEncyService; @Test public void shouldPassReferencingDictionaryOrEncyclopaediasWithoutEditionWithVolumeNumber() { //given List<Author> authors = Arrays.asList(new Author("Raul", "Paul", "Kesner")); List<Editor> editors = Arrays.asList(new Editor("Vinc", "Synt", "Ramachandran")); DictAndEncyDto dictAndEncyDto = DictAndEncyDto.builder() .authors(authors) .editors(editors) .title("Encyclopedia of the human brain") .chapterTitle("Memory neurobiology") .year("2002") .publicationPlace("San Diego") .publisher("Academic Press") .volumeNumber("2") .pages("783-796") .build(); //when ReferenceResponse referenceResponse = dictAndEncyService.generateReference(dictAndEncyDto); //then String expectedResult = "<NAME>. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) " + "Encyclopedia of the human brain, Vol. 2. San Diego: Academic Press, pp. 783-796."; assertEquals(expectedResult, referenceResponse.toString()); } @Test public void shouldPassReferencingDictionaryOrEncyclopaediasWithVolumeNumberEdition() { //given List<Author> authors = Arrays.asList(new Author("Raul", "Paul", "Kesner")); List<Editor> editors = Arrays.asList(new Editor("Vinc", "Synt", "Ramachandran")); DictAndEncyDto dictAndEncyDto = DictAndEncyDto.builder() .authors(authors) .editors(editors) .title("Encyclopedia of the human brain") .chapterTitle("Memory neurobiology") .year("2002") .publicationPlace("San Diego") .publisher("Academic Press") .edition("3") .volumeNumber("2") .pages("783-796") .build(); //when ReferenceResponse referenceResponse = dictAndEncyService.generateReference(dictAndEncyDto); //then String expectedResult = "<NAME>. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) " + "Encyclopedia of the human brain, Vol. 2. 3rd ed. San Diego: Academic Press, pp. 783-796."; assertEquals(expectedResult, referenceResponse.toString()); } @Test public void shouldPassReferencingDictionaryOrEncyclopaediasWithoutEditionAndVolumeNumber() { //given List<Author> authors = Arrays.asList(new Author("Raul", "Paul", "Kesner")); List<Editor> editors = Arrays.asList(new Editor("Vinc", "Synt", "Ramachandran")); DictAndEncyDto dictAndEncyDto = DictAndEncyDto.builder() .authors(authors) .editors(editors) .title("Encyclopedia of the human brain") .chapterTitle("Memory neurobiology") .year("2002") .publicationPlace("San Diego") .publisher("Academic Press") .pages("783-796") .build(); //when ReferenceResponse referenceResponse = dictAndEncyService.generateReference(dictAndEncyDto); //then String expectedResult = "<NAME>. (2002) Memory neurobiology. In: RAMACHANDRAN, V.S. (ed.) " + "Encyclopedia of the human brain. San Diego: Academic Press, pp. 783-796."; assertEquals(expectedResult, referenceResponse.toString()); } }
4,368
0.64522
0.629934
109
39.21101
32.773079
107
false
false
0
0
0
0
77
0.050878
0.541284
false
false
7
65468ad08cf78422d74c040a5e86c2622daa8c26
6,786,048,362,522
6ff1892fc7a42cc357c7310fee945063460e1d82
/src/main/java/com/xiaou/structure/CircleSingleLinkedTest.java
e39757956d3bf93b240a281a52317e5cead66aaa
[]
no_license
xiaou66/lower_code
https://github.com/xiaou66/lower_code
eaf088a45fbf359a8f964c69813805e2d2df3600
eaff77a651d4129c6fad11b4fbabb6290e22219b
refs/heads/master
2022-12-23T13:03:52.906000
2020-10-07T01:09:10
2020-10-07T01:09:10
301,893,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xiaou.structure; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author xiaou */ public class CircleSingleLinkedTest { private CircleSingleLinked<Integer> circleSingleLinked; @Before public void before() { circleSingleLinked = new CircleSingleLinked<Integer>(); } @Test public void addTest() { circleSingleLinked.add(1); circleSingleLinked.add(2); circleSingleLinked.add(3); circleSingleLinked.add(4); circleSingleLinked.add(5); //2->4->1->5->3 } @Test public void YSFQuestionTest() { addTest(); System.out.println(circleSingleLinked.YSFQuestion(2, 0)); } }
UTF-8
Java
719
java
CircleSingleLinkedTest.java
Java
[ { "context": "nit.Before;\nimport org.junit.Test;\n\n/**\n * @author xiaou\n */\npublic class CircleSingleLinkedTest {\n pri", "end": 123, "score": 0.910198986530304, "start": 118, "tag": "USERNAME", "value": "xiaou" } ]
null
[]
package com.xiaou.structure; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author xiaou */ public class CircleSingleLinkedTest { private CircleSingleLinked<Integer> circleSingleLinked; @Before public void before() { circleSingleLinked = new CircleSingleLinked<Integer>(); } @Test public void addTest() { circleSingleLinked.add(1); circleSingleLinked.add(2); circleSingleLinked.add(3); circleSingleLinked.add(4); circleSingleLinked.add(5); //2->4->1->5->3 } @Test public void YSFQuestionTest() { addTest(); System.out.println(circleSingleLinked.YSFQuestion(2, 0)); } }
719
0.642559
0.625869
33
20.818182
18.26647
65
false
false
0
0
0
0
0
0
0.424242
false
false
7
38bfa417308d466415a1324b71984d8f9d76275d
27,135,603,415,145
4a11a55fbe923ff45aab8131624cbdceb551b4a2
/app/src/main/java/com/teammvp/peregrinate/RegisterActivity.java
bc8e25d6cb9f5b3911220c23743e5ee0cdf6a277
[]
no_license
jennofred/peregrinate
https://github.com/jennofred/peregrinate
d955409376a59b60c224ad067458c0342aa78d49
b093de081a598a07906cf066677453110fb72dbf
refs/heads/master
2021-01-10T09:06:41.294000
2016-01-13T14:33:14
2016-01-13T14:33:14
49,579,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.teammvp.peregrinate; import android.app.AlertDialog; import android.app.FragmentTransaction; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.media.Image; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.transition.TransitionInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.w3c.dom.Text; public class RegisterActivity extends AppCompatActivity { String emailStr, passwordStr, usernameStr, birthdayStr, genderStr; EditText emailTextFieldSignUp, usernameTextFieldSignUp, passwordTextFieldSignUp, birthdayTextFieldSignUp, genderTextFieldSignUp; ImageView emptyEmail, emptyUsername, emptyPassword, emptyBirthday, emptyGender; Button signUpButton; ListView gender = null; AlertDialog genderDialog = null; NetworkInfo mWifi; NetworkInfo mMobile; ConnectivityManager connManager; ProgressDialog dialog = null; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; List<NameValuePair> nameValuePairs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); if (Build.VERSION.SDK_INT >= 21) { getWindow().setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.shared_element_transition_login)); } Typeface bebasNeue = Typeface.createFromAsset(getAssets(), "fonts/BebasNeue.otf"); Typeface helveticaNeue = Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeue.otf"); emailTextFieldSignUp = (EditText) findViewById(R.id.emailTextFieldSignUp); usernameTextFieldSignUp = (EditText) findViewById(R.id.usernameTextFieldSignUp); passwordTextFieldSignUp = (EditText) findViewById(R.id.passwordTextFieldSignUp); birthdayTextFieldSignUp = (EditText) findViewById(R.id.birthdayTextFieldSignUp); genderTextFieldSignUp = (EditText) findViewById(R.id.genderTextFieldSignUp); signUpButton = (Button) findViewById(R.id.signUpButton); emailTextFieldSignUp.setTypeface(helveticaNeue); usernameTextFieldSignUp.setTypeface(helveticaNeue); passwordTextFieldSignUp.setTypeface(helveticaNeue); birthdayTextFieldSignUp.setTypeface(helveticaNeue); genderTextFieldSignUp.setTypeface(helveticaNeue); signUpButton.setTypeface(bebasNeue); emptyEmail = (ImageView) findViewById(R.id.emptyEmail); emptyPassword = (ImageView) findViewById(R.id.emptyPassword); emptyUsername = (ImageView) findViewById(R.id.emptyUsername); emptyBirthday = (ImageView) findViewById(R.id.emptyBirthday); emptyGender = (ImageView) findViewById(R.id.emptyGender); birthdayTextFieldSignUp.setInputType(0); genderTextFieldSignUp.setInputType(0); gender = new ListView(this); String[] genderString = {"Male", "Female"}; ArrayAdapter<String> genderAdapter = new ArrayAdapter<String>(this, R.layout.gender_list, R.id.genderList, genderString); gender.setAdapter(genderAdapter); gender.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ViewGroup viewGroup = (ViewGroup) view; TextView txt = (TextView) viewGroup.findViewById(R.id.genderList); String selectedGender = txt.getText().toString(); genderTextFieldSignUp.setText(selectedGender); genderDialog.dismiss(); } }); connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // mWifi = connManager.getActiveNetworkInfo(); mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); birthdayTextFieldSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(birthdayTextFieldSignUp.getWindowToken(), 0); DatePickerDialog dialog = new DatePickerDialog(v); dialog.setCancelable(true); FragmentTransaction ft = getFragmentManager().beginTransaction(); dialog.show(ft, "DatePicker"); } }); genderTextFieldSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(genderTextFieldSignUp.getWindowToken(), 0); AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setCancelable(true); builder.setView(gender); if (genderDialog == null) { genderDialog = builder.create(); } genderDialog.show(); } }); signUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { emptyEmail.setVisibility(View.INVISIBLE); emptyPassword.setVisibility(View.INVISIBLE); emptyUsername.setVisibility(View.INVISIBLE); emptyBirthday.setVisibility(View.INVISIBLE); emptyGender.setVisibility(View.INVISIBLE); emailStr = emailTextFieldSignUp.getText().toString().trim(); passwordStr = passwordTextFieldSignUp.getText().toString().trim(); usernameStr = usernameTextFieldSignUp.getText().toString().trim(); birthdayStr = birthdayTextFieldSignUp.getText().toString().trim(); genderStr = genderTextFieldSignUp.getText().toString().trim(); if (emailStr.length() == 0) { emptyEmail.setVisibility(View.VISIBLE); } if (passwordStr.length() == 0) { emptyPassword.setVisibility(View.VISIBLE); } if (usernameStr.length() == 0) { emptyUsername.setVisibility(View.VISIBLE); } if (birthdayStr.length() == 0) { emptyBirthday.setVisibility(View.VISIBLE); } if (genderStr.length() == 0) { emptyGender.setVisibility(View.VISIBLE); } if (passwordStr.length() != 0 && emailStr.length() != 0 && usernameStr.length() != 0 && birthdayStr.length() != 0 && genderStr.length() != 0) { if (mWifi.isConnected() || mMobile.isConnected()) { dialog = ProgressDialog.show(RegisterActivity.this, "", "Please wait...", true); new Thread(new Runnable() { public void run() { Check(); } }).start(); } else { Snackbar.make(v, "You don't have internet connection", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } } } }); } public void onStart() { super.onStart(); final EditText textDate = (EditText) findViewById(R.id.birthdayTextFieldSignUp); textDate.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(textDate.getWindowToken(), 0); DatePickerDialog dialog = new DatePickerDialog(v); FragmentTransaction ft = getFragmentManager().beginTransaction(); dialog.show(ft, "DatePicker"); } } }); final EditText genderTextField = (EditText) findViewById(R.id.genderTextFieldSignUp); genderTextField.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(genderTextField.getWindowToken(), 0); AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setTitle("Choose your gender"); builder.setCancelable(true); builder.setView(gender); if (genderDialog == null) { genderDialog = builder.create(); } genderDialog.show(); } } }); } public void Check() { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://peregrinate.esy.es/android/user/regcheck.php"); nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("email", emailTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("username", usernameTextFieldSignUp.getText().toString().trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); runOnUiThread(new Runnable() { public void run() { if (response.equalsIgnoreCase("Username already exist!")) { Toast.makeText(getApplicationContext(), "Username already exist! Please try another one.", Toast.LENGTH_SHORT).show(); } dialog.dismiss(); } }); if (response.equalsIgnoreCase("Username is valid")) { Reg(); } else { showAlert(); } } catch (Exception e) { dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } public void Reg() { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://peregrinate.esy.es/android/user/register.php"); nameValuePairs = new ArrayList<NameValuePair>(5); nameValuePairs.add(new BasicNameValuePair("email", emailTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("username", usernameTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("password", passwordTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("birthday", birthdayTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("gender", genderTextFieldSignUp.getText().toString().trim().toLowerCase())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); runOnUiThread(new Runnable() { public void run() { Toast.makeText(RegisterActivity.this, "Registration Successful. You can now login.", Toast.LENGTH_SHORT).show(); } }); dialog.dismiss(); startActivity(new Intent(this, LoginActivity.class)); } catch (Exception e) { dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } public void showAlert() { RegisterActivity.this.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setTitle("Error"); builder.setMessage("Username or email already exist!") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } }); } }
UTF-8
Java
14,197
java
RegisterActivity.java
Java
[ { "context": "eValuePairs.add(new BasicNameValuePair(\"username\", usernameTextFieldSignUp.getText().toString().trim()));\n ", "end": 12440, "score": 0.9204999804496765, "start": 12432, "tag": "USERNAME", "value": "username" }, { "context": "eValuePairs.add(new BasicNameValuePair(\"password\", passwordTextFieldSignUp.getText().toString().trim()));\n ", "end": 12561, "score": 0.536493182182312, "start": 12553, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.teammvp.peregrinate; import android.app.AlertDialog; import android.app.FragmentTransaction; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.media.Image; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.transition.TransitionInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.w3c.dom.Text; public class RegisterActivity extends AppCompatActivity { String emailStr, passwordStr, usernameStr, birthdayStr, genderStr; EditText emailTextFieldSignUp, usernameTextFieldSignUp, passwordTextFieldSignUp, birthdayTextFieldSignUp, genderTextFieldSignUp; ImageView emptyEmail, emptyUsername, emptyPassword, emptyBirthday, emptyGender; Button signUpButton; ListView gender = null; AlertDialog genderDialog = null; NetworkInfo mWifi; NetworkInfo mMobile; ConnectivityManager connManager; ProgressDialog dialog = null; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; List<NameValuePair> nameValuePairs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); if (Build.VERSION.SDK_INT >= 21) { getWindow().setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.shared_element_transition_login)); } Typeface bebasNeue = Typeface.createFromAsset(getAssets(), "fonts/BebasNeue.otf"); Typeface helveticaNeue = Typeface.createFromAsset(getAssets(), "fonts/HelveticaNeue.otf"); emailTextFieldSignUp = (EditText) findViewById(R.id.emailTextFieldSignUp); usernameTextFieldSignUp = (EditText) findViewById(R.id.usernameTextFieldSignUp); passwordTextFieldSignUp = (EditText) findViewById(R.id.passwordTextFieldSignUp); birthdayTextFieldSignUp = (EditText) findViewById(R.id.birthdayTextFieldSignUp); genderTextFieldSignUp = (EditText) findViewById(R.id.genderTextFieldSignUp); signUpButton = (Button) findViewById(R.id.signUpButton); emailTextFieldSignUp.setTypeface(helveticaNeue); usernameTextFieldSignUp.setTypeface(helveticaNeue); passwordTextFieldSignUp.setTypeface(helveticaNeue); birthdayTextFieldSignUp.setTypeface(helveticaNeue); genderTextFieldSignUp.setTypeface(helveticaNeue); signUpButton.setTypeface(bebasNeue); emptyEmail = (ImageView) findViewById(R.id.emptyEmail); emptyPassword = (ImageView) findViewById(R.id.emptyPassword); emptyUsername = (ImageView) findViewById(R.id.emptyUsername); emptyBirthday = (ImageView) findViewById(R.id.emptyBirthday); emptyGender = (ImageView) findViewById(R.id.emptyGender); birthdayTextFieldSignUp.setInputType(0); genderTextFieldSignUp.setInputType(0); gender = new ListView(this); String[] genderString = {"Male", "Female"}; ArrayAdapter<String> genderAdapter = new ArrayAdapter<String>(this, R.layout.gender_list, R.id.genderList, genderString); gender.setAdapter(genderAdapter); gender.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ViewGroup viewGroup = (ViewGroup) view; TextView txt = (TextView) viewGroup.findViewById(R.id.genderList); String selectedGender = txt.getText().toString(); genderTextFieldSignUp.setText(selectedGender); genderDialog.dismiss(); } }); connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // mWifi = connManager.getActiveNetworkInfo(); mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); birthdayTextFieldSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(birthdayTextFieldSignUp.getWindowToken(), 0); DatePickerDialog dialog = new DatePickerDialog(v); dialog.setCancelable(true); FragmentTransaction ft = getFragmentManager().beginTransaction(); dialog.show(ft, "DatePicker"); } }); genderTextFieldSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(genderTextFieldSignUp.getWindowToken(), 0); AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setCancelable(true); builder.setView(gender); if (genderDialog == null) { genderDialog = builder.create(); } genderDialog.show(); } }); signUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { emptyEmail.setVisibility(View.INVISIBLE); emptyPassword.setVisibility(View.INVISIBLE); emptyUsername.setVisibility(View.INVISIBLE); emptyBirthday.setVisibility(View.INVISIBLE); emptyGender.setVisibility(View.INVISIBLE); emailStr = emailTextFieldSignUp.getText().toString().trim(); passwordStr = passwordTextFieldSignUp.getText().toString().trim(); usernameStr = usernameTextFieldSignUp.getText().toString().trim(); birthdayStr = birthdayTextFieldSignUp.getText().toString().trim(); genderStr = genderTextFieldSignUp.getText().toString().trim(); if (emailStr.length() == 0) { emptyEmail.setVisibility(View.VISIBLE); } if (passwordStr.length() == 0) { emptyPassword.setVisibility(View.VISIBLE); } if (usernameStr.length() == 0) { emptyUsername.setVisibility(View.VISIBLE); } if (birthdayStr.length() == 0) { emptyBirthday.setVisibility(View.VISIBLE); } if (genderStr.length() == 0) { emptyGender.setVisibility(View.VISIBLE); } if (passwordStr.length() != 0 && emailStr.length() != 0 && usernameStr.length() != 0 && birthdayStr.length() != 0 && genderStr.length() != 0) { if (mWifi.isConnected() || mMobile.isConnected()) { dialog = ProgressDialog.show(RegisterActivity.this, "", "Please wait...", true); new Thread(new Runnable() { public void run() { Check(); } }).start(); } else { Snackbar.make(v, "You don't have internet connection", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } } } }); } public void onStart() { super.onStart(); final EditText textDate = (EditText) findViewById(R.id.birthdayTextFieldSignUp); textDate.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(textDate.getWindowToken(), 0); DatePickerDialog dialog = new DatePickerDialog(v); FragmentTransaction ft = getFragmentManager().beginTransaction(); dialog.show(ft, "DatePicker"); } } }); final EditText genderTextField = (EditText) findViewById(R.id.genderTextFieldSignUp); genderTextField.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(genderTextField.getWindowToken(), 0); AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setTitle("Choose your gender"); builder.setCancelable(true); builder.setView(gender); if (genderDialog == null) { genderDialog = builder.create(); } genderDialog.show(); } } }); } public void Check() { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://peregrinate.esy.es/android/user/regcheck.php"); nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("email", emailTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("username", usernameTextFieldSignUp.getText().toString().trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); runOnUiThread(new Runnable() { public void run() { if (response.equalsIgnoreCase("Username already exist!")) { Toast.makeText(getApplicationContext(), "Username already exist! Please try another one.", Toast.LENGTH_SHORT).show(); } dialog.dismiss(); } }); if (response.equalsIgnoreCase("Username is valid")) { Reg(); } else { showAlert(); } } catch (Exception e) { dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } public void Reg() { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://peregrinate.esy.es/android/user/register.php"); nameValuePairs = new ArrayList<NameValuePair>(5); nameValuePairs.add(new BasicNameValuePair("email", emailTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("username", usernameTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("password", <PASSWORD>TextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("birthday", birthdayTextFieldSignUp.getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("gender", genderTextFieldSignUp.getText().toString().trim().toLowerCase())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); runOnUiThread(new Runnable() { public void run() { Toast.makeText(RegisterActivity.this, "Registration Successful. You can now login.", Toast.LENGTH_SHORT).show(); } }); dialog.dismiss(); startActivity(new Intent(this, LoginActivity.class)); } catch (Exception e) { dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } public void showAlert() { RegisterActivity.this.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this); builder.setTitle("Error"); builder.setMessage("Username or email already exist!") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } }); } }
14,199
0.626189
0.624639
309
44.944984
32.816746
159
false
false
0
0
0
0
0
0
0.763754
false
false
7
e4022aa78ff0c82ad2af7dfe85dee576c4b28306
30,210,799,966,206
1c4fc36054ca6ef9b229fbfd7354dec142c09ff4
/src/main/java/com/prometheus/ledger/core/model/error/BaseErrorCode.java
642f5bd34b5ce49cdddbb03eff647f19f93e0bbe
[ "BSD-2-Clause" ]
permissive
bonggal2/ledger
https://github.com/bonggal2/ledger
25a8ac3902b0e387ae6620650f21e9ce4da094b7
ca4aca3dcf60e3e78d6616aa8d78f8f00d2a3636
refs/heads/master
2022-12-08T21:00:14.920000
2020-09-12T17:07:06
2020-09-12T17:07:06
295,005,848
0
0
BSD-2-Clause
true
2020-09-12T18:47:19
2020-09-12T18:47:18
2020-09-12T17:07:12
2020-09-12T18:34:16
16,779
0
0
0
null
false
false
package com.prometheus.ledger.core.model.error; public interface BaseErrorCode { String getErrorCode(); String getErrorMessage(); }
UTF-8
Java
141
java
BaseErrorCode.java
Java
[]
null
[]
package com.prometheus.ledger.core.model.error; public interface BaseErrorCode { String getErrorCode(); String getErrorMessage(); }
141
0.758865
0.758865
6
22.5
16.899212
47
false
false
0
0
0
0
0
0
0.5
false
false
7
181cc63326af213632512b560099f946152caad8
15,788,299,821,773
4bae3208f7365cea15acf3fb359207226d1f64bb
/modeshape-jcr/src/main/java/org/modeshape/jcr/value/ValueTypeSystem.java
a08da8a092db3586d2aaf74dd85b4e65a420c4a6
[ "Apache-2.0" ]
permissive
teiid/teiid-modeshape
https://github.com/teiid/teiid-modeshape
ad4c7622d4c7f8297684600177334ef8af66c397
8dffe84d2cc7d8b7e48f84efc49a1b0a5e46faa6
refs/heads/master
2023-09-01T07:34:07.609000
2019-07-26T16:57:25
2019-07-26T16:57:25
114,037,491
0
6
Apache-2.0
false
2022-06-21T01:23:43
2017-12-12T20:46:38
2019-07-26T16:57:28
2022-06-21T01:23:40
22,371
1
5
6
Java
false
false
/* * ModeShape (http://www.modeshape.org) * * 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 org.modeshape.jcr.value; import java.math.BigDecimal; import java.net.URI; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import org.modeshape.common.util.Base64; import org.modeshape.jcr.api.value.DateTime; import org.modeshape.jcr.cache.NodeKey; import org.modeshape.jcr.query.model.TypeSystem; import org.modeshape.jcr.value.basic.NodeKeyReference; /** * */ public final class ValueTypeSystem extends TypeSystem { private final String defaultTypeName; protected final ValueFactories valueFactories; protected final ValueFactory<String> stringValueFactory; private final Map<PropertyType, TypeFactory<?>> typeFactoriesByPropertyType; private final Map<String, TypeFactory<?>> typeFactoriesByName; private final Map<String, PropertyType> propertyTypeByName; private final TypeFactory<String> stringFactory; private final TypeFactory<Boolean> booleanFactory; private final TypeFactory<Long> longFactory; private final TypeFactory<Double> doubleFactory; private final TypeFactory<BigDecimal> decimalFactory; private final TypeFactory<DateTime> dateFactory; private final TypeFactory<Path> pathFactory; private final TypeFactory<Name> nameFactory; private final TypeFactory<Reference> referenceFactory; private final TypeFactory<BinaryValue> binaryFactory; private final TypeFactory<NodeKey> nodeKeyFactory; /** * Create a type system using the supplied value factories. * * @param valueFactories the value factories; * @throws IllegalArgumentException if the value factories are null */ public ValueTypeSystem( ValueFactories valueFactories ) { this(valueFactories, null); } /** * Create a type system using the supplied value factories and locale * * @param valueFactories the value factories; * @param locale the locale, may not be null * @throws IllegalArgumentException if the value factories are null */ public ValueTypeSystem( final ValueFactories valueFactories, final Locale locale ) { this.valueFactories = valueFactories; this.defaultTypeName = PropertyType.STRING.getName().toUpperCase(); Map<PropertyType, TypeFactory<?>> factories = new HashMap<>(); this.stringValueFactory = valueFactories.getStringFactory(); this.stringFactory = new Factory<String>(stringValueFactory) { @Override public String asString( Object value ) { return stringValueFactory.create(value); } @Override public String asReadableString( Object value ) { return stringValueFactory.create(value); } @Override @SuppressWarnings( { "unchecked", "rawtypes" } ) public Comparator<String> getComparator() { return locale == null ? super.getComparator() : ValueComparators.collatorComparator(locale); } }; this.booleanFactory = new Factory<Boolean>(valueFactories.getBooleanFactory()); this.longFactory = new Factory<Long>(valueFactories.getLongFactory()); this.doubleFactory = new Factory<Double>(valueFactories.getDoubleFactory()); this.decimalFactory = new Factory<BigDecimal>(valueFactories.getDecimalFactory()); this.dateFactory = new Factory<DateTime>(valueFactories.getDateFactory()) { @Override public DateTime create( String value ) throws ValueFormatException { DateTime result = valueFactory.create(value); // Convert the timestamp to UTC, since that's how everything should be queried ... return result.toUtcTimeZone(); } }; this.pathFactory = new Factory<Path>(valueFactories.getPathFactory()); this.nameFactory = new Factory<Name>(valueFactories.getNameFactory()); this.referenceFactory = new Factory<Reference>(valueFactories.getReferenceFactory()); this.nodeKeyFactory = new NodeKeyTypeFactory(stringValueFactory); this.binaryFactory = new Factory<BinaryValue>(valueFactories.getBinaryFactory()) { @Override public String asReadableString( Object value ) { BinaryValue binary = this.valueFactory.create(value); // Just print out the SHA-1 hash in Base64, plus length return "(Binary,length=" + binary.getSize() + ",SHA1=" + Base64.encodeBytes(binary.getHash()) + ")"; } @Override public long length( Object value ) { BinaryValue binary = this.valueFactory.create(value); return binary != null ? binary.getSize() : 0; } }; factories.put(PropertyType.STRING, this.stringFactory); factories.put(PropertyType.BOOLEAN, this.booleanFactory); factories.put(PropertyType.DATE, this.dateFactory); factories.put(PropertyType.DECIMAL, new Factory<BigDecimal>(valueFactories.getDecimalFactory())); factories.put(PropertyType.DOUBLE, this.doubleFactory); factories.put(PropertyType.LONG, this.longFactory); factories.put(PropertyType.NAME, new Factory<Name>(valueFactories.getNameFactory())); factories.put(PropertyType.OBJECT, new Factory<Object>(valueFactories.getObjectFactory())); factories.put(PropertyType.PATH, this.pathFactory); factories.put(PropertyType.REFERENCE, new Factory<Reference>(valueFactories.getReferenceFactory())); factories.put(PropertyType.WEAKREFERENCE, new Factory<Reference>(valueFactories.getWeakReferenceFactory())); factories.put(PropertyType.SIMPLEREFERENCE, new Factory<Reference>(valueFactories.getSimpleReferenceFactory())); factories.put(PropertyType.URI, new Factory<URI>(valueFactories.getUriFactory())); factories.put(PropertyType.BINARY, this.binaryFactory); this.typeFactoriesByPropertyType = Collections.unmodifiableMap(factories); Map<String, PropertyType> propertyTypeByName = new HashMap<String, PropertyType>(); for (Map.Entry<PropertyType, TypeFactory<?>> entry : this.typeFactoriesByPropertyType.entrySet()) { propertyTypeByName.put(entry.getValue().getTypeName(), entry.getKey()); } this.propertyTypeByName = Collections.unmodifiableMap(propertyTypeByName); Map<String, TypeFactory<?>> byName = new HashMap<>(); for (TypeFactory<?> factory : factories.values()) { byName.put(factory.getTypeName(), factory); } byName.put(nodeKeyFactory.getTypeName(), nodeKeyFactory); this.typeFactoriesByName = Collections.unmodifiableMap(byName); } @Override public String asString( Object value ) { return stringValueFactory.create(value); } @Override public TypeFactory<Boolean> getBooleanFactory() { return booleanFactory; } @Override public TypeFactory<String> getStringFactory() { return this.stringFactory; } @Override public TypeFactory<?> getDateTimeFactory() { return dateFactory; } @Override public String getDefaultType() { return defaultTypeName; } @Override @SuppressWarnings( "unchecked" ) public Comparator<Object> getDefaultComparator() { return (Comparator<Object>)PropertyType.OBJECT.getComparator(); } @Override public TypeFactory<Double> getDoubleFactory() { return doubleFactory; } @Override public TypeFactory<BigDecimal> getDecimalFactory() { return decimalFactory; } @Override public TypeFactory<Long> getLongFactory() { return longFactory; } @Override public TypeFactory<Path> getPathFactory() { return pathFactory; } @Override public TypeFactory<Name> getNameFactory() { return nameFactory; } @Override public TypeFactory<Reference> getReferenceFactory() { return referenceFactory; } @Override public TypeFactory<BinaryValue> getBinaryFactory() { return binaryFactory; } @Override public TypeFactory<NodeKey> getNodeKeyFactory() { return nodeKeyFactory; } @Override public TypeFactory<?> getTypeFactory( String typeName ) { if (typeName == null) return null; return typeFactoriesByName.get(typeName.toUpperCase()); // may be null } @Override public TypeFactory<?> getTypeFactory( Object prototype ) { ValueFactory<?> valueFactory = valueFactories.getValueFactory(prototype); if (valueFactory == null) return null; PropertyType type = valueFactory.getPropertyType(); assert type != null; return typeFactoriesByPropertyType.get(type); } @Override public Set<String> getTypeNames() { return typeFactoriesByName.keySet(); } @Override public String getCompatibleType( String type1, String type2 ) { if (type1 == null) { return type2 != null ? type2 : getDefaultType(); } if (type2 == null) return type1; if (type1.equals(type2)) return type1; // neither is null ... PropertyType ptype1 = propertyTypeByName.get(type1); PropertyType ptype2 = propertyTypeByName.get(type2); assert ptype1 != null; assert ptype2 != null; if (ptype1 == PropertyType.STRING) return type1; if (ptype2 == PropertyType.STRING) return type2; // Dates are compatible with longs ... if (ptype1 == PropertyType.LONG && ptype2 == PropertyType.DATE) return type1; if (ptype1 == PropertyType.DATE && ptype2 == PropertyType.LONG) return type2; // Booleans and longs are compatible ... if (ptype1 == PropertyType.LONG && ptype2 == PropertyType.BOOLEAN) return type1; if (ptype1 == PropertyType.BOOLEAN && ptype2 == PropertyType.LONG) return type2; // Doubles and longs ... if (ptype1 == PropertyType.DOUBLE && ptype2 == PropertyType.LONG) return type1; if (ptype1 == PropertyType.LONG && ptype2 == PropertyType.DOUBLE) return type2; // Paths and names ... if (ptype1 == PropertyType.PATH && ptype2 == PropertyType.NAME) return type1; if (ptype1 == PropertyType.NAME && ptype2 == PropertyType.PATH) return type2; // Otherwise, it's just the default type (string) ... return getDefaultType(); } @Override public TypeFactory<?> getCompatibleType( TypeFactory<?> type1, TypeFactory<?> type2 ) { return getTypeFactory(getCompatibleType(type1.getTypeName(), type2.getTypeName())); } protected class Factory<T> implements TypeFactory<T> { protected final PropertyType type; protected final ValueFactory<T> valueFactory; protected final String typeName; protected Factory( ValueFactory<T> valueFactory ) { this.valueFactory = valueFactory; this.type = this.valueFactory.getPropertyType(); this.typeName = type.getName().toUpperCase(); } @Override public String asReadableString( Object value ) { return asString(value); } @Override public String asString( Object value ) { if (value instanceof String) { // Convert to the typed value, then back to a string ... value = valueFactory.create((String)value); } return stringValueFactory.create(value); } @Override public T create( String value ) throws ValueFormatException { return valueFactory.create(value); } @Override public T create( Object value ) throws ValueFormatException { return valueFactory.create(value); } @Override @SuppressWarnings( "unchecked" ) public Class<T> getType() { return (Class<T>)type.getValueClass(); } @Override public long length( Object value ) { String str = asString(valueFactory.create(value)); return str != null ? str.length() : 0; } @Override @SuppressWarnings( "unchecked" ) public Comparator<T> getComparator() { return (Comparator<T>)type.getComparator(); } @Override public String getTypeName() { return typeName; } @Override public String toString() { return "TypeFactory<" + getTypeName() + ">"; } } protected static class NodeKeyTypeFactory implements TypeFactory<NodeKey> { private final ValueFactory<String> stringFactory; protected NodeKeyTypeFactory( ValueFactory<String> stringFactory ) { this.stringFactory = stringFactory; } @Override public Class<NodeKey> getType() { return NodeKey.class; } @Override public String getTypeName() { return getType().getName().toUpperCase(); } @Override public String asString( Object value ) { return ((NodeKey)value).toString(); } @Override public String asReadableString( Object value ) { return asString(value); } @Override public long length( Object value ) { return asString(value).length(); } @Override public NodeKey create( Object value ) throws ValueFormatException { if (value == null) return null; if (value instanceof NodeKey) { return (NodeKey)value; } if (value instanceof NodeKeyReference) { return ((NodeKeyReference)value).getNodeKey(); } String str = stringFactory.create(value); return create(str); } @Override public NodeKey create( String value ) throws ValueFormatException { if (NodeKey.isValidFormat(value)) { return new NodeKey(value); } throw new ValueFormatException(value, PropertyType.OBJECT, "Unable to convert " + value.getClass() + " to a NodeKey"); } @Override public Comparator<NodeKey> getComparator() { return NodeKey.COMPARATOR; } } }
UTF-8
Java
15,179
java
ValueTypeSystem.java
Java
[]
null
[]
/* * ModeShape (http://www.modeshape.org) * * 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 org.modeshape.jcr.value; import java.math.BigDecimal; import java.net.URI; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import org.modeshape.common.util.Base64; import org.modeshape.jcr.api.value.DateTime; import org.modeshape.jcr.cache.NodeKey; import org.modeshape.jcr.query.model.TypeSystem; import org.modeshape.jcr.value.basic.NodeKeyReference; /** * */ public final class ValueTypeSystem extends TypeSystem { private final String defaultTypeName; protected final ValueFactories valueFactories; protected final ValueFactory<String> stringValueFactory; private final Map<PropertyType, TypeFactory<?>> typeFactoriesByPropertyType; private final Map<String, TypeFactory<?>> typeFactoriesByName; private final Map<String, PropertyType> propertyTypeByName; private final TypeFactory<String> stringFactory; private final TypeFactory<Boolean> booleanFactory; private final TypeFactory<Long> longFactory; private final TypeFactory<Double> doubleFactory; private final TypeFactory<BigDecimal> decimalFactory; private final TypeFactory<DateTime> dateFactory; private final TypeFactory<Path> pathFactory; private final TypeFactory<Name> nameFactory; private final TypeFactory<Reference> referenceFactory; private final TypeFactory<BinaryValue> binaryFactory; private final TypeFactory<NodeKey> nodeKeyFactory; /** * Create a type system using the supplied value factories. * * @param valueFactories the value factories; * @throws IllegalArgumentException if the value factories are null */ public ValueTypeSystem( ValueFactories valueFactories ) { this(valueFactories, null); } /** * Create a type system using the supplied value factories and locale * * @param valueFactories the value factories; * @param locale the locale, may not be null * @throws IllegalArgumentException if the value factories are null */ public ValueTypeSystem( final ValueFactories valueFactories, final Locale locale ) { this.valueFactories = valueFactories; this.defaultTypeName = PropertyType.STRING.getName().toUpperCase(); Map<PropertyType, TypeFactory<?>> factories = new HashMap<>(); this.stringValueFactory = valueFactories.getStringFactory(); this.stringFactory = new Factory<String>(stringValueFactory) { @Override public String asString( Object value ) { return stringValueFactory.create(value); } @Override public String asReadableString( Object value ) { return stringValueFactory.create(value); } @Override @SuppressWarnings( { "unchecked", "rawtypes" } ) public Comparator<String> getComparator() { return locale == null ? super.getComparator() : ValueComparators.collatorComparator(locale); } }; this.booleanFactory = new Factory<Boolean>(valueFactories.getBooleanFactory()); this.longFactory = new Factory<Long>(valueFactories.getLongFactory()); this.doubleFactory = new Factory<Double>(valueFactories.getDoubleFactory()); this.decimalFactory = new Factory<BigDecimal>(valueFactories.getDecimalFactory()); this.dateFactory = new Factory<DateTime>(valueFactories.getDateFactory()) { @Override public DateTime create( String value ) throws ValueFormatException { DateTime result = valueFactory.create(value); // Convert the timestamp to UTC, since that's how everything should be queried ... return result.toUtcTimeZone(); } }; this.pathFactory = new Factory<Path>(valueFactories.getPathFactory()); this.nameFactory = new Factory<Name>(valueFactories.getNameFactory()); this.referenceFactory = new Factory<Reference>(valueFactories.getReferenceFactory()); this.nodeKeyFactory = new NodeKeyTypeFactory(stringValueFactory); this.binaryFactory = new Factory<BinaryValue>(valueFactories.getBinaryFactory()) { @Override public String asReadableString( Object value ) { BinaryValue binary = this.valueFactory.create(value); // Just print out the SHA-1 hash in Base64, plus length return "(Binary,length=" + binary.getSize() + ",SHA1=" + Base64.encodeBytes(binary.getHash()) + ")"; } @Override public long length( Object value ) { BinaryValue binary = this.valueFactory.create(value); return binary != null ? binary.getSize() : 0; } }; factories.put(PropertyType.STRING, this.stringFactory); factories.put(PropertyType.BOOLEAN, this.booleanFactory); factories.put(PropertyType.DATE, this.dateFactory); factories.put(PropertyType.DECIMAL, new Factory<BigDecimal>(valueFactories.getDecimalFactory())); factories.put(PropertyType.DOUBLE, this.doubleFactory); factories.put(PropertyType.LONG, this.longFactory); factories.put(PropertyType.NAME, new Factory<Name>(valueFactories.getNameFactory())); factories.put(PropertyType.OBJECT, new Factory<Object>(valueFactories.getObjectFactory())); factories.put(PropertyType.PATH, this.pathFactory); factories.put(PropertyType.REFERENCE, new Factory<Reference>(valueFactories.getReferenceFactory())); factories.put(PropertyType.WEAKREFERENCE, new Factory<Reference>(valueFactories.getWeakReferenceFactory())); factories.put(PropertyType.SIMPLEREFERENCE, new Factory<Reference>(valueFactories.getSimpleReferenceFactory())); factories.put(PropertyType.URI, new Factory<URI>(valueFactories.getUriFactory())); factories.put(PropertyType.BINARY, this.binaryFactory); this.typeFactoriesByPropertyType = Collections.unmodifiableMap(factories); Map<String, PropertyType> propertyTypeByName = new HashMap<String, PropertyType>(); for (Map.Entry<PropertyType, TypeFactory<?>> entry : this.typeFactoriesByPropertyType.entrySet()) { propertyTypeByName.put(entry.getValue().getTypeName(), entry.getKey()); } this.propertyTypeByName = Collections.unmodifiableMap(propertyTypeByName); Map<String, TypeFactory<?>> byName = new HashMap<>(); for (TypeFactory<?> factory : factories.values()) { byName.put(factory.getTypeName(), factory); } byName.put(nodeKeyFactory.getTypeName(), nodeKeyFactory); this.typeFactoriesByName = Collections.unmodifiableMap(byName); } @Override public String asString( Object value ) { return stringValueFactory.create(value); } @Override public TypeFactory<Boolean> getBooleanFactory() { return booleanFactory; } @Override public TypeFactory<String> getStringFactory() { return this.stringFactory; } @Override public TypeFactory<?> getDateTimeFactory() { return dateFactory; } @Override public String getDefaultType() { return defaultTypeName; } @Override @SuppressWarnings( "unchecked" ) public Comparator<Object> getDefaultComparator() { return (Comparator<Object>)PropertyType.OBJECT.getComparator(); } @Override public TypeFactory<Double> getDoubleFactory() { return doubleFactory; } @Override public TypeFactory<BigDecimal> getDecimalFactory() { return decimalFactory; } @Override public TypeFactory<Long> getLongFactory() { return longFactory; } @Override public TypeFactory<Path> getPathFactory() { return pathFactory; } @Override public TypeFactory<Name> getNameFactory() { return nameFactory; } @Override public TypeFactory<Reference> getReferenceFactory() { return referenceFactory; } @Override public TypeFactory<BinaryValue> getBinaryFactory() { return binaryFactory; } @Override public TypeFactory<NodeKey> getNodeKeyFactory() { return nodeKeyFactory; } @Override public TypeFactory<?> getTypeFactory( String typeName ) { if (typeName == null) return null; return typeFactoriesByName.get(typeName.toUpperCase()); // may be null } @Override public TypeFactory<?> getTypeFactory( Object prototype ) { ValueFactory<?> valueFactory = valueFactories.getValueFactory(prototype); if (valueFactory == null) return null; PropertyType type = valueFactory.getPropertyType(); assert type != null; return typeFactoriesByPropertyType.get(type); } @Override public Set<String> getTypeNames() { return typeFactoriesByName.keySet(); } @Override public String getCompatibleType( String type1, String type2 ) { if (type1 == null) { return type2 != null ? type2 : getDefaultType(); } if (type2 == null) return type1; if (type1.equals(type2)) return type1; // neither is null ... PropertyType ptype1 = propertyTypeByName.get(type1); PropertyType ptype2 = propertyTypeByName.get(type2); assert ptype1 != null; assert ptype2 != null; if (ptype1 == PropertyType.STRING) return type1; if (ptype2 == PropertyType.STRING) return type2; // Dates are compatible with longs ... if (ptype1 == PropertyType.LONG && ptype2 == PropertyType.DATE) return type1; if (ptype1 == PropertyType.DATE && ptype2 == PropertyType.LONG) return type2; // Booleans and longs are compatible ... if (ptype1 == PropertyType.LONG && ptype2 == PropertyType.BOOLEAN) return type1; if (ptype1 == PropertyType.BOOLEAN && ptype2 == PropertyType.LONG) return type2; // Doubles and longs ... if (ptype1 == PropertyType.DOUBLE && ptype2 == PropertyType.LONG) return type1; if (ptype1 == PropertyType.LONG && ptype2 == PropertyType.DOUBLE) return type2; // Paths and names ... if (ptype1 == PropertyType.PATH && ptype2 == PropertyType.NAME) return type1; if (ptype1 == PropertyType.NAME && ptype2 == PropertyType.PATH) return type2; // Otherwise, it's just the default type (string) ... return getDefaultType(); } @Override public TypeFactory<?> getCompatibleType( TypeFactory<?> type1, TypeFactory<?> type2 ) { return getTypeFactory(getCompatibleType(type1.getTypeName(), type2.getTypeName())); } protected class Factory<T> implements TypeFactory<T> { protected final PropertyType type; protected final ValueFactory<T> valueFactory; protected final String typeName; protected Factory( ValueFactory<T> valueFactory ) { this.valueFactory = valueFactory; this.type = this.valueFactory.getPropertyType(); this.typeName = type.getName().toUpperCase(); } @Override public String asReadableString( Object value ) { return asString(value); } @Override public String asString( Object value ) { if (value instanceof String) { // Convert to the typed value, then back to a string ... value = valueFactory.create((String)value); } return stringValueFactory.create(value); } @Override public T create( String value ) throws ValueFormatException { return valueFactory.create(value); } @Override public T create( Object value ) throws ValueFormatException { return valueFactory.create(value); } @Override @SuppressWarnings( "unchecked" ) public Class<T> getType() { return (Class<T>)type.getValueClass(); } @Override public long length( Object value ) { String str = asString(valueFactory.create(value)); return str != null ? str.length() : 0; } @Override @SuppressWarnings( "unchecked" ) public Comparator<T> getComparator() { return (Comparator<T>)type.getComparator(); } @Override public String getTypeName() { return typeName; } @Override public String toString() { return "TypeFactory<" + getTypeName() + ">"; } } protected static class NodeKeyTypeFactory implements TypeFactory<NodeKey> { private final ValueFactory<String> stringFactory; protected NodeKeyTypeFactory( ValueFactory<String> stringFactory ) { this.stringFactory = stringFactory; } @Override public Class<NodeKey> getType() { return NodeKey.class; } @Override public String getTypeName() { return getType().getName().toUpperCase(); } @Override public String asString( Object value ) { return ((NodeKey)value).toString(); } @Override public String asReadableString( Object value ) { return asString(value); } @Override public long length( Object value ) { return asString(value).length(); } @Override public NodeKey create( Object value ) throws ValueFormatException { if (value == null) return null; if (value instanceof NodeKey) { return (NodeKey)value; } if (value instanceof NodeKeyReference) { return ((NodeKeyReference)value).getNodeKey(); } String str = stringFactory.create(value); return create(str); } @Override public NodeKey create( String value ) throws ValueFormatException { if (NodeKey.isValidFormat(value)) { return new NodeKey(value); } throw new ValueFormatException(value, PropertyType.OBJECT, "Unable to convert " + value.getClass() + " to a NodeKey"); } @Override public Comparator<NodeKey> getComparator() { return NodeKey.COMPARATOR; } } }
15,179
0.646683
0.642598
407
36.294842
29.335835
130
false
false
0
0
0
0
0
0
0.486486
false
false
7
6ebcfbb9dcd6541401b0ba1eb2348006dc984050
18,339,510,421,243
44d225841fca1a0ddbb05498c3247599b1838756
/JavaEE_2019/ArraysDemo_fill_byteArray/ArraysDemo/src/ArraysDemo.java
72319b26e06b62b12bd74deb782a98eb7002f2a3
[]
no_license
pavanganeshbhagathi/Java_Spring_2019
https://github.com/pavanganeshbhagathi/Java_Spring_2019
a33df6379e02e7804e8238acdef5137681ee0d8a
4607a94a455cbc858690ffb11d408006f9798e93
refs/heads/master
2020-12-06T23:40:37.396000
2020-01-08T13:35:10
2020-01-08T13:35:10
232,581,578
2
0
null
true
2020-01-08T14:26:35
2020-01-08T14:26:34
2020-01-08T13:35:27
2020-01-08T13:35:24
56,568
0
0
0
null
false
false
import java.util.Arrays; public class ArraysDemo { public static void main(String[] args) { byte[] byteArray = new byte[] { 2, 7, 9, 7, 8 }; System.out.println("Before fill = " + Arrays.toString(byteArray)); Arrays.fill(byteArray, (byte) 8); System.out.println("After fill = " + Arrays.toString(byteArray)); } }
UTF-8
Java
329
java
ArraysDemo.java
Java
[]
null
[]
import java.util.Arrays; public class ArraysDemo { public static void main(String[] args) { byte[] byteArray = new byte[] { 2, 7, 9, 7, 8 }; System.out.println("Before fill = " + Arrays.toString(byteArray)); Arrays.fill(byteArray, (byte) 8); System.out.println("After fill = " + Arrays.toString(byteArray)); } }
329
0.659574
0.641337
16
19.5625
24.348944
68
false
false
0
0
0
0
0
0
1.3125
false
false
7
ed9895e10bed71dc862a389c9f883534d403861f
16,904,991,281,504
cd3ccc969d6e31dce1a0cdc21de71899ab670a46
/agp-7.1.0-alpha01/tools/base/profiler/integration-tests/ProfilerTester/app/src/main/java/android/com/java/profilertester/taskcategory/TaskCategory.java
e43ca5b7914d87d19435601606b7462b008d9bfd
[ "Apache-2.0" ]
permissive
jomof/CppBuildCacheWorkInProgress
https://github.com/jomof/CppBuildCacheWorkInProgress
75e76e1bd1d8451e3ee31631e74f22e5bb15dd3c
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
refs/heads/main
2023-05-28T19:03:16.798000
2021-06-10T20:59:25
2021-06-10T20:59:25
374,736,765
0
1
Apache-2.0
false
2021-06-07T21:06:53
2021-06-07T16:44:55
2021-06-07T20:39:43
2021-06-07T21:05:53
108,679
0
0
1
Java
false
false
package android.com.java.profilertester.taskcategory; import android.annotation.TargetApi; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public abstract class TaskCategory { public abstract static class Task { protected static final long DEFAULT_TASK_TIME_MS = TimeUnit.SECONDS.toMillis(10); protected static final long LONG_TASK_TIME_MS = TimeUnit.SECONDS.toMillis(20); /** Method that is called just prior to {@link Task#execute()} begins running. */ public void preExecute() {} /** * Main execution logic for the task. * * @return A displayable string describing the results of the execution. {@code null} is OK * to return, if there's no useful message to show after the task completes. */ @Nullable protected abstract String execute() throws Exception; /** * Method that is called when {@link Task#execute()} finishes running. User is responsible * for determining under what conditions should the contents be run. */ public void postExecute() {} @Override public final String toString() { return getTaskDescription(); } @NonNull protected abstract String getTaskDescription(); @Nullable protected SelectionListener getSelectionListener() { return null; } public interface SelectionListener { void onSelection(@NonNull Object selectedItem); } } @NonNull public abstract List<? extends Task> getTasks(); @Override @NonNull public final String toString() { return getCategoryName(); } public final void executeTask( @NonNull Task target, @Nullable PostExecuteRunner postExecuteRunner) { new AsyncTaskWrapper(this, target, postExecuteRunner).execute(); } @NonNull public final List<Task.SelectionListener> getTaskSelectionListeners() { List<Task.SelectionListener> selectionListeners = new ArrayList<>(); List<? extends Task> tasks = getTasks(); for (Task task : tasks) { Task.SelectionListener selectionListener = task.getSelectionListener(); if (selectionListener != null) { selectionListeners.add(selectionListener); } } return selectionListeners; } @NonNull protected abstract String getCategoryName(); /** * A predicate for whether or not to run the given {@code taskToRun}. Override this method to * conditionally execute the {@code taskToRun} (defaults to {@code true}). This is always called * before the task is executed. * * @param taskToRun the selected task to be run. * @return true to run the task, or false to prevent the task from being run. */ protected boolean shouldRunTask(@NonNull Task taskToRun) { return true; } @NonNull public RequestCodePermissions getPermissionsRequired(@NonNull Task taskToRun) { return new RequestCodePermissions(new String[0], ActivityRequestCodes.NO_REQUEST_CODE); } /** * Callback to the {@link TaskCategory} if it needs to start an {@link Intent}. The params are * just passed through from {@link android.app.Activity#onActivityResult(int, int, Intent)}. */ public void onActivityResult(int requestCode, int resultCode, Intent data) {} private static final class AsyncTaskWrapper extends AsyncTask<Void, Void, String> { private final TaskCategory mTaskCategory; private final Task mTask; private final PostExecuteRunner mPostExecuteRunner; private AsyncTaskWrapper( @NonNull TaskCategory taskCategory, @NonNull Task task, @Nullable PostExecuteRunner postExecuteRunner) { mTaskCategory = taskCategory; mTask = task; mPostExecuteRunner = postExecuteRunner; } @Override protected void onPreExecute() { try { if (!mTaskCategory.shouldRunTask(mTask)) { cancel(true); return; } mTask.preExecute(); } catch (Exception e) { e.printStackTrace(); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected String doInBackground(Void... voids) { try { return mTask.execute(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } } @Override protected void onPostExecute(String s) { mTask.postExecute(); if (mPostExecuteRunner != null) { mPostExecuteRunner.accept(s); } } } public interface PostExecuteRunner { void accept(@Nullable String s); } public static final class RequestCodePermissions { @NonNull private final String[] mPermissions; @NonNull private final ActivityRequestCodes mRequestCode; RequestCodePermissions( @NonNull String[] permissions, @NonNull ActivityRequestCodes requestCode) { mPermissions = permissions; mRequestCode = requestCode; } @NonNull public String[] getPermissions() { return mPermissions; } @NonNull public ActivityRequestCodes getRequestCode() { return mRequestCode; } } }
UTF-8
Java
5,810
java
TaskCategory.java
Java
[]
null
[]
package android.com.java.profilertester.taskcategory; import android.annotation.TargetApi; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public abstract class TaskCategory { public abstract static class Task { protected static final long DEFAULT_TASK_TIME_MS = TimeUnit.SECONDS.toMillis(10); protected static final long LONG_TASK_TIME_MS = TimeUnit.SECONDS.toMillis(20); /** Method that is called just prior to {@link Task#execute()} begins running. */ public void preExecute() {} /** * Main execution logic for the task. * * @return A displayable string describing the results of the execution. {@code null} is OK * to return, if there's no useful message to show after the task completes. */ @Nullable protected abstract String execute() throws Exception; /** * Method that is called when {@link Task#execute()} finishes running. User is responsible * for determining under what conditions should the contents be run. */ public void postExecute() {} @Override public final String toString() { return getTaskDescription(); } @NonNull protected abstract String getTaskDescription(); @Nullable protected SelectionListener getSelectionListener() { return null; } public interface SelectionListener { void onSelection(@NonNull Object selectedItem); } } @NonNull public abstract List<? extends Task> getTasks(); @Override @NonNull public final String toString() { return getCategoryName(); } public final void executeTask( @NonNull Task target, @Nullable PostExecuteRunner postExecuteRunner) { new AsyncTaskWrapper(this, target, postExecuteRunner).execute(); } @NonNull public final List<Task.SelectionListener> getTaskSelectionListeners() { List<Task.SelectionListener> selectionListeners = new ArrayList<>(); List<? extends Task> tasks = getTasks(); for (Task task : tasks) { Task.SelectionListener selectionListener = task.getSelectionListener(); if (selectionListener != null) { selectionListeners.add(selectionListener); } } return selectionListeners; } @NonNull protected abstract String getCategoryName(); /** * A predicate for whether or not to run the given {@code taskToRun}. Override this method to * conditionally execute the {@code taskToRun} (defaults to {@code true}). This is always called * before the task is executed. * * @param taskToRun the selected task to be run. * @return true to run the task, or false to prevent the task from being run. */ protected boolean shouldRunTask(@NonNull Task taskToRun) { return true; } @NonNull public RequestCodePermissions getPermissionsRequired(@NonNull Task taskToRun) { return new RequestCodePermissions(new String[0], ActivityRequestCodes.NO_REQUEST_CODE); } /** * Callback to the {@link TaskCategory} if it needs to start an {@link Intent}. The params are * just passed through from {@link android.app.Activity#onActivityResult(int, int, Intent)}. */ public void onActivityResult(int requestCode, int resultCode, Intent data) {} private static final class AsyncTaskWrapper extends AsyncTask<Void, Void, String> { private final TaskCategory mTaskCategory; private final Task mTask; private final PostExecuteRunner mPostExecuteRunner; private AsyncTaskWrapper( @NonNull TaskCategory taskCategory, @NonNull Task task, @Nullable PostExecuteRunner postExecuteRunner) { mTaskCategory = taskCategory; mTask = task; mPostExecuteRunner = postExecuteRunner; } @Override protected void onPreExecute() { try { if (!mTaskCategory.shouldRunTask(mTask)) { cancel(true); return; } mTask.preExecute(); } catch (Exception e) { e.printStackTrace(); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected String doInBackground(Void... voids) { try { return mTask.execute(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } } @Override protected void onPostExecute(String s) { mTask.postExecute(); if (mPostExecuteRunner != null) { mPostExecuteRunner.accept(s); } } } public interface PostExecuteRunner { void accept(@Nullable String s); } public static final class RequestCodePermissions { @NonNull private final String[] mPermissions; @NonNull private final ActivityRequestCodes mRequestCode; RequestCodePermissions( @NonNull String[] permissions, @NonNull ActivityRequestCodes requestCode) { mPermissions = permissions; mRequestCode = requestCode; } @NonNull public String[] getPermissions() { return mPermissions; } @NonNull public ActivityRequestCodes getRequestCode() { return mRequestCode; } } }
5,810
0.620654
0.619793
178
31.64045
27.808434
100
false
false
0
0
0
0
0
0
0.365169
false
false
7
9fc4eb008961ace809e6685fe170654a157e931a
26,706,106,692,123
4e79eb880981fe4ad60a2c6a59f7d1cc50cfc183
/AndroidPersonalPlaylist/app/src/main/java/tech/mccauley/androidpersonalplaylist/PlaylistManager.java
8af5aeaa97b45e3d231cc25e1dcdbc350b8bf47b
[]
no_license
cdmccauley/android-demos
https://github.com/cdmccauley/android-demos
f2373c0320e5ea9e9c5098d66c6c43611b544c48
5ca566a10c766ab02cf92a042063f710c277ba55
refs/heads/master
2020-03-18T17:00:15.531000
2018-07-03T02:26:45
2018-07-03T02:26:45
134,999,689
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tech.mccauley.androidpersonalplaylist; import android.content.Context; import android.media.MediaPlayer; import android.view.View; import android.widget.Button; import java.util.ArrayList; public class PlaylistManager { // declarations PlaylistItem[] playlistItems; Context mainContext; ArrayList<MediaPlayer> playlistPlayers; ArrayList<Button> playButtons; boolean playing; // constructor public PlaylistManager(Context mainContext) { playlistItems = new PlaylistItem[] { new PlaylistItem("CHOKE", "I Don't Know How But They Found Me", "CHOKE", "choke"), new PlaylistItem("Ma Chérie (feat. Kellin Quinn)", "Palaye Royale", "Boom Boom Room", "boomboomroom"), new PlaylistItem("High Hopes", "Panic! At The Disco", "Pray For The Wicked", "prayforthewicked") }; this.mainContext = mainContext; playlistPlayers = new ArrayList<>(); playButtons = new ArrayList<>(); playing = false; } public PlaylistItem[] getPlaylistItems() { return playlistItems; } public Context getMainContext() { return mainContext; } public void addPlaylistPlayer(MediaPlayer player, Button button) { playlistPlayers.add(player); playButtons.add(button); } public void playPlaylist(int item) { if (playing) { playing = false; playButtons.get(item).setText("Play"); playlistPlayers.get(item).pause(); for (int i = 0; i < playlistPlayers.size(); i++) { if (i != item) { playButtons.get(i).setEnabled(true); } } } else { for (int i = 0; i < playlistPlayers.size(); i++) { if (i != item) { playButtons.get(i).setEnabled(false); } } playlistPlayers.get(item).start(); playButtons.get(item).setText("Pause"); playing = true; } } }
UTF-8
Java
2,057
java
PlaylistManager.java
Java
[ { "context": " new PlaylistItem(\"Ma Chérie (feat. Kellin Quinn)\", \"Palaye Royale\", \"Boom Boom Room\", \"boomboomro", "end": 688, "score": 0.9988303184509277, "start": 676, "tag": "NAME", "value": "Kellin Quinn" }, { "context": "w PlaylistItem(\"Ma Chérie (feat. Kellin Quinn)\", \"Palaye Royale\", \"Boom Boom Room\", \"boomboomroom\"),\n ", "end": 706, "score": 0.6352036595344543, "start": 693, "tag": "NAME", "value": "Palaye Royale" } ]
null
[]
package tech.mccauley.androidpersonalplaylist; import android.content.Context; import android.media.MediaPlayer; import android.view.View; import android.widget.Button; import java.util.ArrayList; public class PlaylistManager { // declarations PlaylistItem[] playlistItems; Context mainContext; ArrayList<MediaPlayer> playlistPlayers; ArrayList<Button> playButtons; boolean playing; // constructor public PlaylistManager(Context mainContext) { playlistItems = new PlaylistItem[] { new PlaylistItem("CHOKE", "I Don't Know How But They Found Me", "CHOKE", "choke"), new PlaylistItem("Ma Chérie (feat. <NAME>)", "<NAME>", "Boom Boom Room", "boomboomroom"), new PlaylistItem("High Hopes", "Panic! At The Disco", "Pray For The Wicked", "prayforthewicked") }; this.mainContext = mainContext; playlistPlayers = new ArrayList<>(); playButtons = new ArrayList<>(); playing = false; } public PlaylistItem[] getPlaylistItems() { return playlistItems; } public Context getMainContext() { return mainContext; } public void addPlaylistPlayer(MediaPlayer player, Button button) { playlistPlayers.add(player); playButtons.add(button); } public void playPlaylist(int item) { if (playing) { playing = false; playButtons.get(item).setText("Play"); playlistPlayers.get(item).pause(); for (int i = 0; i < playlistPlayers.size(); i++) { if (i != item) { playButtons.get(i).setEnabled(true); } } } else { for (int i = 0; i < playlistPlayers.size(); i++) { if (i != item) { playButtons.get(i).setEnabled(false); } } playlistPlayers.get(item).start(); playButtons.get(item).setText("Pause"); playing = true; } } }
2,044
0.581712
0.580739
67
29.686567
25.279459
118
false
false
0
0
0
0
0
0
0.656716
false
false
7
1064027e538c77510be182704de894e068320a21
14,860,586,854,567
20417b46d745f67b58cdc2c5aefc336767b4d8b7
/src/main/java/com/dao/BlogMapper.java
f38eebc54b42a05f166525779535c7c4f3897097
[]
no_license
BaiMaGod/ApeHouse
https://github.com/BaiMaGod/ApeHouse
5e5e07fd44a489b32a37a15225a61f20031b47f0
64d97834c0bfdb124396a903b9c859c7f71019a4
refs/heads/master
2023-01-11T03:41:01.431000
2019-07-25T08:15:25
2019-07-25T08:15:25
186,220,246
1
0
null
false
2022-12-30T10:26:19
2019-05-12T06:31:29
2019-07-25T08:15:28
2022-12-30T10:26:18
77,596
1
0
24
JavaScript
false
false
package com.dao; import com.model.Blog; import com.model.BlogExample; import org.apache.ibatis.annotations.Mapper; import org.mybatis.spring.annotation.MapperScan; import java.util.List; @Mapper public interface BlogMapper { long countByExample(BlogExample example); int deleteByPrimaryKey(String id); int insert(Blog record); int insertSelective(Blog record); List<Blog> selectByExampleWithBLOBs(BlogExample example); List<Blog> selectByExample(BlogExample example); Blog selectByPrimaryKey(String id); int updateByPrimaryKeySelective(Blog record); int updateByPrimaryKeyWithBLOBs(Blog record); int updateByPrimaryKey(Blog record); }
UTF-8
Java
716
java
BlogMapper.java
Java
[]
null
[]
package com.dao; import com.model.Blog; import com.model.BlogExample; import org.apache.ibatis.annotations.Mapper; import org.mybatis.spring.annotation.MapperScan; import java.util.List; @Mapper public interface BlogMapper { long countByExample(BlogExample example); int deleteByPrimaryKey(String id); int insert(Blog record); int insertSelective(Blog record); List<Blog> selectByExampleWithBLOBs(BlogExample example); List<Blog> selectByExample(BlogExample example); Blog selectByPrimaryKey(String id); int updateByPrimaryKeySelective(Blog record); int updateByPrimaryKeyWithBLOBs(Blog record); int updateByPrimaryKey(Blog record); }
716
0.738827
0.738827
31
21.161291
20.700783
61
false
false
0
0
0
0
0
0
0.516129
false
false
7
15702a6aaa1a789b3d16ca12651bfaf9e132fb54
11,974,368,849,855
ba46a0e014aa8038533db81b51048fbe224e3f56
/bots/finance-assistant-bot/src/main/java/by/bsuir/tofi/finance_assistant/bots/finance_assistant_bot/services/requests/Functions.java
f9d6504e1d473b4f2f38d196d28897e979a6a741
[]
no_license
DmitriyOpanovich/tofi
https://github.com/DmitriyOpanovich/tofi
c02737e3ac75db48225f2492408a15dc158f2273
f4e6afe1cb3bcfd62f5cc99d95660afc1f8413cc
refs/heads/master
2021-05-03T12:31:02.781000
2016-12-29T14:37:09
2016-12-29T14:37:09
72,107,961
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.bsuir.tofi.finance_assistant.bots.finance_assistant_bot.services.requests; import org.springframework.http.HttpMethod; /** * Created by 1 on 06.12.2016. */ public enum Functions { UPDATE_USER("", HttpMethod.POST), LEAVE_FEEDBACK("/feedback", HttpMethod.POST), CONNECT_BOT_WITH_SITE_USER("/telegram/register", HttpMethod.POST); private final String path; private final HttpMethod httpMethod; Functions(String path, HttpMethod httpMethod) { this.path = path; this.httpMethod = httpMethod; } public String getPath() { return path; } public HttpMethod getHttpMethod() { return httpMethod; } }
UTF-8
Java
685
java
Functions.java
Java
[]
null
[]
package by.bsuir.tofi.finance_assistant.bots.finance_assistant_bot.services.requests; import org.springframework.http.HttpMethod; /** * Created by 1 on 06.12.2016. */ public enum Functions { UPDATE_USER("", HttpMethod.POST), LEAVE_FEEDBACK("/feedback", HttpMethod.POST), CONNECT_BOT_WITH_SITE_USER("/telegram/register", HttpMethod.POST); private final String path; private final HttpMethod httpMethod; Functions(String path, HttpMethod httpMethod) { this.path = path; this.httpMethod = httpMethod; } public String getPath() { return path; } public HttpMethod getHttpMethod() { return httpMethod; } }
685
0.677372
0.664234
29
22.620689
22.713224
85
false
false
0
0
0
0
0
0
0.517241
false
false
7
cca7bf04d1ab6fa2225cdd355f1f76b916ed8172
29,695,403,909,420
37ca73a1e5c1b1ba7bd8353cc0d0643605c20593
/Project2Task3/src/project2task3/UDPServerWithDoubleArithmetic.java
7bd689b89bbf524b42bace855d2664ad72c6b127
[]
no_license
keatonwatts/javaExamples
https://github.com/keatonwatts/javaExamples
6f3429e9dc61a4853e4b9229dada69aaae78690d
ce1cb0021db6575f67900fafb5661371aea4a486
refs/heads/master
2021-01-23T13:30:24.894000
2015-02-23T18:15:30
2015-02-23T18:16:21
31,221,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Author: Keaton Watts Last Modified: Feb 14, 2015 * * This program uses UDP Server & Client Architecture to perform basic * operations. This .java file is the UDP server Client will ask server to * add doubles from and to a given amount. */ //used http://javaprogramming.language-tutorial.com/2012/10/udp-client-server-communication-using.html for multiple references package project2task3; import java.net.*; import java.io.*; import java.nio.ByteBuffer; import static java.util.Arrays.*; public class UDPServerWithDoubleArithmetic { public static void main(String args[]) { DatagramSocket aSocket = null; //print System.out.println("java UDPServerWithDoubleArithmetic"); try { aSocket = new DatagramSocket(6789); //create socket at agreed port //create arrays to store send and receive data byte[] receiveData = new byte[17]; byte[] sendData = new byte[1000]; while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); aSocket.receive(receivePacket); //get data in byte array from client byte[] messageFromClient = receivePacket.getData(); //doubles are stored in 8 bytes so... //capture the first set of 8 bytes for x byte[] xByte = new byte[8]; xByte = copyOfRange(messageFromClient, 0, 8); //capture the second set of 8 bytes for y byte[] yByte = new byte[8]; yByte = copyOfRange(messageFromClient, 8, 16); //capture the last byte for the operator byte[] opByte = new byte[1]; opByte = copyOfRange(messageFromClient, 16, 17); //use conversion methods to converte byte array to long... //convert long to double and store in respective value double x = Double.longBitsToDouble(byteArrayToLong(xByte)); double y = Double.longBitsToDouble(byteArrayToLong(yByte)); //convert and store operation string String op = new String(opByte); //value to store answer in when computed in the switch below double answer = 0.0; //determine which operator was selected and execute appropriate method switch (op) { case "+": //addition //splitMessage[0] + splitMessage[1] answer = x + y; break; case "-": //subtraction //splitMessage[0] - splitMessage[1] answer = x - y; break; case "/": //division //splitMessage[0] / splitMessage[1] answer = x / y; break; case "^": //exponent //splitMessage[0] ^ splitMessage[1] //https://au.answers.yahoo.com/question/index?qid=20080407131719AA4GjMU answer = (int) Math.pow(x, y); break; case "X": //multiplication //splitMessage[0] * splitMessage[1] answer = x * y; break; default: break; } //convert data to send back answer String finalData = String.valueOf(answer); sendData = finalData.getBytes(); //send data back to client DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort()); aSocket.send(sendPacket); }//end while } catch (SocketException e) { System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); } finally { if (aSocket != null) { aSocket.close(); } } } public static long byteArrayToLong(byte bytes[]) { long v = 0; for (int i = 0; i < bytes.length; i++) { // bytes[i] will be promoted to a long with the byte’s leftmost // bit replicated. We need to clear that with 0xff. v = (v << 8) + (bytes[i] & 0xff); } return v; } }
UTF-8
Java
4,749
java
UDPServerWithDoubleArithmetic.java
Java
[ { "context": "/**\n * Author: Keaton Watts Last Modified: Feb 14, 2015\n * \n* This program us", "end": 27, "score": 0.9998827576637268, "start": 15, "tag": "NAME", "value": "Keaton Watts" } ]
null
[]
/** * Author: <NAME> Last Modified: Feb 14, 2015 * * This program uses UDP Server & Client Architecture to perform basic * operations. This .java file is the UDP server Client will ask server to * add doubles from and to a given amount. */ //used http://javaprogramming.language-tutorial.com/2012/10/udp-client-server-communication-using.html for multiple references package project2task3; import java.net.*; import java.io.*; import java.nio.ByteBuffer; import static java.util.Arrays.*; public class UDPServerWithDoubleArithmetic { public static void main(String args[]) { DatagramSocket aSocket = null; //print System.out.println("java UDPServerWithDoubleArithmetic"); try { aSocket = new DatagramSocket(6789); //create socket at agreed port //create arrays to store send and receive data byte[] receiveData = new byte[17]; byte[] sendData = new byte[1000]; while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); aSocket.receive(receivePacket); //get data in byte array from client byte[] messageFromClient = receivePacket.getData(); //doubles are stored in 8 bytes so... //capture the first set of 8 bytes for x byte[] xByte = new byte[8]; xByte = copyOfRange(messageFromClient, 0, 8); //capture the second set of 8 bytes for y byte[] yByte = new byte[8]; yByte = copyOfRange(messageFromClient, 8, 16); //capture the last byte for the operator byte[] opByte = new byte[1]; opByte = copyOfRange(messageFromClient, 16, 17); //use conversion methods to converte byte array to long... //convert long to double and store in respective value double x = Double.longBitsToDouble(byteArrayToLong(xByte)); double y = Double.longBitsToDouble(byteArrayToLong(yByte)); //convert and store operation string String op = new String(opByte); //value to store answer in when computed in the switch below double answer = 0.0; //determine which operator was selected and execute appropriate method switch (op) { case "+": //addition //splitMessage[0] + splitMessage[1] answer = x + y; break; case "-": //subtraction //splitMessage[0] - splitMessage[1] answer = x - y; break; case "/": //division //splitMessage[0] / splitMessage[1] answer = x / y; break; case "^": //exponent //splitMessage[0] ^ splitMessage[1] //https://au.answers.yahoo.com/question/index?qid=20080407131719AA4GjMU answer = (int) Math.pow(x, y); break; case "X": //multiplication //splitMessage[0] * splitMessage[1] answer = x * y; break; default: break; } //convert data to send back answer String finalData = String.valueOf(answer); sendData = finalData.getBytes(); //send data back to client DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort()); aSocket.send(sendPacket); }//end while } catch (SocketException e) { System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); } finally { if (aSocket != null) { aSocket.close(); } } } public static long byteArrayToLong(byte bytes[]) { long v = 0; for (int i = 0; i < bytes.length; i++) { // bytes[i] will be promoted to a long with the byte’s leftmost // bit replicated. We need to clear that with 0xff. v = (v << 8) + (bytes[i] & 0xff); } return v; } }
4,743
0.503055
0.488098
129
35.79845
26.85314
126
false
false
0
0
0
0
0
0
0.449612
false
false
7
7bfe9ae9f5e31e0f596e8d61401c90f03e9a2cd3
19,138,374,286,963
05d7ddb6c94387a03ecee54cde4a48590333308a
/proy/src/main/java/es/unir/web/dto/UsuarioDTO.java
38152400633843702f1285ef49f8d46197235026
[]
no_license
ram1r0/TFG
https://github.com/ram1r0/TFG
90bb57816edb0584bdcca31a0e5ac5a19914e4f2
d69e5da4e1d3e8def90c4cf3f79459eb651283da
refs/heads/master
2022-10-29T13:30:00.252000
2022-10-17T12:41:40
2022-10-17T12:41:40
89,235,398
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.unir.web.dto; import java.util.List; import java.util.Set; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.TableGenerator; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; @Entity @Table(name = "web_usuario") @TableGenerator(name = "generador", table = "web_pk", pkColumnName = "x_pk", pkColumnValue = "1", valueColumnName = "next_pk", allocationSize = 25) public class UsuarioDTO extends BaseDTO { public static final String CNombre = "nombre"; @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "generador") @Column(name = "X_USUARIO") private Long id; @Column(name = "C_USUARIO") private String usuario; @Column(name = "T_NOMBRE") private String nombre; @Column(name = "T_CLAVE") private String clave; @Column(name = "C_PERFIL") private Integer perfil; @Column(name = "C_CATEGORIA") private String categoria; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Integer getPerfil() { return perfil; } public void setPerfil(Integer perfil) { this.perfil = perfil; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } }
UTF-8
Java
2,150
java
UsuarioDTO.java
Java
[]
null
[]
package es.unir.web.dto; import java.util.List; import java.util.Set; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.TableGenerator; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; @Entity @Table(name = "web_usuario") @TableGenerator(name = "generador", table = "web_pk", pkColumnName = "x_pk", pkColumnValue = "1", valueColumnName = "next_pk", allocationSize = 25) public class UsuarioDTO extends BaseDTO { public static final String CNombre = "nombre"; @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "generador") @Column(name = "X_USUARIO") private Long id; @Column(name = "C_USUARIO") private String usuario; @Column(name = "T_NOMBRE") private String nombre; @Column(name = "T_CLAVE") private String clave; @Column(name = "C_PERFIL") private Integer perfil; @Column(name = "C_CATEGORIA") private String categoria; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Integer getPerfil() { return perfil; } public void setPerfil(Integer perfil) { this.perfil = perfil; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } }
2,150
0.693023
0.691628
98
19.938776
20.890295
147
false
false
0
0
0
0
0
0
0.959184
false
false
7
f398470ea3086f16be71dfdb86ec0fabe3f46219
38,216,619,006,857
96f8d42c474f8dd42ecc6811b6e555363f168d3e
/baike/sources/qsbk/app/live/animation/ae.java
90e54066337fd8973731351f342119799c6f089d
[]
no_license
aheadlcx/analyzeApk
https://github.com/aheadlcx/analyzeApk
050b261595cecc85790558a02d79739a789ae3a3
25cecc394dde4ed7d4971baf0e9504dcb7fabaca
refs/heads/master
2020-03-10T10:24:49.773000
2018-04-13T09:44:45
2018-04-13T09:44:45
129,332,351
6
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package qsbk.app.live.animation; class ae implements Runnable { final /* synthetic */ ShipAnimation a; ae(ShipAnimation shipAnimation) { this.a = shipAnimation; } public void run() { this.a.b(); if (this.a.o <= (this.a.e * 2) / 5) { this.a.o = this.a.o + 20; this.a.a(this.a.m, -20); this.a.a(this.a.n, -20); this.a.i(); return; } this.a.j(); } }
UTF-8
Java
470
java
ae.java
Java
[]
null
[]
package qsbk.app.live.animation; class ae implements Runnable { final /* synthetic */ ShipAnimation a; ae(ShipAnimation shipAnimation) { this.a = shipAnimation; } public void run() { this.a.b(); if (this.a.o <= (this.a.e * 2) / 5) { this.a.o = this.a.o + 20; this.a.a(this.a.m, -20); this.a.a(this.a.n, -20); this.a.i(); return; } this.a.j(); } }
470
0.470213
0.453191
21
21.380953
14.923539
45
false
false
0
0
0
0
0
0
0.571429
false
false
7
1979493f838e18a38952b15e1fe69b2add8d96cb
33,878,702,078,207
e9f98a754ff4cba85ffed59205c91ef8c83e767c
/app/src/main/java/com/kevin/jdmall/adapter/HomeBannerAdapter.java
ffb27c3280730f7ed070c25edba039eb19567336
[]
no_license
iamzhengkai/JDMall
https://github.com/iamzhengkai/JDMall
2a676bf4d164de79c75f17b5b574b3c65f18896a
9f723c522d7ffdfa911b5827a9a3046f5c3ef89f
refs/heads/master
2021-01-24T08:36:57.177000
2017-09-04T10:25:15
2017-09-04T10:25:15
93,388,394
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kevin.jdmall.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.kevin.jdmall.MyConstants; import com.kevin.jdmall.R; import com.kevin.jdmall.bean.BannerResult; import com.kevin.jdmall.ui.view.RatioImageView; import com.kevin.jdmall.utils.ToastUtil; import java.util.List; /** * Function: * * @FileName: com.kevin.jdmall.adapter.HomeBannerAdapter.java * @author: zk * @date: 2017-06-23 20:52 */ public class HomeBannerAdapter extends BasePagerAdapter<BannerResult.ResultBean> { private Context mContext; public HomeBannerAdapter(List<BannerResult.ResultBean> list, Context context) { super(list); mContext = context; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public Object instantiateItem(ViewGroup container, int position) { RatioImageView ratioImageView = (RatioImageView) View.inflate(mContext, R.layout .item_img_home_banner, null); //if (mList.size() > 0) { int realPosition = position % mList.size(); String imageUrl = MyConstants.BASE_URL + mList.get(realPosition).getAdUrl(); Glide.with(mContext).load(imageUrl).into(ratioImageView); //} //1.problem: after the onClickListener was setted, some conflicts occurred with the ViewPagers onTouchListener //2.solution:you should override dispatchTouchEvent method in RatioViewPager if you want to do sth before //you dispatch touch event ratioImageView.setOnClickListener(v -> { ToastUtil.showToast("你点击了第 " + realPosition + "项!"); }); container.addView(ratioImageView); return ratioImageView; } }
UTF-8
Java
1,816
java
HomeBannerAdapter.java
Java
[ { "context": ".jdmall.adapter.HomeBannerAdapter.java\n * @author: zk\n * @date: 2017-06-23 20:52\n */\n\npublic class Home", "end": 475, "score": 0.9976335763931274, "start": 473, "tag": "USERNAME", "value": "zk" } ]
null
[]
package com.kevin.jdmall.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.kevin.jdmall.MyConstants; import com.kevin.jdmall.R; import com.kevin.jdmall.bean.BannerResult; import com.kevin.jdmall.ui.view.RatioImageView; import com.kevin.jdmall.utils.ToastUtil; import java.util.List; /** * Function: * * @FileName: com.kevin.jdmall.adapter.HomeBannerAdapter.java * @author: zk * @date: 2017-06-23 20:52 */ public class HomeBannerAdapter extends BasePagerAdapter<BannerResult.ResultBean> { private Context mContext; public HomeBannerAdapter(List<BannerResult.ResultBean> list, Context context) { super(list); mContext = context; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public Object instantiateItem(ViewGroup container, int position) { RatioImageView ratioImageView = (RatioImageView) View.inflate(mContext, R.layout .item_img_home_banner, null); //if (mList.size() > 0) { int realPosition = position % mList.size(); String imageUrl = MyConstants.BASE_URL + mList.get(realPosition).getAdUrl(); Glide.with(mContext).load(imageUrl).into(ratioImageView); //} //1.problem: after the onClickListener was setted, some conflicts occurred with the ViewPagers onTouchListener //2.solution:you should override dispatchTouchEvent method in RatioViewPager if you want to do sth before //you dispatch touch event ratioImageView.setOnClickListener(v -> { ToastUtil.showToast("你点击了第 " + realPosition + "项!"); }); container.addView(ratioImageView); return ratioImageView; } }
1,816
0.692564
0.68424
55
31.763636
29.589289
118
false
false
0
0
0
0
0
0
0.509091
false
false
7
803c4b2f5b75467a7f1f8352899d64c737fadfa5
38,792,144,664,052
c3a0a41fbd769f061164fcb06dc70d577ff42f7f
/Submission4/app/src/main/java/com/medialink/submission4/view/adapter/PagerAdapter.java
ad184e034f7ed953fb62e62fcccb59aa764aa4cc
[ "Apache-2.0" ]
permissive
leon9reat/decoding-android
https://github.com/leon9reat/decoding-android
3ddc87a63e40b59c6bd421e063afdaa991db28f6
401a0810f66413dd3d96a9997d4327e0bc345a20
refs/heads/master
2020-08-03T04:57:52.372000
2019-10-22T02:15:48
2019-10-22T02:15:48
211,630,806
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.medialink.submission4.view.adapter; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import com.medialink.submission4.view.MovieFragment; import com.medialink.submission4.view.TvFragment; public class PagerAdapter extends FragmentStatePagerAdapter { int numOfTab; public PagerAdapter(@NonNull FragmentManager fm, int behavior, int numOfTab) { super(fm, behavior); this.numOfTab = numOfTab; } @NonNull @Override public Fragment getItem(int position) { switch (position) { case 0: return new MovieFragment(); case 1: return new TvFragment(); default: return null; } } @Override public int getCount() { return numOfTab; } }
UTF-8
Java
932
java
PagerAdapter.java
Java
[]
null
[]
package com.medialink.submission4.view.adapter; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import com.medialink.submission4.view.MovieFragment; import com.medialink.submission4.view.TvFragment; public class PagerAdapter extends FragmentStatePagerAdapter { int numOfTab; public PagerAdapter(@NonNull FragmentManager fm, int behavior, int numOfTab) { super(fm, behavior); this.numOfTab = numOfTab; } @NonNull @Override public Fragment getItem(int position) { switch (position) { case 0: return new MovieFragment(); case 1: return new TvFragment(); default: return null; } } @Override public int getCount() { return numOfTab; } }
932
0.662017
0.656652
37
24.18919
20.708841
82
false
false
0
0
0
0
0
0
0.459459
false
false
7