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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f806851a3261b12fe72388444f38c142cab34017
| 31,018,253,844,139 |
01452e041f716685f056cee5363add0765069d77
|
/src/main/java/webserver/Response.java
|
20ccad1cbc2a76d6dc2cac15ae3fd2a1e4c49fa9
|
[] |
no_license
|
andrewferlitsch/epipog-nosql
|
https://github.com/andrewferlitsch/epipog-nosql
|
53d051484ec62509571b0fcf0d43936d82ce4faf
|
7c85393a8c2c97fa44204d9ce48a7e688b0bad5b
|
refs/heads/master
| 2021-06-08T22:01:38.490000 | 2017-01-22T02:13:22 | 2017-01-22T02:13:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Epipog, Copyright(c) 2016-17, Andrew Ferlitsch, CC-BY
*/
package epipog.webserver;
public class Response {
private final long id;
private final int status;
private final String content;
// Status: OK
public Response( long id, String content) {
this.id = id;
this.content = content;
this.status = 200;
}
// Status: Error
public Response( long id, int status, String content) {
this.id = id;
this.content = content;
this.status = status;
}
public long getId() {
return id;
}
public int getStatus() {
return status;
}
public String getContent() {
return content;
}
}
|
UTF-8
|
Java
| 689 |
java
|
Response.java
|
Java
|
[
{
"context": "/*\n * Epipog, Copyright(c) 2016-17, Andrew Ferlitsch, CC-BY\n */\npackage epipog.webserver;\n\npublic clas",
"end": 52,
"score": 0.9997440576553345,
"start": 36,
"tag": "NAME",
"value": "Andrew Ferlitsch"
}
] | null |
[] |
/*
* Epipog, Copyright(c) 2016-17, <NAME>, CC-BY
*/
package epipog.webserver;
public class Response {
private final long id;
private final int status;
private final String content;
// Status: OK
public Response( long id, String content) {
this.id = id;
this.content = content;
this.status = 200;
}
// Status: Error
public Response( long id, int status, String content) {
this.id = id;
this.content = content;
this.status = status;
}
public long getId() {
return id;
}
public int getStatus() {
return status;
}
public String getContent() {
return content;
}
}
| 679 | 0.593614 | 0.580552 | 38 | 17.157894 | 15.695333 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false |
7
|
0dbfe35e8b6f0a9f76c1873b7f223356c3fee56e
| 18,726,057,445,275 |
ff4dbf14c20c88ba0bdabd267ba9ffb56d7598a9
|
/src/Fabrica/TestandoConexao.java
|
3756a190f15b3452453b9e46cb38a383998aaaa7
|
[] |
no_license
|
edurib17/cad-usuario-java
|
https://github.com/edurib17/cad-usuario-java
|
240ba59c8a5a97025133a32bd4f829f0f21746f8
|
f70c56ec5fd0fd597df4689e4f63c7f2004a7a57
|
refs/heads/main
| 2023-03-08T22:39:12.629000 | 2021-02-27T19:35:39 | 2021-02-27T19:35:39 | 342,940,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Fabrica;
/**
*
* @author eduardo
*/
import java.sql.Connection;
import java.sql.SQLException;
public class TestandoConexao {
public static void main(String[]args) throws SQLException {
Connection connection = new ConnectionFabrica().getConnection();
System.out.println("Conexão aberta!");
connection.close();
}
}
|
UTF-8
|
Java
| 358 |
java
|
TestandoConexao.java
|
Java
|
[
{
"context": "\npackage Fabrica;\n/**\n *\n * @author eduardo\n */\n \nimport java.sql.Connection;\nimport java.sql",
"end": 43,
"score": 0.9508554935455322,
"start": 36,
"tag": "NAME",
"value": "eduardo"
}
] | null |
[] |
package Fabrica;
/**
*
* @author eduardo
*/
import java.sql.Connection;
import java.sql.SQLException;
public class TestandoConexao {
public static void main(String[]args) throws SQLException {
Connection connection = new ConnectionFabrica().getConnection();
System.out.println("Conexão aberta!");
connection.close();
}
}
| 358 | 0.689076 | 0.689076 | 18 | 18.833334 | 20.923803 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
7
|
12a54f4c9f0c13be16e6b30f5426a127bbd5e6a8
| 27,144,193,335,129 |
747c934d03a4c1ef2871030805d1a9d8e4406724
|
/com.jduck.opencart/src/main/java/com/jduck/opencart/model/OcSession.java
|
7529f0f88d48dd89ded4df2c1e24f76f24944959
|
[] |
no_license
|
debashisz/JduckCommerce
|
https://github.com/debashisz/JduckCommerce
|
04e94d77284c21097bd7a7b5863d21cc2e1b4238
|
ac316d3abfed358e4043729e11df3e160a47db17
|
refs/heads/master
| 2020-03-21T23:36:51.312000 | 2018-07-07T06:18:59 | 2018-07-07T06:18:59 | 139,197,532 | 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 com.jduck.opencart.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Windows10
*/
@Entity
@Table(name = "oc_session")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "OcSession.findAll", query = "SELECT o FROM OcSession o"),
@NamedQuery(name = "OcSession.findBySessionId", query = "SELECT o FROM OcSession o WHERE o.sessionId = :sessionId"),
@NamedQuery(name = "OcSession.findByExpire", query = "SELECT o FROM OcSession o WHERE o.expire = :expire")})
public class OcSession implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 32)
@Column(name = "session_id")
private String sessionId;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "data")
private String data;
@Basic(optional = false)
@NotNull
@Column(name = "expire")
@Temporal(TemporalType.TIMESTAMP)
private Date expire;
public OcSession() {
}
public OcSession(String sessionId) {
this.sessionId = sessionId;
}
public OcSession(String sessionId, String data, Date expire) {
this.sessionId = sessionId;
this.data = data;
this.expire = expire;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Date getExpire() {
return expire;
}
public void setExpire(Date expire) {
this.expire = expire;
}
@Override
public int hashCode() {
int hash = 0;
hash += (sessionId != null ? sessionId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof OcSession)) {
return false;
}
OcSession other = (OcSession) object;
if ((this.sessionId == null && other.sessionId != null) || (this.sessionId != null && !this.sessionId.equals(other.sessionId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.jduck.opencart.model.OcSession[ sessionId=" + sessionId + " ]";
}
}
|
UTF-8
|
Java
| 3,162 |
java
|
OcSession.java
|
Java
|
[
{
"context": "bind.annotation.XmlRootElement;\n\n/**\n *\n * @author Windows10\n */\n@Entity\n@Table(name = \"oc_session\")\n@XmlRootE",
"end": 775,
"score": 0.9991462826728821,
"start": 766,
"tag": "USERNAME",
"value": "Windows10"
}
] | 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 com.jduck.opencart.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Windows10
*/
@Entity
@Table(name = "oc_session")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "OcSession.findAll", query = "SELECT o FROM OcSession o"),
@NamedQuery(name = "OcSession.findBySessionId", query = "SELECT o FROM OcSession o WHERE o.sessionId = :sessionId"),
@NamedQuery(name = "OcSession.findByExpire", query = "SELECT o FROM OcSession o WHERE o.expire = :expire")})
public class OcSession implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 32)
@Column(name = "session_id")
private String sessionId;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "data")
private String data;
@Basic(optional = false)
@NotNull
@Column(name = "expire")
@Temporal(TemporalType.TIMESTAMP)
private Date expire;
public OcSession() {
}
public OcSession(String sessionId) {
this.sessionId = sessionId;
}
public OcSession(String sessionId, String data, Date expire) {
this.sessionId = sessionId;
this.data = data;
this.expire = expire;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Date getExpire() {
return expire;
}
public void setExpire(Date expire) {
this.expire = expire;
}
@Override
public int hashCode() {
int hash = 0;
hash += (sessionId != null ? sessionId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof OcSession)) {
return false;
}
OcSession other = (OcSession) object;
if ((this.sessionId == null && other.sessionId != null) || (this.sessionId != null && !this.sessionId.equals(other.sessionId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.jduck.opencart.model.OcSession[ sessionId=" + sessionId + " ]";
}
}
| 3,162 | 0.6537 | 0.649273 | 118 | 25.79661 | 24.925842 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.440678 | false | false |
7
|
c3401dd940696f6ceab19b3e9ee9e02c9f455db2
| 32,650,341,444,644 |
500761e783f9c63efbb43e4654809939bffc62d6
|
/user/src/main/java/com/sxs/spi/App.java
|
13a73e1e8adb30a6bc06cc862a812f32b64cc515
|
[] |
no_license
|
dwyanewede/java-spi
|
https://github.com/dwyanewede/java-spi
|
76d501fa954544fc662d80af9404474407491b0f
|
6e419db3b5e727f46ed395d7011ffba73e15314b
|
refs/heads/master
| 2023-01-01T11:40:43.103000 | 2020-06-23T02:38:05 | 2020-06-23T02:38:05 | 274,290,248 | 0 | 0 | null | false | 2020-10-13T23:01:02 | 2020-06-23T02:32:35 | 2020-06-23T02:40:24 | 2020-10-13T23:01:01 | 4 | 0 | 0 | 5 |
Java
| false | false |
package com.sxs.spi;
import java.util.ServiceLoader;
/**
* Hello world!
*
*/
public class App{
/**
* 测试口罩种类
* @param args
*/
public static void main( String[] args ){
ServiceLoader<MaskInterface> maskLoader = ServiceLoader.load(MaskInterface.class);
for (MaskInterface mask : maskLoader) {
System.err.println(mask.getMask());
}
}
}
|
UTF-8
|
Java
| 415 |
java
|
App.java
|
Java
|
[] | null |
[] |
package com.sxs.spi;
import java.util.ServiceLoader;
/**
* Hello world!
*
*/
public class App{
/**
* 测试口罩种类
* @param args
*/
public static void main( String[] args ){
ServiceLoader<MaskInterface> maskLoader = ServiceLoader.load(MaskInterface.class);
for (MaskInterface mask : maskLoader) {
System.err.println(mask.getMask());
}
}
}
| 415 | 0.595533 | 0.595533 | 23 | 16.52174 | 21.729301 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.173913 | false | false |
7
|
f4327f56850c33ba67e35c0c2616f750380f7182
| 32,650,341,445,524 |
01304083410d3368696b9661150375a12758d6d5
|
/src/com/cmpe/serviceapp/MainActivity.java
|
da9d6db687577b31942f0a96408305b5e0d8c28b
|
[] |
no_license
|
GayathriSrinivas/AndroidServices
|
https://github.com/GayathriSrinivas/AndroidServices
|
0e2971bb2b1522c746ea7c1709ab53e096f3c3f4
|
da037fba4f2af359586aba0ae8b7fbc1a41d8a6a
|
refs/heads/master
| 2020-05-02T09:45:42.386000 | 2014-02-22T19:24:33 | 2014-02-22T19:24:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cmpe.serviceapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button btn_pdf;
private Button btn_image;
private Button btn_text;
private Button btn_close;
private Intent pdfIntent;
private Intent imageIntent;
private Intent textIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme_Holo);
setContentView(R.layout.activity_main);
btn_pdf =(Button)findViewById(R.id.btn_pdf);
btn_image =(Button)findViewById(R.id.btn_image);
btn_text =(Button)findViewById(R.id.btn_text);
btn_close =(Button)findViewById(R.id.btn_close);
btn_pdf.setOnClickListener(this);
btn_image.setOnClickListener(this);
btn_text.setOnClickListener(this);
btn_close.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_pdf:
pdfIntent = new Intent(this,DownloadPdfActivity.class);
startActivity(pdfIntent);
break;
case R.id.btn_image:
imageIntent = new Intent(this,DownloadImageActivity.class);
startActivity(imageIntent);
break;
case R.id.btn_text:
textIntent = new Intent(this,DownloadTextActivity.class);
startActivity(textIntent);
break;
case R.id.btn_close:
finish();
break;
default:
break;
}
}
}
|
UTF-8
|
Java
| 1,539 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.cmpe.serviceapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button btn_pdf;
private Button btn_image;
private Button btn_text;
private Button btn_close;
private Intent pdfIntent;
private Intent imageIntent;
private Intent textIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme_Holo);
setContentView(R.layout.activity_main);
btn_pdf =(Button)findViewById(R.id.btn_pdf);
btn_image =(Button)findViewById(R.id.btn_image);
btn_text =(Button)findViewById(R.id.btn_text);
btn_close =(Button)findViewById(R.id.btn_close);
btn_pdf.setOnClickListener(this);
btn_image.setOnClickListener(this);
btn_text.setOnClickListener(this);
btn_close.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_pdf:
pdfIntent = new Intent(this,DownloadPdfActivity.class);
startActivity(pdfIntent);
break;
case R.id.btn_image:
imageIntent = new Intent(this,DownloadImageActivity.class);
startActivity(imageIntent);
break;
case R.id.btn_text:
textIntent = new Intent(this,DownloadTextActivity.class);
startActivity(textIntent);
break;
case R.id.btn_close:
finish();
break;
default:
break;
}
}
}
| 1,539 | 0.744639 | 0.744639 | 59 | 25.084745 | 17.84613 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.338983 | false | false |
7
|
b062af58fcf8f3b685b9c82d798be4694c26dcbf
| 33,277,406,630,256 |
69329bf4c3fe3bd3e8c0df6e24ed3d30f4469a02
|
/src/main/java/org/ibatis/spring/SqlMapClientFactoryBeanX.java
|
86b75f0ed6ef8a1e94d0c1131d062b89cc312f74
|
[
"Apache-2.0"
] |
permissive
|
dukeware/jbatis
|
https://github.com/dukeware/jbatis
|
2527ab9180d994a4e02c813748e49625bfb70e6a
|
c5629b11aa8a56312118e7536a0e278e9b56d9b9
|
refs/heads/master
| 2020-04-03T14:04:09.802000 | 2018-10-31T07:18:10 | 2018-10-31T07:18:10 | 155,310,531 | 0 | 1 |
Apache-2.0
| false | 2018-10-30T04:07:37 | 2018-10-30T02:15:10 | 2018-10-30T03:32:26 | 2018-10-30T03:32:25 | 5 | 0 | 1 | 1 | null | false | null |
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ibatis.spring;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.springframework.web.context.ServletContextAware;
/**
* Add string attrs from servlet context to ibatis global properties.
*
* @author Song Sun
*/
public class SqlMapClientFactoryBeanX extends SqlMapClientFactoryBean implements ServletContextAware {
ServletContext servletContext;
@Override
public void setServletContext(ServletContext ctx) {
servletContext = ctx;
}
@Override
protected Properties getProperties(Properties props) {
Properties p = super.getProperties(props);
if (servletContext != null) {
Enumeration<String> params = servletContext.getInitParameterNames();
while (params.hasMoreElements()) {
String key = params.nextElement();
String val = servletContext.getInitParameter(key);
p.setProperty(key, (String) val);
}
Enumeration<String> keys = servletContext.getAttributeNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object val = servletContext.getAttribute(key);
if (val instanceof String) {
p.setProperty(key, (String) val);
}
}
}
return p;
}
}
|
UTF-8
|
Java
| 2,055 |
java
|
SqlMapClientFactoryBeanX.java
|
Java
|
[
{
"context": "ontext to ibatis global properties.\n * \n * @author Song Sun\n */\npublic class SqlMapClientFactoryBeanX extends ",
"end": 906,
"score": 0.9649365544319153,
"start": 898,
"tag": "NAME",
"value": "Song Sun"
}
] | null |
[] |
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ibatis.spring;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.springframework.web.context.ServletContextAware;
/**
* Add string attrs from servlet context to ibatis global properties.
*
* @author <NAME>
*/
public class SqlMapClientFactoryBeanX extends SqlMapClientFactoryBean implements ServletContextAware {
ServletContext servletContext;
@Override
public void setServletContext(ServletContext ctx) {
servletContext = ctx;
}
@Override
protected Properties getProperties(Properties props) {
Properties p = super.getProperties(props);
if (servletContext != null) {
Enumeration<String> params = servletContext.getInitParameterNames();
while (params.hasMoreElements()) {
String key = params.nextElement();
String val = servletContext.getInitParameter(key);
p.setProperty(key, (String) val);
}
Enumeration<String> keys = servletContext.getAttributeNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object val = servletContext.getAttribute(key);
if (val instanceof String) {
p.setProperty(key, (String) val);
}
}
}
return p;
}
}
| 2,053 | 0.656934 | 0.651095 | 63 | 31.619047 | 27.2673 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false |
7
|
a4bc963e2019cdcd0052d26caa637e57e8cd3391
| 15,513,421,915,482 |
ab69dc77fa4abe726120a9c61da0153f8109b409
|
/sms/src/main/java/sms/entities/order/promotion/range/IPromotionRangeService.java
|
1babd88a287096d7e747f9e2d0e6a37d09981022
|
[] |
no_license
|
Solonaru/SQA
|
https://github.com/Solonaru/SQA
|
c23f472af6c4f9d30fcdb05156146ec9f45a0c67
|
74e1bca9c17f8fd161df21ddffc17beb7bbf443c
|
refs/heads/master
| 2020-04-27T20:49:25.336000 | 2019-05-05T07:55:19 | 2019-05-05T07:55:19 | 174,672,075 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sms.entities.order.promotion.range;
import java.util.List;
import java.util.Optional;
public interface IPromotionRangeService {
public Optional<PromotionRange> findPromotionRangeById(int promotionRangeId);
public List<PromotionRange> findAllPromotionRanges();
public void insertPromotionRange(PromotionRange promotionRange);
public void updatePromotionRange(PromotionRange promotionRange);
public void deletePromotionRangeById(int promotionRangeId);
}
|
UTF-8
|
Java
| 473 |
java
|
IPromotionRangeService.java
|
Java
|
[] | null |
[] |
package sms.entities.order.promotion.range;
import java.util.List;
import java.util.Optional;
public interface IPromotionRangeService {
public Optional<PromotionRange> findPromotionRangeById(int promotionRangeId);
public List<PromotionRange> findAllPromotionRanges();
public void insertPromotionRange(PromotionRange promotionRange);
public void updatePromotionRange(PromotionRange promotionRange);
public void deletePromotionRangeById(int promotionRangeId);
}
| 473 | 0.841438 | 0.841438 | 18 | 25.277779 | 28.126314 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false |
7
|
844be73f3e8e245265ddcb05a17513a855154961
| 19,954,418,101,458 |
03462483890d138caa1fad3dca3d5aa75639f7af
|
/shop/src/main/java/ro/msg/learning/configuration/SpringMailConfig.java
|
89baa96f0ccaaf5d46ee654e521008a701800379
|
[
"MIT"
] |
permissive
|
ro-msg-spring-training/online-shop-PatriciaPopa21
|
https://github.com/ro-msg-spring-training/online-shop-PatriciaPopa21
|
18bf2d3f4717ce574629f0ac5cd9e24b6094aa4b
|
50fbaefe7282beb6f4e4ef6ef7ae2a31f648f7b9
|
refs/heads/master
| 2021-03-03T13:33:23.318000 | 2020-04-29T10:41:06 | 2020-04-29T10:41:06 | 245,964,373 | 1 | 0 |
MIT
| false | 2020-04-29T10:41:08 | 2020-03-09T06:55:39 | 2020-04-27T13:23:17 | 2020-04-29T10:41:07 | 233 | 1 | 0 | 0 |
Java
| false | false |
package ro.msg.learning.configuration;
import java.io.IOException;
import java.util.Collections;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
@Configuration
@PropertySource("classpath:mail/emailconfig.properties")
public class SpringMailConfig implements ApplicationContextAware, EnvironmentAware {
public static final String EMAIL_TEMPLATE_ENCODING = "UTF-8";
private static final String JAVA_MAIL_FILE = "classpath:mail/javamail.properties";
private static final String HOST = "spring.mail.host";
private static final String PORT = "spring.mail.port";
private static final String PROTOCOL = "mail.server.protocol";
private static final String USERNAME = "spring.mail.username";
private static final String PASSWORD = "spring.mail.password";
private ApplicationContext applicationContext;
private Environment environment;
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void setEnvironment(final Environment environment) {
this.environment = environment;
}
/*
* SPRING + JAVAMAIL: JavaMailSender instance, configured via .properties files.
*/
@Bean
public JavaMailSender mailSender() throws IOException {
final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
// Basic mail sender configuration, based on emailconfig.properties
mailSender.setHost(environment.getProperty(HOST));
mailSender.setPort(Integer.parseInt(environment.getProperty(PORT)));
mailSender.setProtocol(environment.getProperty(PROTOCOL));
mailSender.setUsername(environment.getProperty(USERNAME));
mailSender.setPassword(environment.getProperty(PASSWORD));
// JavaMail-specific mail sender configuration, based on javamail.properties
final Properties javaMailProperties = new Properties();
javaMailProperties.load(applicationContext.getResource(JAVA_MAIL_FILE).getInputStream());
mailSender.setJavaMailProperties(javaMailProperties);
return mailSender;
}
/*
* Message externalization/internationalization for emails.
*
* NOTE we are avoiding the use of the name 'messageSource' for this bean
* because that would make the MessageSource defined in SpringWebConfig (and
* made available for the web-side template engine) delegate to this one, and
* thus effectively merge email messages into web messages and make both types
* available at the web side, which could bring undesired collisions.
*
* NOTE also that given we want this specific message source to be used by our
* SpringTemplateEngines for emails (and not by the web one), we will set it
* explicitly into each of the TemplateEngine objects with
* 'setTemplateEngineMessageSource(...)'
*/
@Bean
public ResourceBundleMessageSource emailMessageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("mail/messages.properties");
return messageSource;
}
/* ******************************************************************** */
/* THYMELEAF-SPECIFIC ARTIFACTS FOR EMAIL */
/* TemplateResolver(3) <- TemplateEngine */
/* ******************************************************************** */
@Bean
public TemplateEngine emailTemplateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// Resolver for TEXT emails
templateEngine.addTemplateResolver(textTemplateResolver());
// Resolver for HTML emails (except the editable one)
templateEngine.addTemplateResolver(htmlTemplateResolver());
// Message source, internationalization specific to emails
templateEngine.setTemplateEngineMessageSource(emailMessageSource());
return templateEngine;
}
private ITemplateResolver textTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(1);
templateResolver.setResolvablePatterns(Collections.singleton("text/*"));
templateResolver.setPrefix("/mail/");
templateResolver.setSuffix(".txt");
templateResolver.setTemplateMode(TemplateMode.TEXT);
templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING);
templateResolver.setCacheable(false);
return templateResolver;
}
private ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(2);
templateResolver.setResolvablePatterns(Collections.singleton("html/*"));
templateResolver.setPrefix("/mail/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING);
templateResolver.setCacheable(false);
return templateResolver;
}
}
|
UTF-8
|
Java
| 5,647 |
java
|
SpringMailConfig.java
|
Java
|
[
{
"context": "ername\";\n\tprivate static final String PASSWORD = \"spring.mail.password\";\n\n\tprivate ApplicationContext applicationContext",
"end": 1628,
"score": 0.9994385838508606,
"start": 1608,
"tag": "PASSWORD",
"value": "spring.mail.password"
},
{
"context": "\n\t\tmailSender.setUsername(environment.getProperty(USERNAME));\n\t\tmailSender.setPassword(environment.getProper",
"end": 2527,
"score": 0.9849269390106201,
"start": 2519,
"tag": "USERNAME",
"value": "USERNAME"
}
] | null |
[] |
package ro.msg.learning.configuration;
import java.io.IOException;
import java.util.Collections;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
@Configuration
@PropertySource("classpath:mail/emailconfig.properties")
public class SpringMailConfig implements ApplicationContextAware, EnvironmentAware {
public static final String EMAIL_TEMPLATE_ENCODING = "UTF-8";
private static final String JAVA_MAIL_FILE = "classpath:mail/javamail.properties";
private static final String HOST = "spring.mail.host";
private static final String PORT = "spring.mail.port";
private static final String PROTOCOL = "mail.server.protocol";
private static final String USERNAME = "spring.mail.username";
private static final String PASSWORD = "<PASSWORD>";
private ApplicationContext applicationContext;
private Environment environment;
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void setEnvironment(final Environment environment) {
this.environment = environment;
}
/*
* SPRING + JAVAMAIL: JavaMailSender instance, configured via .properties files.
*/
@Bean
public JavaMailSender mailSender() throws IOException {
final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
// Basic mail sender configuration, based on emailconfig.properties
mailSender.setHost(environment.getProperty(HOST));
mailSender.setPort(Integer.parseInt(environment.getProperty(PORT)));
mailSender.setProtocol(environment.getProperty(PROTOCOL));
mailSender.setUsername(environment.getProperty(USERNAME));
mailSender.setPassword(environment.getProperty(PASSWORD));
// JavaMail-specific mail sender configuration, based on javamail.properties
final Properties javaMailProperties = new Properties();
javaMailProperties.load(applicationContext.getResource(JAVA_MAIL_FILE).getInputStream());
mailSender.setJavaMailProperties(javaMailProperties);
return mailSender;
}
/*
* Message externalization/internationalization for emails.
*
* NOTE we are avoiding the use of the name 'messageSource' for this bean
* because that would make the MessageSource defined in SpringWebConfig (and
* made available for the web-side template engine) delegate to this one, and
* thus effectively merge email messages into web messages and make both types
* available at the web side, which could bring undesired collisions.
*
* NOTE also that given we want this specific message source to be used by our
* SpringTemplateEngines for emails (and not by the web one), we will set it
* explicitly into each of the TemplateEngine objects with
* 'setTemplateEngineMessageSource(...)'
*/
@Bean
public ResourceBundleMessageSource emailMessageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("mail/messages.properties");
return messageSource;
}
/* ******************************************************************** */
/* THYMELEAF-SPECIFIC ARTIFACTS FOR EMAIL */
/* TemplateResolver(3) <- TemplateEngine */
/* ******************************************************************** */
@Bean
public TemplateEngine emailTemplateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// Resolver for TEXT emails
templateEngine.addTemplateResolver(textTemplateResolver());
// Resolver for HTML emails (except the editable one)
templateEngine.addTemplateResolver(htmlTemplateResolver());
// Message source, internationalization specific to emails
templateEngine.setTemplateEngineMessageSource(emailMessageSource());
return templateEngine;
}
private ITemplateResolver textTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(1);
templateResolver.setResolvablePatterns(Collections.singleton("text/*"));
templateResolver.setPrefix("/mail/");
templateResolver.setSuffix(".txt");
templateResolver.setTemplateMode(TemplateMode.TEXT);
templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING);
templateResolver.setCacheable(false);
return templateResolver;
}
private ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setOrder(2);
templateResolver.setResolvablePatterns(Collections.singleton("html/*"));
templateResolver.setPrefix("/mail/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING);
templateResolver.setCacheable(false);
return templateResolver;
}
}
| 5,637 | 0.791039 | 0.790154 | 137 | 40.226276 | 28.960833 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.532847 | false | false |
7
|
a33ceeea352882c254f0fa1a75fd08b503dbd424
| 30,408,368,466,508 |
2beec7093215e799e04846165d9c664d3b0662b5
|
/src/PC_part/SACK_pc_client/Dialogs/ErrorDialogue.java
|
8d8ce5e400b8e5923d1a6f201f764167fd751223
|
[] |
no_license
|
ShirinkinArseny/SchoolAlarmClocK
|
https://github.com/ShirinkinArseny/SchoolAlarmClocK
|
347487d8e662c8bb12ae86bef47e94b1e551c30f
|
7061efc17a1adca7e2fa92fc35f3ebfa28f084e4
|
refs/heads/master
| 2021-01-22T02:58:08.170000 | 2015-05-15T10:53:32 | 2015-05-15T10:53:32 | 31,126,447 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package PC_part.SACK_pc_client.Dialogs;
import PC_part.SACK_pc_client.Controls.UICanvas;
import javax.swing.*;
import java.awt.event.*;
public class ErrorDialogue extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JTextArea errorText;
public ErrorDialogue(String text) {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(e -> dispose());
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
errorText.setText(text);
contentPane.registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
setSize(400, 200);
setLocation(UICanvas.clickX - 200, UICanvas.clickY - 100);
setVisible(true);
}
}
|
UTF-8
|
Java
| 1,016 |
java
|
ErrorDialogue.java
|
Java
|
[] | null |
[] |
package PC_part.SACK_pc_client.Dialogs;
import PC_part.SACK_pc_client.Controls.UICanvas;
import javax.swing.*;
import java.awt.event.*;
public class ErrorDialogue extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JTextArea errorText;
public ErrorDialogue(String text) {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(e -> dispose());
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
errorText.setText(text);
contentPane.registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
setSize(400, 200);
setLocation(UICanvas.clickX - 200, UICanvas.clickY - 100);
setVisible(true);
}
}
| 1,016 | 0.66437 | 0.651575 | 37 | 26.459459 | 29.02524 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.648649 | false | false |
7
|
5efa7fc5108e7a1e49f34e5dae439f4c40cd7403
| 25,417,616,491,820 |
e8626f9f64a8bb90008015b06856d3da16eeecad
|
/processing/src/main/java/org/apache/druid/java/util/metrics/CgroupCpuSetMonitor.java
|
0534e00259f352b10619309e3577a7884a8c8589
|
[
"EPL-1.0",
"Classpath-exception-2.0",
"ISC",
"GPL-2.0-only",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-cla",
"0BSD",
"LicenseRef-scancode-sun-no-high-risk-activities",
"LicenseRef-scancode-free-unknown",
"JSON",
"LicenseRef-scancode-unicode",
"CC-BY-SA-3.0",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-westhawk",
"CDDL-1.1",
"BSD-2-Clause",
"EPL-2.0",
"CDDL-1.0",
"GCC-exception-3.1",
"MPL-2.0",
"CC-PDDC",
"MIT",
"LicenseRef-scancode-unicode-icu-58",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
apache/druid
|
https://github.com/apache/druid
|
bb1b20be5104882e4eeb045d109b559f396086c0
|
d4e972e1e4b798d7e057e910deea4d192fe57952
|
refs/heads/master
| 2023-09-05T02:41:03.009000 | 2023-09-04T07:48:55 | 2023-09-04T07:48:55 | 6,358,188 | 4,364 | 1,629 |
Apache-2.0
| false | 2023-09-14T21:04:46 | 2012-10-23T19:08:07 | 2023-09-14T21:04:40 | 2023-09-14T21:04:46 | 324,885 | 12,839 | 3,591 | 1,383 |
Java
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.java.util.metrics;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
import org.apache.druid.java.util.metrics.cgroups.CgroupDiscoverer;
import org.apache.druid.java.util.metrics.cgroups.CpuSet;
import java.util.Map;
public class CgroupCpuSetMonitor extends FeedDefiningMonitor
{
final CgroupDiscoverer cgroupDiscoverer;
final Map<String, String[]> dimensions;
public CgroupCpuSetMonitor(CgroupDiscoverer cgroupDiscoverer, final Map<String, String[]> dimensions, String feed)
{
super(feed);
this.cgroupDiscoverer = cgroupDiscoverer;
this.dimensions = dimensions;
}
public CgroupCpuSetMonitor(final Map<String, String[]> dimensions, String feed)
{
this(null, dimensions, feed);
}
public CgroupCpuSetMonitor(final Map<String, String[]> dimensions)
{
this(dimensions, DEFAULT_METRICS_FEED);
}
public CgroupCpuSetMonitor()
{
this(ImmutableMap.of());
}
@Override
public boolean doMonitor(ServiceEmitter emitter)
{
final CpuSet cpuset = new CpuSet(cgroupDiscoverer);
final CpuSet.CpuSetMetric cpusetSnapshot = cpuset.snapshot();
final ServiceMetricEvent.Builder builder = builder();
MonitorUtils.addDimensionsToBuilder(builder, dimensions);
emitter.emit(builder.setMetric(
"cgroup/cpuset/cpu_count",
cpusetSnapshot.getCpuSetCpus().length
));
emitter.emit(builder.setMetric(
"cgroup/cpuset/effective_cpu_count",
cpusetSnapshot.getEffectiveCpuSetCpus().length
));
emitter.emit(builder.setMetric(
"cgroup/cpuset/mems_count",
cpusetSnapshot.getCpuSetMems().length
));
emitter.emit(builder.setMetric(
"cgroup/cpuset/effective_mems_count",
cpusetSnapshot.getEffectiveCpuSetMems().length
));
return true;
}
}
|
UTF-8
|
Java
| 2,748 |
java
|
CgroupCpuSetMonitor.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.java.util.metrics;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.java.util.emitter.service.ServiceMetricEvent;
import org.apache.druid.java.util.metrics.cgroups.CgroupDiscoverer;
import org.apache.druid.java.util.metrics.cgroups.CpuSet;
import java.util.Map;
public class CgroupCpuSetMonitor extends FeedDefiningMonitor
{
final CgroupDiscoverer cgroupDiscoverer;
final Map<String, String[]> dimensions;
public CgroupCpuSetMonitor(CgroupDiscoverer cgroupDiscoverer, final Map<String, String[]> dimensions, String feed)
{
super(feed);
this.cgroupDiscoverer = cgroupDiscoverer;
this.dimensions = dimensions;
}
public CgroupCpuSetMonitor(final Map<String, String[]> dimensions, String feed)
{
this(null, dimensions, feed);
}
public CgroupCpuSetMonitor(final Map<String, String[]> dimensions)
{
this(dimensions, DEFAULT_METRICS_FEED);
}
public CgroupCpuSetMonitor()
{
this(ImmutableMap.of());
}
@Override
public boolean doMonitor(ServiceEmitter emitter)
{
final CpuSet cpuset = new CpuSet(cgroupDiscoverer);
final CpuSet.CpuSetMetric cpusetSnapshot = cpuset.snapshot();
final ServiceMetricEvent.Builder builder = builder();
MonitorUtils.addDimensionsToBuilder(builder, dimensions);
emitter.emit(builder.setMetric(
"cgroup/cpuset/cpu_count",
cpusetSnapshot.getCpuSetCpus().length
));
emitter.emit(builder.setMetric(
"cgroup/cpuset/effective_cpu_count",
cpusetSnapshot.getEffectiveCpuSetCpus().length
));
emitter.emit(builder.setMetric(
"cgroup/cpuset/mems_count",
cpusetSnapshot.getCpuSetMems().length
));
emitter.emit(builder.setMetric(
"cgroup/cpuset/effective_mems_count",
cpusetSnapshot.getEffectiveCpuSetMems().length
));
return true;
}
}
| 2,748 | 0.740539 | 0.739083 | 83 | 32.108433 | 26.636786 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53012 | false | false |
7
|
4d9d5afe4d09d076cd61548fabc18c2759ed0e82
| 30,210,800,001,259 |
6a7e7b6ec4975558397c84a78fecaabee018fc88
|
/src/main/java/model/Stock.java
|
d40a0ae464385ce13ceed3dd508520caa5c07657
|
[] |
no_license
|
FrancescoMa/SuperSimpleStocks
|
https://github.com/FrancescoMa/SuperSimpleStocks
|
390a503d87f8cc6153d2035737c7d70d0f76cfb9
|
c695952ce9f812a3d2c3902f188893f87a5867a4
|
refs/heads/master
| 2020-04-05T23:34:27.193000 | 2015-09-26T23:29:21 | 2015-09-26T23:29:21 | 42,819,167 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*
*/
package model;
import org.apache.log4j.Logger;
import mainStocks.Operations;
/**
* @author FrancescoM
*
*/
public class Stock {
final static Logger logger = Logger.getLogger(Stock.class);
private String symbol="";
private boolean preferred=false;
private double lastDividend=0.0;
private double fixedDividend;
private double parValue=0.0;
/*
* progressive. it is reasonable to assume that:
* if is register a sales growth in the previous 15 min,
* the price increases of (deltax/qtySell)%
*/
private double tickerPrice = 1.0;
/*
* this constructor is for common Stocks. So, it hasn't the Fixed Dividend value
*/
public Stock(String symbol, int lastDividend, int parValue){
this.symbol=symbol;
this.lastDividend=lastDividend;
this.parValue=parValue;
}
/*
* this constructor is for preferred Stocks
*/
public Stock(String symbol, int lastDividend, int fixedDividend, int parValue){
this.symbol=symbol;
this.lastDividend=lastDividend;
this.parValue=parValue;
this.fixedDividend=fixedDividend;
this.preferred=true;
}
/**
* @return the symbol
*/
public String getSymbol() {
return symbol;
}
/**
* @param symbol the symbol to set
*/
public void setSymbol(String symbol) {
this.symbol = symbol;
}
/**
* @return the preferred
*/
public boolean isPreferred() {
return preferred;
}
/**
* @param preferred the preferred to set
*/
public void setPreferred(boolean preferred) {
this.preferred = preferred;
}
/**
* @return the lastDividend
*/
public double getLastDividend() {
return lastDividend;
}
/**
* @param lastDividend the lastDividend to set
*/
public void setLastDividend(double lastDividend) {
this.lastDividend = lastDividend;
}
/**
* @return the fixedDividend
*/
public double getFixedDividend() {
return fixedDividend;
}
/**
* @param fixedDividend the fixedDividend to set
*/
public void setFixedDividend(double fixedDividend) {
this.fixedDividend = fixedDividend;
}
/**
* @return the parValue
*/
public double getParValue() {
return parValue;
}
/**
* @param parValue the parValue to set
*/
public void setParValue(double parValue) {
this.parValue = parValue;
}
/**
* @return the tickerPrice
*/
public double getTickerPrice() {
return tickerPrice;
}
/**
* @param tickerPrice the tickerPrice to set
*/
public void setTickerPrice(double tickerPrice) {
this.tickerPrice = tickerPrice;
Operations op= new Operations();
double dividendUpgrade;
try {
dividendUpgrade = op.peRatio(lastDividend, tickerPrice);
this.lastDividend= dividendUpgrade;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 2,759 |
java
|
Stock.java
|
Java
|
[
{
"context": "r;\n\nimport mainStocks.Operations;\n\n\n/**\n * @author FrancescoM\n *\n */\npublic class Stock {\n\n\tfinal static Logger",
"end": 118,
"score": 0.7551258206367493,
"start": 108,
"tag": "NAME",
"value": "FrancescoM"
}
] | null |
[] |
/**
*
*/
package model;
import org.apache.log4j.Logger;
import mainStocks.Operations;
/**
* @author FrancescoM
*
*/
public class Stock {
final static Logger logger = Logger.getLogger(Stock.class);
private String symbol="";
private boolean preferred=false;
private double lastDividend=0.0;
private double fixedDividend;
private double parValue=0.0;
/*
* progressive. it is reasonable to assume that:
* if is register a sales growth in the previous 15 min,
* the price increases of (deltax/qtySell)%
*/
private double tickerPrice = 1.0;
/*
* this constructor is for common Stocks. So, it hasn't the Fixed Dividend value
*/
public Stock(String symbol, int lastDividend, int parValue){
this.symbol=symbol;
this.lastDividend=lastDividend;
this.parValue=parValue;
}
/*
* this constructor is for preferred Stocks
*/
public Stock(String symbol, int lastDividend, int fixedDividend, int parValue){
this.symbol=symbol;
this.lastDividend=lastDividend;
this.parValue=parValue;
this.fixedDividend=fixedDividend;
this.preferred=true;
}
/**
* @return the symbol
*/
public String getSymbol() {
return symbol;
}
/**
* @param symbol the symbol to set
*/
public void setSymbol(String symbol) {
this.symbol = symbol;
}
/**
* @return the preferred
*/
public boolean isPreferred() {
return preferred;
}
/**
* @param preferred the preferred to set
*/
public void setPreferred(boolean preferred) {
this.preferred = preferred;
}
/**
* @return the lastDividend
*/
public double getLastDividend() {
return lastDividend;
}
/**
* @param lastDividend the lastDividend to set
*/
public void setLastDividend(double lastDividend) {
this.lastDividend = lastDividend;
}
/**
* @return the fixedDividend
*/
public double getFixedDividend() {
return fixedDividend;
}
/**
* @param fixedDividend the fixedDividend to set
*/
public void setFixedDividend(double fixedDividend) {
this.fixedDividend = fixedDividend;
}
/**
* @return the parValue
*/
public double getParValue() {
return parValue;
}
/**
* @param parValue the parValue to set
*/
public void setParValue(double parValue) {
this.parValue = parValue;
}
/**
* @return the tickerPrice
*/
public double getTickerPrice() {
return tickerPrice;
}
/**
* @param tickerPrice the tickerPrice to set
*/
public void setTickerPrice(double tickerPrice) {
this.tickerPrice = tickerPrice;
Operations op= new Operations();
double dividendUpgrade;
try {
dividendUpgrade = op.peRatio(lastDividend, tickerPrice);
this.lastDividend= dividendUpgrade;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 2,759 | 0.689743 | 0.686481 | 153 | 17.032681 | 18.576611 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.30719 | false | false |
7
|
8c7e06f269be6d0154005a36a547344ecb2c66c3
| 25,271,587,623,264 |
08e538cf4a2c4490570994b0c1cbe9539fc07916
|
/Tema 2/Prácticas/Practica 2/src/java/Login.java
|
6ba288a4a9b6286c70d465749b8a70ce13cb140b
|
[] |
no_license
|
LadyNightmare/ServiciosTelematicos
|
https://github.com/LadyNightmare/ServiciosTelematicos
|
568f210dd3d8df622cf7d68628e7416d78b03172
|
3be172660425249f24d581a969a16387b460cf9e
|
refs/heads/master
| 2020-03-27T21:13:01.574000 | 2019-09-28T10:41:01 | 2019-09-28T10:41:01 | 147,125,295 | 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.
*/
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author ladynightmare
*/
@WebServlet(urlPatterns = {"/Login"})
public class Login extends HttpServlet {
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String password = request.getParameter("password");
String dir = request.getParameter("dire");
Boolean enc = false;
File f = new File(dir + "\\log.txt");
if(f.exists()){
Scanner sc = new Scanner (f);
while(sc.hasNext()){
String us = sc.next();
String pas = sc.next();
if(us.equals(user) && pas.equals(password)) {
enc = true;
}
}
if (enc) {
HttpSession session = request.getSession(true);
session.putValue("user", user);
session.putValue("dir", "");
response.sendRedirect("blog.jsp");
} else {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
PrintWriter out = response.getWriter();
out.println("<p id='warning'>Contraseña o usuario incorrecto</p>\n");
rd.include(request, response);
}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
PrintWriter out = response.getWriter();
out.println("<p id='warning'>No hay registro</p>\n");
rd.include(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
UTF-8
|
Java
| 3,317 |
java
|
Login.java
|
Java
|
[
{
"context": "javax.servlet.http.HttpSession;\n\n/**\n *\n * @author ladynightmare\n */\n@WebServlet(urlPatterns = {\"/Login\"})\npublic ",
"end": 640,
"score": 0.9993289113044739,
"start": 627,
"tag": "USERNAME",
"value": "ladynightmare"
},
{
"context": ";\n String password = request.getParameter(\"password\");\n String dir = request.getParameter(\"dir",
"end": 1754,
"score": 0.5130103230476379,
"start": 1746,
"tag": "PASSWORD",
"value": "password"
}
] | 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.
*/
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author ladynightmare
*/
@WebServlet(urlPatterns = {"/Login"})
public class Login extends HttpServlet {
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String password = request.getParameter("<PASSWORD>");
String dir = request.getParameter("dire");
Boolean enc = false;
File f = new File(dir + "\\log.txt");
if(f.exists()){
Scanner sc = new Scanner (f);
while(sc.hasNext()){
String us = sc.next();
String pas = sc.next();
if(us.equals(user) && pas.equals(password)) {
enc = true;
}
}
if (enc) {
HttpSession session = request.getSession(true);
session.putValue("user", user);
session.putValue("dir", "");
response.sendRedirect("blog.jsp");
} else {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
PrintWriter out = response.getWriter();
out.println("<p id='warning'>Contraseña o usuario incorrecto</p>\n");
rd.include(request, response);
}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
PrintWriter out = response.getWriter();
out.println("<p id='warning'>No hay registro</p>\n");
rd.include(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 3,319 | 0.614411 | 0.614109 | 105 | 30.590477 | 25.845953 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
7
|
97afd1f266c94cc9584eb9d54da1a4d4c60e0c96
| 17,626,545,822,077 |
348e4b63c761cbf41b3c2b385f961eb63a62ea7c
|
/src/main/java/de/hska/customer/rest/CustomerHandler.java
|
77982d8116cc29c90e5f4e29e07a9896b18cabe5
|
[] |
no_license
|
JohnnyVim/AvG-RESTful
|
https://github.com/JohnnyVim/AvG-RESTful
|
87bfc7b5b955c4e5d27b7fd2fd4d45089b95a5af
|
5bdf8a238406fcb9d2d03bebdd0427c7fcf4c67e
|
refs/heads/master
| 2020-04-03T00:02:44.659000 | 2018-10-29T15:19:59 | 2018-10-29T15:19:59 | 154,886,662 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.hska.customer.rest;
import de.hska.customer.entity.Customer;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CustomerHandler {
private List<Customer> customers;
public CustomerHandler() {
customers = new ArrayList<>();
customers.add(new Customer("Manuel", "Neuer", 1000));
customers.add(new Customer("Ariane", "Alpha", 2000));
customers.add(new Customer("Benno", "Beta", 500));
}
public ResponseEntity<List<Customer>> findAll() {
if (emptyCustomers()) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(customers, HttpStatus.OK);
}
public ResponseEntity<Customer> findByName(String firstName, String lastName) {
if (emptyCustomers()) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
Customer temp = findCustomer(firstName, lastName);
if (temp == null) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(temp, HttpStatus.OK);
}
public ResponseEntity<Boolean> add(Customer customer) {
Customer temp = findCustomer(customer);
if (temp != null) return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
customers.add(customer);
return new ResponseEntity<>(HttpStatus.CREATED);
}
public ResponseEntity<Boolean> isCreditWorthy(Customer customer, double credit) {
if (customer.getLimit() > credit)
return new ResponseEntity<>(HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
private boolean emptyCustomers() {
return (customers == null || customers.isEmpty());
}
private Customer findCustomer(String firstName, String lastName) {
if (emptyCustomers()) return null;
List<Customer> temp = customers.stream().filter(x -> x.getFirstName().equals(firstName)
&& x.getLastName().equals(lastName)).collect(Collectors.toList());
if (temp.size() != 1) return null;
return temp.get(0);
}
private Customer findCustomer(Customer customer) {
return findCustomer(customer.getFirstName(), customer.getLastName());
}
}
|
UTF-8
|
Java
| 2,309 |
java
|
CustomerHandler.java
|
Java
|
[
{
"context": "rrayList<>();\n customers.add(new Customer(\"Manuel\", \"Neuer\", 1000));\n customers.add(new Cust",
"end": 436,
"score": 0.9997597932815552,
"start": 430,
"tag": "NAME",
"value": "Manuel"
},
{
"context": "();\n customers.add(new Customer(\"Manuel\", \"Neuer\", 1000));\n customers.add(new Customer(\"Ari",
"end": 445,
"score": 0.9996992349624634,
"start": 440,
"tag": "NAME",
"value": "Neuer"
},
{
"context": "uer\", 1000));\n customers.add(new Customer(\"Ariane\", \"Alpha\", 2000));\n customers.add(new Cust",
"end": 498,
"score": 0.999855101108551,
"start": 492,
"tag": "NAME",
"value": "Ariane"
},
{
"context": "pha\", 2000));\n customers.add(new Customer(\"Benno\", \"Beta\", 500));\n }\n\n public ResponseEntity",
"end": 559,
"score": 0.9997841715812683,
"start": 554,
"tag": "NAME",
"value": "Benno"
}
] | null |
[] |
package de.hska.customer.rest;
import de.hska.customer.entity.Customer;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CustomerHandler {
private List<Customer> customers;
public CustomerHandler() {
customers = new ArrayList<>();
customers.add(new Customer("Manuel", "Neuer", 1000));
customers.add(new Customer("Ariane", "Alpha", 2000));
customers.add(new Customer("Benno", "Beta", 500));
}
public ResponseEntity<List<Customer>> findAll() {
if (emptyCustomers()) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(customers, HttpStatus.OK);
}
public ResponseEntity<Customer> findByName(String firstName, String lastName) {
if (emptyCustomers()) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
Customer temp = findCustomer(firstName, lastName);
if (temp == null) return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(temp, HttpStatus.OK);
}
public ResponseEntity<Boolean> add(Customer customer) {
Customer temp = findCustomer(customer);
if (temp != null) return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
customers.add(customer);
return new ResponseEntity<>(HttpStatus.CREATED);
}
public ResponseEntity<Boolean> isCreditWorthy(Customer customer, double credit) {
if (customer.getLimit() > credit)
return new ResponseEntity<>(HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
private boolean emptyCustomers() {
return (customers == null || customers.isEmpty());
}
private Customer findCustomer(String firstName, String lastName) {
if (emptyCustomers()) return null;
List<Customer> temp = customers.stream().filter(x -> x.getFirstName().equals(firstName)
&& x.getLastName().equals(lastName)).collect(Collectors.toList());
if (temp.size() != 1) return null;
return temp.get(0);
}
private Customer findCustomer(Customer customer) {
return findCustomer(customer.getFirstName(), customer.getLastName());
}
}
| 2,309 | 0.679515 | 0.673885 | 62 | 36.241936 | 28.942482 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.725806 | false | false |
7
|
b5e0c3a4b3133c409e38222f41835c945ae7bf4b
| 32,624,571,593,293 |
9528993f63a35c8ee989e05456a098e3f6aef5e0
|
/solutions/Language/src/test/java/roman/numerals/NumeralsTest.java
|
571f68a02c0da5cfae06041f1022477917c9a463
|
[] |
no_license
|
SF3/Java-and-Spring
|
https://github.com/SF3/Java-and-Spring
|
6443f461935544cbc7687715b4baa658deb644dc
|
e186379788f1d7fb805168798e1ea2f3f09c7860
|
refs/heads/main
| 2023-05-31T05:54:15.579000 | 2021-07-01T09:34:49 | 2021-07-01T09:34:49 | 382,361,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package roman.numerals;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class NumeralsTest {
@Test
public void conversions() {
assertEquals("I",Numeral.convert(1));
assertEquals("III",Numeral.convert(3));
assertEquals("IV",Numeral.convert(4));
assertEquals("V",Numeral.convert(5));
assertEquals("VI",Numeral.convert(6));
assertEquals("IX",Numeral.convert(9));
assertEquals("X",Numeral.convert(10));
assertEquals("XI",Numeral.convert(11));
assertEquals("XL",Numeral.convert(40));
assertEquals("XLI",Numeral.convert(41));
assertEquals("L",Numeral.convert(50));
assertEquals("LI",Numeral.convert(51));
assertEquals("XC",Numeral.convert(90));
assertEquals("XCI",Numeral.convert(91));
assertEquals("C",Numeral.convert(100));
assertEquals("CI",Numeral.convert(101));
}
}
|
UTF-8
|
Java
| 859 |
java
|
NumeralsTest.java
|
Java
|
[] | null |
[] |
package roman.numerals;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class NumeralsTest {
@Test
public void conversions() {
assertEquals("I",Numeral.convert(1));
assertEquals("III",Numeral.convert(3));
assertEquals("IV",Numeral.convert(4));
assertEquals("V",Numeral.convert(5));
assertEquals("VI",Numeral.convert(6));
assertEquals("IX",Numeral.convert(9));
assertEquals("X",Numeral.convert(10));
assertEquals("XI",Numeral.convert(11));
assertEquals("XL",Numeral.convert(40));
assertEquals("XLI",Numeral.convert(41));
assertEquals("L",Numeral.convert(50));
assertEquals("LI",Numeral.convert(51));
assertEquals("XC",Numeral.convert(90));
assertEquals("XCI",Numeral.convert(91));
assertEquals("C",Numeral.convert(100));
assertEquals("CI",Numeral.convert(101));
}
}
| 859 | 0.724098 | 0.691502 | 28 | 29.678572 | 17.521524 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.5 | false | false |
7
|
0db71c15771cde213c1ba46cdd1b7438fb459884
| 2,121,713,898,921 |
18bdae59a57cb878bdb4d41f0264c2c37d93b26d
|
/webiot2/AppMobile/Neuralgrid/Neuralgrid/app/src/main/java/com/example/mac/drawerdemo/Model/Dashboard/PieChartVO.java
|
dafc8a2be6235fcac4e905bc1743efbb8c7f0bb6
|
[] |
no_license
|
rahulp4/WebIoT
|
https://github.com/rahulp4/WebIoT
|
c001a058adb3b0413eaffa32ce3b81e786cd92f6
|
d19cf74b7ddb25ba9cf558639de043f8215a3de0
|
refs/heads/master
| 2018-02-15T08:32:56.519000 | 2018-02-13T16:44:35 | 2018-02-13T16:44:35 | 64,410,579 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.mac.drawerdemo.Model.Dashboard;
import java.io.Serializable;
/**
* Created by mac on 12/09/17.
*/
public class PieChartVO implements Serializable {
private String dataId;
private String dataIdLable;
private double dataIdValueDouble;
private int dataIdValueInt;
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getDataIdLable() {
return dataIdLable;
}
public void setDataIdLable(String dataIdLable) {
this.dataIdLable = dataIdLable;
}
public double getDataIdValueDouble() {
return dataIdValueDouble;
}
public void setDataIdValueDouble(double dataIdValueDouble) {
this.dataIdValueDouble = dataIdValueDouble;
}
public int getDataIdValueInt() {
return dataIdValueInt;
}
public void setDataIdValueInt(int dataIdValueInt) {
this.dataIdValueInt = dataIdValueInt;
}
@Override
public String toString() {
return "PieChartVO{" +
"dataId='" + dataId + '\'' +
", dataIdLable='" + dataIdLable + '\'' +
", dataIdValueDouble=" + dataIdValueDouble +
", dataIdValueInt=" + dataIdValueInt +
'}';
}
}
|
UTF-8
|
Java
| 1,332 |
java
|
PieChartVO.java
|
Java
|
[] | null |
[] |
package com.example.mac.drawerdemo.Model.Dashboard;
import java.io.Serializable;
/**
* Created by mac on 12/09/17.
*/
public class PieChartVO implements Serializable {
private String dataId;
private String dataIdLable;
private double dataIdValueDouble;
private int dataIdValueInt;
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getDataIdLable() {
return dataIdLable;
}
public void setDataIdLable(String dataIdLable) {
this.dataIdLable = dataIdLable;
}
public double getDataIdValueDouble() {
return dataIdValueDouble;
}
public void setDataIdValueDouble(double dataIdValueDouble) {
this.dataIdValueDouble = dataIdValueDouble;
}
public int getDataIdValueInt() {
return dataIdValueInt;
}
public void setDataIdValueInt(int dataIdValueInt) {
this.dataIdValueInt = dataIdValueInt;
}
@Override
public String toString() {
return "PieChartVO{" +
"dataId='" + dataId + '\'' +
", dataIdLable='" + dataIdLable + '\'' +
", dataIdValueDouble=" + dataIdValueDouble +
", dataIdValueInt=" + dataIdValueInt +
'}';
}
}
| 1,332 | 0.62012 | 0.615616 | 56 | 22.785715 | 20.21113 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false |
7
|
e2f313e96b54eeaf87ba3afa39713612eb7f25ed
| 31,018,253,857,971 |
fbd7687ba16fc88427f968881e028070b2a1bca1
|
/src/main/java/com/uhd/core/asset/report/ReportBuilder.java
|
7bd31fbdd4d4df0f2c4ceecb81460f90622e5fee
|
[] |
no_license
|
JSextonn/restaurant-management
|
https://github.com/JSextonn/restaurant-management
|
4f4e386de53d8335c715a2c162217e582e553726
|
9545082f3f9bfa68908432efde59343ef43c4b0c
|
refs/heads/master
| 2019-07-03T15:39:38.283000 | 2018-04-26T19:32:22 | 2018-04-26T19:32:22 | 123,010,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.uhd.core.asset.report;
public interface ReportBuilder<T> {
Report build(T entity);
}
|
UTF-8
|
Java
| 102 |
java
|
ReportBuilder.java
|
Java
|
[] | null |
[] |
package com.uhd.core.asset.report;
public interface ReportBuilder<T> {
Report build(T entity);
}
| 102 | 0.735294 | 0.735294 | 5 | 19.4 | 15.679286 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
7
|
391004d2444bbda599701e06f4fece05fc0dc252
| 31,018,253,854,866 |
5b30b28e6d1e534f74269dbcfd38031f0d90ed0b
|
/mobile/src/main/java/net/ddns/andrewnetwork/raspberrymonitor/Resource/Utils.java
|
b35a8e69066e623d155b0b5d428696ca6b0cba1c
|
[] |
no_license
|
TheSpartan94/RaspberryMonitor
|
https://github.com/TheSpartan94/RaspberryMonitor
|
32a74f4d0665bdbea4e99300c4fc67c245858460
|
c1649b5aee3cf49fa15d7695ee587d38b9a60377
|
refs/heads/master
| 2021-08-22T22:00:04.658000 | 2017-12-01T11:00:44 | 2017-12-01T11:00:44 | 112,729,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.ddns.andrewnetwork.raspberrymonitor.Resource;
import android.content.Context;
import android.database.Cursor;
import net.ddns.andrewnetwork.raspberrymonitor.Adapter.CredentialAdapter;
import net.ddns.andrewnetwork.raspberrymonitor.Class.Connection;
import net.ddns.andrewnetwork.raspberrymonitor.Class.Credential;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by andry on 24/11/2017.
*/
public abstract class Utils {
public static ArrayList<String> convertToListOfStrings(Cursor c,String column) {
ArrayList<String> mArrayList = new ArrayList<>();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
mArrayList.add(c.getString(c.getColumnIndex(column)));
}
return mArrayList;
}
public static ArrayList<String> convertToListOfStrings(Cursor c,int column) {
ArrayList<String> mArrayList = new ArrayList<>();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
mArrayList.add(c.getString(column));
}
return mArrayList;
}
public static ArrayList<Credential> convertToListOfCredential(Cursor c) {
ArrayList<Credential> mArrayList = new ArrayList<>();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
// The Cursor is now set to the right position
String name = c.getString(c.getColumnIndex("name"));
String username = c.getString(c.getColumnIndex("username"));
char[] password = c.getString(c.getColumnIndex("password")).toCharArray();
int id = c.getInt(c.getColumnIndex("_id"));
mArrayList.add(new Credential(name,username,password,id));
}
return mArrayList;
}
public static ArrayList<Connection> convertToListOfConnection(Cursor c, Context context) throws UnknownHostException {
ArrayList<Connection> mArrayList = new ArrayList<>();
CredentialAdapter cred = new CredentialAdapter(context);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
// The Cursor is now set to the right position
String name = c.getString(c.getColumnIndex("name"));
String address = c.getString(c.getColumnIndex("address"));
int port = c.getInt(c.getColumnIndex("port"));
int id = c.getInt(c.getColumnIndex("_id"));
Credential credential = cred.getCredentialFromList(c.getInt(c.getColumnIndex("credential")));
mArrayList.add(new Connection(address,name,port,id,credential));
}
return mArrayList;
}
public static ArrayList<ArrayList<String>> convertToBidemonsialListOfConnection(Cursor c, Context context) throws UnknownHostException {
ArrayList<ArrayList<String>> mArrayList = new ArrayList<>();
CredentialAdapter cred = new CredentialAdapter(context);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
ArrayList<String> connection = new ArrayList<>();
connection.add(c.getString(c.getColumnIndex("name")));
connection.add(c.getString(c.getColumnIndex("address")));
connection.add(c.getString(c.getColumnIndex("port")));
connection.add(cred.getCredentialFromList(c.getInt(c.getColumnIndex("credential"))).getName());
mArrayList.add(connection);
}
return mArrayList;
}
}
|
UTF-8
|
Java
| 3,400 |
java
|
Utils.java
|
Java
|
[
{
"context": "on;\nimport java.util.ArrayList;\n\n/**\n * Created by andry on 24/11/2017.\n */\n\npublic abstract class Utils {",
"end": 419,
"score": 0.9995395541191101,
"start": 414,
"tag": "USERNAME",
"value": "andry"
},
{
"context": " String username = c.getString(c.getColumnIndex(\"username\"));\n char[] password = c.getString(c.g",
"end": 1485,
"score": 0.764516294002533,
"start": 1477,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package net.ddns.andrewnetwork.raspberrymonitor.Resource;
import android.content.Context;
import android.database.Cursor;
import net.ddns.andrewnetwork.raspberrymonitor.Adapter.CredentialAdapter;
import net.ddns.andrewnetwork.raspberrymonitor.Class.Connection;
import net.ddns.andrewnetwork.raspberrymonitor.Class.Credential;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by andry on 24/11/2017.
*/
public abstract class Utils {
public static ArrayList<String> convertToListOfStrings(Cursor c,String column) {
ArrayList<String> mArrayList = new ArrayList<>();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
mArrayList.add(c.getString(c.getColumnIndex(column)));
}
return mArrayList;
}
public static ArrayList<String> convertToListOfStrings(Cursor c,int column) {
ArrayList<String> mArrayList = new ArrayList<>();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
mArrayList.add(c.getString(column));
}
return mArrayList;
}
public static ArrayList<Credential> convertToListOfCredential(Cursor c) {
ArrayList<Credential> mArrayList = new ArrayList<>();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
// The Cursor is now set to the right position
String name = c.getString(c.getColumnIndex("name"));
String username = c.getString(c.getColumnIndex("username"));
char[] password = c.getString(c.getColumnIndex("password")).toCharArray();
int id = c.getInt(c.getColumnIndex("_id"));
mArrayList.add(new Credential(name,username,password,id));
}
return mArrayList;
}
public static ArrayList<Connection> convertToListOfConnection(Cursor c, Context context) throws UnknownHostException {
ArrayList<Connection> mArrayList = new ArrayList<>();
CredentialAdapter cred = new CredentialAdapter(context);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
// The Cursor is now set to the right position
String name = c.getString(c.getColumnIndex("name"));
String address = c.getString(c.getColumnIndex("address"));
int port = c.getInt(c.getColumnIndex("port"));
int id = c.getInt(c.getColumnIndex("_id"));
Credential credential = cred.getCredentialFromList(c.getInt(c.getColumnIndex("credential")));
mArrayList.add(new Connection(address,name,port,id,credential));
}
return mArrayList;
}
public static ArrayList<ArrayList<String>> convertToBidemonsialListOfConnection(Cursor c, Context context) throws UnknownHostException {
ArrayList<ArrayList<String>> mArrayList = new ArrayList<>();
CredentialAdapter cred = new CredentialAdapter(context);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
ArrayList<String> connection = new ArrayList<>();
connection.add(c.getString(c.getColumnIndex("name")));
connection.add(c.getString(c.getColumnIndex("address")));
connection.add(c.getString(c.getColumnIndex("port")));
connection.add(cred.getCredentialFromList(c.getInt(c.getColumnIndex("credential"))).getName());
mArrayList.add(connection);
}
return mArrayList;
}
}
| 3,400 | 0.670294 | 0.667941 | 76 | 43.736843 | 33.06229 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false |
7
|
dad125a4f9a32a2745057c52e3c4ae7618a5e539
| 515,396,096,401 |
3f0ebecd4946e93b97b82f63f8c147b64a726780
|
/Lab/MathServer.java
|
ede8a1f2b6bfb73452a51f2b955853d8cdb60a01
|
[] |
no_license
|
yichenghuang980/OO_Programming_Java
|
https://github.com/yichenghuang980/OO_Programming_Java
|
c912a4cfda0d326435a3c0ee6457d36e72331cc2
|
18d7be840ae72124310d260f66e6bfd9547710fd
|
refs/heads/master
| 2023-01-07T13:36:44.348000 | 2020-11-20T02:37:51 | 2020-11-20T02:37:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lab;
import java.io.*;
import java.net.*;
public class MathServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(4242);
System.out.println("Waiting for the client...");
Socket socket = serverSocket.accept();
System.out.println("Client connected!");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.flush();
String first = reader.readLine();
String second = reader.readLine();
String mode = reader.readLine();
String response;
switch (mode) {
case "1":
response = Integer.toString(Integer.parseInt(first) + Integer.parseInt(second));
break;
case "2":
response = Integer.toString(Integer.parseInt(first) - Integer.parseInt(second));
break;
case "3":
response = Integer.toString(Integer.parseInt(first) * Integer.parseInt(second));
break;
default:
response = Integer.toString(Integer.parseInt(first) / Integer.parseInt(second));
break;
}
writer.write(response);
writer.newLine();
writer.flush();
writer.close();
reader.close();
}
}
|
UTF-8
|
Java
| 1,472 |
java
|
MathServer.java
|
Java
|
[] | null |
[] |
package lab;
import java.io.*;
import java.net.*;
public class MathServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(4242);
System.out.println("Waiting for the client...");
Socket socket = serverSocket.accept();
System.out.println("Client connected!");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.flush();
String first = reader.readLine();
String second = reader.readLine();
String mode = reader.readLine();
String response;
switch (mode) {
case "1":
response = Integer.toString(Integer.parseInt(first) + Integer.parseInt(second));
break;
case "2":
response = Integer.toString(Integer.parseInt(first) - Integer.parseInt(second));
break;
case "3":
response = Integer.toString(Integer.parseInt(first) * Integer.parseInt(second));
break;
default:
response = Integer.toString(Integer.parseInt(first) / Integer.parseInt(second));
break;
}
writer.write(response);
writer.newLine();
writer.flush();
writer.close();
reader.close();
}
}
| 1,472 | 0.590353 | 0.585598 | 42 | 34.047619 | 30.053883 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false |
7
|
dda80fdc4aa1e1e4a240f6a649281925bce744b4
| 28,441,273,459,675 |
9f4c3ee2f80a5dbe91fc0668c7aa97257d86a66e
|
/app/src/main/java/com/mycompany/loginapp/login/notUsed/ParseFbSignIn.java
|
d1fd8faa9d95a9b158b8ff5d710f8fe148f237cb
|
[] |
no_license
|
AlexanderRiishoej/AndroidSocialApp
|
https://github.com/AlexanderRiishoej/AndroidSocialApp
|
c1db791d9f3c82bfd7141d1441faaa4f1c73f7e1
|
9bcb147d6662edc340d1a58b2314c77ce90916e8
|
refs/heads/master
| 2021-01-10T22:06:04.174000 | 2015-10-03T18:58:01 | 2015-10-03T18:58:01 | 35,973,182 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mycompany.loginapp.login.notUsed;
/**
* Created by Alexander on 11-07-2015.
* Helper interface to notify when to sign in with parse when using Facebook as sign-in
*/
public interface ParseFbSignIn {
void signIn();
}
|
UTF-8
|
Java
| 236 |
java
|
ParseFbSignIn.java
|
Java
|
[
{
"context": "company.loginapp.login.notUsed;\n\n/**\n * Created by Alexander on 11-07-2015.\n * Helper interface to notify when",
"end": 74,
"score": 0.9995032548904419,
"start": 65,
"tag": "NAME",
"value": "Alexander"
}
] | null |
[] |
package com.mycompany.loginapp.login.notUsed;
/**
* Created by Alexander on 11-07-2015.
* Helper interface to notify when to sign in with parse when using Facebook as sign-in
*/
public interface ParseFbSignIn {
void signIn();
}
| 236 | 0.737288 | 0.70339 | 9 | 25.222221 | 27.242849 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false |
7
|
fbe58da67e37da639b43028b63b97a0a17184e86
| 26,190,710,629,917 |
4a1c5f0fe3310f00062ce51c5a840ce58a9e85d7
|
/framework_src/ejbModule/com/aiait/framework/frontal/xml/model/Screen.java
|
8404578ed2302bba1e5b539b296ce05aca6b27e2
|
[] |
no_license
|
yimng/ecompazz
|
https://github.com/yimng/ecompazz
|
ccb32d9826f8e28db871df08fe6393a274877d1d
|
a44c988e180ac794bfcb10d4c99475316bd47316
|
refs/heads/master
| 2019-06-28T18:05:34.633000 | 2015-02-10T01:31:43 | 2015-02-10T01:31:43 | 30,568,784 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.aiait.framework.frontal.xml.model;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Element;
import com.aiait.framework.util.Utilities;
public class Screen implements Serializable{
private String templatePath;
private String name;
private Map items;
public Screen(String templatePath, Element element) {
this.templatePath = templatePath;
this.setName(Utilities.nullToString(element.getAttribute("name")));
items = new HashMap(4);
}
public void addItem(ScreenItem item){
items.put(item.getName(), item);
}
public ScreenItem getScreenItem(String itemName){
return (ScreenItem)items.get(itemName);
}
/**
* @return
*/
public String getName() {
return name;
}
/**
* @return
*/
public String getTemplatePath() {
return templatePath;
}
/**
* @param string
*/
public void setName(String string) {
name = string;
}
}
|
UTF-8
|
Java
| 938 |
java
|
Screen.java
|
Java
|
[] | null |
[] |
package com.aiait.framework.frontal.xml.model;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Element;
import com.aiait.framework.util.Utilities;
public class Screen implements Serializable{
private String templatePath;
private String name;
private Map items;
public Screen(String templatePath, Element element) {
this.templatePath = templatePath;
this.setName(Utilities.nullToString(element.getAttribute("name")));
items = new HashMap(4);
}
public void addItem(ScreenItem item){
items.put(item.getName(), item);
}
public ScreenItem getScreenItem(String itemName){
return (ScreenItem)items.get(itemName);
}
/**
* @return
*/
public String getName() {
return name;
}
/**
* @return
*/
public String getTemplatePath() {
return templatePath;
}
/**
* @param string
*/
public void setName(String string) {
name = string;
}
}
| 938 | 0.706823 | 0.704691 | 57 | 15.456141 | 17.535997 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.175439 | false | false |
7
|
005f541a103714fed9e8d7374aa19fe485621d19
| 11,132,555,293,296 |
c7fb502da59f186496f404ba199471113a34bc2b
|
/lng-admin/lng-admin-api/src/main/java/com/lng168/admin/api/PurchOfferService.java
|
ace963c4a33d849737dc88ff9e79a27cc05bb9cc
|
[] |
no_license
|
shanghai-yiyun/lng168-system
|
https://github.com/shanghai-yiyun/lng168-system
|
48318c453e25111254f5f1ebcfb2652a5e63dc67
|
bc73bf543dac6e54a87ad4a0493f65b7aebb42f1
|
refs/heads/master
| 2020-06-15T04:58:42.935000 | 2020-02-28T08:03:49 | 2020-02-28T08:03:49 | 195,208,360 | 0 | 0 | null | false | 2020-07-01T23:42:56 | 2019-07-04T09:10:44 | 2020-02-28T08:06:39 | 2020-07-01T23:42:54 | 6,268 | 0 | 0 | 3 |
Java
| false | false |
package com.lng168.admin.api;
import com.baomidou.mybatisplus.service.IService;
import com.lng168.admin.api.model.PurchOffer;
import java.util.List;
import java.util.Map;
/**
* <p>
* 采购报价表 服务类
* </p>
*
* @author lng168
* @since 2019-07-23
*/
public interface PurchOfferService extends IService<PurchOffer> {
/**
* 报价
* @param dataMap
*/
public void insert(Map<Object,Object> dataMap) throws Exception;
public Integer selectCount(Map<Object, Object> mp);
public List<PurchOffer> selectList(Map<Object, Object> mp);
}
|
UTF-8
|
Java
| 582 |
java
|
PurchOfferService.java
|
Java
|
[
{
"context": "ap;\n\n/**\n * <p>\n * 采购报价表 服务类\n * </p>\n *\n * @author lng168\n * @since 2019-07-23\n */\npublic interface PurchOf",
"end": 228,
"score": 0.9994291067123413,
"start": 222,
"tag": "USERNAME",
"value": "lng168"
}
] | null |
[] |
package com.lng168.admin.api;
import com.baomidou.mybatisplus.service.IService;
import com.lng168.admin.api.model.PurchOffer;
import java.util.List;
import java.util.Map;
/**
* <p>
* 采购报价表 服务类
* </p>
*
* @author lng168
* @since 2019-07-23
*/
public interface PurchOfferService extends IService<PurchOffer> {
/**
* 报价
* @param dataMap
*/
public void insert(Map<Object,Object> dataMap) throws Exception;
public Integer selectCount(Map<Object, Object> mp);
public List<PurchOffer> selectList(Map<Object, Object> mp);
}
| 582 | 0.688612 | 0.658363 | 30 | 17.733334 | 21.726994 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.366667 | false | false |
7
|
e93669db021b1f5618a56d9b481bb76b33cf8ce5
| 30,889,404,844,849 |
4b4dc14e604cc1b1f2d3227efcf8e39a3a3ee774
|
/app/src/main/java/com/hira_software/location_by_yohannes/repository/LocationData.java
|
b779f6cd981c3eea38f8c9a73e63a70a3be22cfb
|
[] |
no_license
|
jonmersha/locationApp
|
https://github.com/jonmersha/locationApp
|
78633c85693f9df8e8a2b4b0cecad0026592cbeb
|
ce66e5740ebd5ff260cf26b32d6e52721c8be612
|
refs/heads/master
| 2022-12-06T20:56:14 | 2020-09-10T01:28:09 | 2020-09-10T01:28:09 | 294,009,014 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hira_software.location_by_yohannes.repository;
public class LocationData {
public static LocationModel locationModel;
}
|
UTF-8
|
Java
| 137 |
java
|
LocationData.java
|
Java
|
[] | null |
[] |
package com.hira_software.location_by_yohannes.repository;
public class LocationData {
public static LocationModel locationModel;
}
| 137 | 0.810219 | 0.810219 | 5 | 26.4 | 23.346092 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
7
|
d55341bc4fd739e378d81e18d8f3cfb487ee0c0b
| 30,889,404,844,456 |
eabfcfff4ef2b4c12176693157453ab1fe18fd67
|
/client/src/main/java/com/netty/chat/base/RequestInfo.java
|
2b7776fe5777fce17d50ecfdea41f7930391c779
|
[] |
no_license
|
hgd613/netty-demo
|
https://github.com/hgd613/netty-demo
|
444103d06307b7c4cc4044df0ace99e79d1f9c4b
|
155687cc51efe7612241114083cfe4e4f03c1619
|
refs/heads/master
| 2020-04-24T17:54:42.581000 | 2019-02-23T02:50:21 | 2019-02-23T02:50:21 | 172,163,045 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.netty.chat.base;
import java.io.Serializable;
/**
* Created by Huo on 2019/1/14.
*/
public class RequestInfo implements Serializable{
private static final long serialVersionUID = 4110820425939875033L;
private byte type;
private String info;
public RequestInfo() {
}
public RequestInfo(byte type, String info) {
this.type = type;
this.info = info;
}
public byte getType() {
return type;
}
public void setType(byte type) {
this.type = type;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
|
UTF-8
|
Java
| 671 |
java
|
RequestInfo.java
|
Java
|
[
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by Huo on 2019/1/14.\n */\npublic class RequestInfo implem",
"end": 81,
"score": 0.8900253772735596,
"start": 78,
"tag": "USERNAME",
"value": "Huo"
}
] | null |
[] |
package com.netty.chat.base;
import java.io.Serializable;
/**
* Created by Huo on 2019/1/14.
*/
public class RequestInfo implements Serializable{
private static final long serialVersionUID = 4110820425939875033L;
private byte type;
private String info;
public RequestInfo() {
}
public RequestInfo(byte type, String info) {
this.type = type;
this.info = info;
}
public byte getType() {
return type;
}
public void setType(byte type) {
this.type = type;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
| 671 | 0.611028 | 0.57228 | 38 | 16.657894 | 17.094591 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false |
7
|
75e431e5b38a4246e1643c2949d7b53d4ed4ce50
| 26,800,595,989,277 |
108d0dc6a3618b03fd9642b6a0395f99fe1c643e
|
/springboot-optimistic-handler/src/main/java/com/raven/springboot/config/interceptor/AbstractOptimisticHandlerAnnotationInterceptor.java
|
27813e97094f9cf8d04328befb06f1963fb7ea8a
|
[] |
no_license
|
RavenHuo/springboot-study-lab
|
https://github.com/RavenHuo/springboot-study-lab
|
9342fa53c507b9ad213f83c0e18c66a95a5a353c
|
c0d055fe61da4b6763e920cfc8df586ae6cf956f
|
refs/heads/master
| 2023-01-31T20:57:57.853000 | 2020-12-15T15:16:17 | 2020-12-15T15:16:17 | 298,209,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.raven.springboot.config.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.AopUtils;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.ClassUtils;
import javax.persistence.OptimisticLockException;
import java.lang.reflect.Method;
/**
* @description:
* @author: huorw
* @create: 2020-12-08 23:37
*/
@Slf4j
public abstract class AbstractOptimisticHandlerAnnotationInterceptor implements MethodInterceptor {
/**
* 代理方法
* @param invocation
* @return
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
try {
log.info("optimisticHandler invoke ------------ method={}", invocation.getMethod());
invocation.proceed();
}
// 捕获乐观锁异常
catch (OptimisticLockException ex) {
// 获取代理类
Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
// 获取代理方法
Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
// 获取代理方法的实现方法
final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
optimisticHandler(userDeclaredMethod);
}
return null;
}
/**
* 此处实现处理 乐观锁方法
* @param userDeclaredMethod
*/
protected abstract void optimisticHandler(Method userDeclaredMethod) throws Throwable;
}
|
UTF-8
|
Java
| 1,716 |
java
|
AbstractOptimisticHandlerAnnotationInterceptor.java
|
Java
|
[
{
"context": ".reflect.Method;\n\n/**\n * @description:\n * @author: huorw\n * @create: 2020-12-08 23:37\n */\n@Slf4j\npublic ab",
"end": 457,
"score": 0.9996469020843506,
"start": 452,
"tag": "USERNAME",
"value": "huorw"
}
] | null |
[] |
package com.raven.springboot.config.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.AopUtils;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.ClassUtils;
import javax.persistence.OptimisticLockException;
import java.lang.reflect.Method;
/**
* @description:
* @author: huorw
* @create: 2020-12-08 23:37
*/
@Slf4j
public abstract class AbstractOptimisticHandlerAnnotationInterceptor implements MethodInterceptor {
/**
* 代理方法
* @param invocation
* @return
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
try {
log.info("optimisticHandler invoke ------------ method={}", invocation.getMethod());
invocation.proceed();
}
// 捕获乐观锁异常
catch (OptimisticLockException ex) {
// 获取代理类
Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
// 获取代理方法
Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
// 获取代理方法的实现方法
final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
optimisticHandler(userDeclaredMethod);
}
return null;
}
/**
* 此处实现处理 乐观锁方法
* @param userDeclaredMethod
*/
protected abstract void optimisticHandler(Method userDeclaredMethod) throws Throwable;
}
| 1,716 | 0.688575 | 0.679361 | 51 | 30.921568 | 31.633219 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.372549 | false | false |
7
|
d2083573fdca876fdf54834c7e433d56e606c67e
| 17,386,027,641,430 |
a48954554298bd36f287f74ff02e57bf37af488b
|
/arc/src/main/java/com/xiansenliu/arc/lo/LOContract.java
|
9ddc6c9764972d60408cccb895b7308c0fa7ab90
|
[
"Apache-2.0"
] |
permissive
|
aikudeweixiao/Android_Demos
|
https://github.com/aikudeweixiao/Android_Demos
|
18ec9127972319f0837f2cb5a32d35872c035207
|
7dad68a388008cb3e1800532ac23b2dc9d88955b
|
refs/heads/master
| 2020-03-23T20:24:53.186000 | 2018-04-07T13:47:59 | 2018-04-07T13:47:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.xiansenliu.arc.lo;
import com.xiansenliu.arc.mvp.BasePresenter;
import com.xiansenliu.arc.mvp.BaseView;
/**
* Author xinliu
* Date 12/22/17
* Time 8:52 PM
* Email xinliugm@gmail.com
*/
public interface LOContract {
abstract class BaseLifecyclePresenter extends BasePresenter<LifecycleView> {
abstract void getMsg();
}
interface LifecycleView extends BaseView {
void showMsg(String msg);
}
}
|
UTF-8
|
Java
| 474 |
java
|
LOContract.java
|
Java
|
[
{
"context": ".xiansenliu.arc.mvp.BaseView;\n\n/**\n * Author xinliu\n * Date 12/22/17\n * Time 8:52 PM\n",
"end": 144,
"score": 0.9996802806854248,
"start": 138,
"tag": "USERNAME",
"value": "xinliu"
},
{
"context": " 12/22/17\n * Time 8:52 PM\n * Email xinliugm@gmail.com\n */\n\npublic interface LOContract {\n\n abstract ",
"end": 228,
"score": 0.9999319911003113,
"start": 210,
"tag": "EMAIL",
"value": "xinliugm@gmail.com"
}
] | null |
[] |
package com.xiansenliu.arc.lo;
import com.xiansenliu.arc.mvp.BasePresenter;
import com.xiansenliu.arc.mvp.BaseView;
/**
* Author xinliu
* Date 12/22/17
* Time 8:52 PM
* Email <EMAIL>
*/
public interface LOContract {
abstract class BaseLifecyclePresenter extends BasePresenter<LifecycleView> {
abstract void getMsg();
}
interface LifecycleView extends BaseView {
void showMsg(String msg);
}
}
| 463 | 0.666667 | 0.647679 | 22 | 20.545454 | 20.550884 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false |
7
|
0b496b20395fbaf000c72479e1f3af8da5b4fbdc
| 21,672,404,977,260 |
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/21/21_e5d96001c75a9dc610f8bb1cb00713be1e6964d0/VersionedObject/21_e5d96001c75a9dc610f8bb1cb00713be1e6964d0_VersionedObject_s.java
|
749924ffd0ca96891b7970980a54308095041818
|
[] |
no_license
|
zhongxingyu/Seer
|
https://github.com/zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false |
/*
* component: "openEHR Reference Implementation"
* description: "Class VersionedObject"
* keywords: "common"
*
* author: "Yin Su Lim <y.lim@chime.ucl.ac.uk>"
* support: "CHIME, UCL"
* copyright: "Copyright (c) 2006 UCL, UK"
* license: "See notice at bottom of class"
*
* file: "$URL: http://svn.openehr.org/ref_impl_java/TRUNK/libraries/src/java/org/openehr/rm/common/changecontrol/VersionedObject.java $"
* revision: "$LastChangedRevision: 53 $"
* last_change: "$LastChangedDate: 2006-08-11 13:20:08 +0100 (Fri, 11 Aug 2006) $"
*/
package org.openehr.rm.common.changecontrol;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.openehr.rm.RMObject;
import org.openehr.rm.common.generic.Attestation;
import org.openehr.rm.common.generic.AuditDetails;
import org.openehr.rm.common.generic.RevisionHistory;
import org.openehr.rm.common.generic.RevisionHistoryItem;
import org.openehr.rm.datatypes.quantity.datetime.DvDateTime;
import org.openehr.rm.datatypes.text.DvCodedText;
import org.openehr.rm.support.identification.HierarchicalObjectID;
import org.openehr.rm.support.identification.ObjectID;
import org.openehr.rm.support.identification.ObjectReference;
import org.openehr.rm.support.identification.ObjectVersionID;
import org.openehr.rm.support.identification.VersionTreeID;
import org.openehr.rm.support.terminology.TerminologyService;
/**
* @author yinsulim
*
*/
/**
* @author yinsulim
*
* @param <T>
*/
public class VersionedObject<T> extends RMObject {
/**
* Constructs a VersionObject with first originalVersion
*/
public VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated, ObjectVersionID versionID, T data,
DvCodedText lifecycleState, AuditDetails commitAudit,
ObjectReference contribution, String signature,
TerminologyService terminologyService) {
this(uid, ownerID, timeCreated);
commitOriginalVersion(versionID, null, data, commitAudit, contribution,
lifecycleState, signature, terminologyService);
}
/**
* Constructs a VersionObject with first importedVersion
*/
public VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated, OriginalVersion<T> item, AuditDetails commitAudit,
ObjectReference contribution, String signature) {
this(uid, ownerID, timeCreated);
commitImportedVersion(item, commitAudit, contribution, signature);
}
/**
* Constructs a VersionObject with first merged Version
*/
public VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated, ObjectVersionID versionID,
ObjectVersionID precedingVersionID, T data, DvCodedText lifecycleState,
AuditDetails commitAudit, ObjectReference contribution,
Set<ObjectVersionID> otherInputVersionUids, String signature,
TerminologyService terminologyService) {
this(uid, ownerID, timeCreated);
commitOriginalMergedVersion(versionID, precedingVersionID, data, lifecycleState,
commitAudit, contribution, otherInputVersionUids, signature,
terminologyService);
}
private VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated) {
if (uid == null) {
throw new IllegalArgumentException("null uid");
}
if (ownerID == null) {
throw new IllegalArgumentException("null ownerID");
}
if (timeCreated == null) {
throw new IllegalArgumentException("null timeCreated");
}
this.uid = uid;
this.ownerID = ownerID;
this.timeCreated = timeCreated;
timeVersionMap = new TreeMap<DvDateTime, Version<T>>();
idVersionMap = new HashMap<ObjectVersionID, Version<T>>();
}
/**
* Add a new ImportedVersion
*
* @param commitAudit
* @param contribution
* @param item
*/
public synchronized void commitImportedVersion(OriginalVersion<T> item, AuditDetails commitAudit,
ObjectReference contribution, String signature) {
commitVersionCheck(item.getUid(), item.getPrecedingVersionID());
Version<T> version = new ImportedVersion<T>(item, commitAudit, contribution, signature);
addVersion(version);
}
private synchronized void commitVersionCheck(ObjectVersionID vUid, ObjectVersionID precedingVUid) {
if (versionCount() > 0 && !hasVersionID(precedingVUid)) {
throw new IllegalArgumentException("precedingVersionID not found");
}
if(!vUid.objectID().equals(this.uid.root())) {
throw new IllegalArgumentException("ownerID different from versionedObject");
}
}
private synchronized void addVersion(Version<T> version) {
if (!version.getUid().versionTreeID().isBranch()) {
int trunkNo = Integer.parseInt(version.getUid().versionTreeID().trunkVersion());
if (trunkNo != trunkCounter + 1) {
throw new IllegalArgumentException("invlalid trunk no in uid");
} else {
trunkCounter++;
latestTrunkUid = version.getUid();
}
}
timeVersionMap.put(version.getCommitAudit().getTimeCommitted(), version);
idVersionMap.put(version.getUid(), version);
}
/**
* Add a new original Version
* @param versionID
* @param precedingVersionID
* @param data
* @param commitAudit
* @param contribution
* @param lifecycleState
* @param terminologyService
*/
public synchronized void commitOriginalVersion(ObjectVersionID versionID,
ObjectVersionID precedingVersionID, T data, AuditDetails commitAudit,
ObjectReference contribution, DvCodedText lifecycleState, String signature,
TerminologyService terminologyService) {
commitVersionCheck(versionID, precedingVersionID);
Version<T> version = new OriginalVersion<T>(versionID, precedingVersionID,
data, lifecycleState, commitAudit, contribution, signature, null, null,
false, terminologyService);
addVersion(version);
}
/**
* Add a new original MergedVersion
* @param versionID
* @param precedingVersionID
* @param data
* @param commitAudit
* @param contribution
* @param lifecycleState
* @param terminologyService
*/
public synchronized void commitOriginalMergedVersion(ObjectVersionID versionID,
ObjectVersionID precedingVersionID, T data, DvCodedText lifecycleState,
AuditDetails commitAudit, ObjectReference contribution,
Set<ObjectVersionID> otherInputVersionUids, String signature,
TerminologyService terminologyService) {
//if (versionCount() > 0 && !hasVersionID(precedingVersionID)) {
// throw new IllegalArgumentException("precedingVersionID not found");
//}
commitVersionCheck(versionID, precedingVersionID);
Version<T> version = new OriginalVersion<T>(versionID, precedingVersionID,
data, lifecycleState, commitAudit, contribution, signature, otherInputVersionUids,
null, true, terminologyService);
addVersion(version);
}
/**
* Create a next logical uid for a Version based on precedingVersionID
*
* @param precedingVersionID
* @param systemID
* @return
*/
//TODO: delete this
/* private ObjectVersionID nextUid(ObjectVersionID precedingVersionID, String systemID) {
VersionTreeID vTreeId = null;
HierarchicalObjectID creatingSystemID = null;
if (precedingVersionID != null) {
vTreeId = precedingVersionID.versionTreeID().next();
creatingSystemID = precedingVersionID.creatingSystemID();
} else {
vTreeId = new VersionTreeID(Integer.toString(1));
creatingSystemID = new HierarchicalObjectID(systemID);
}
return new ObjectVersionID(uid.root(), creatingSystemID, vTreeId);
}*/
/**
* Unique identifier of this version repository.
*
* @return UID
*/
public HierarchicalObjectID getUid() {
return uid;
}
/**
* Reference to object to which this versioned repository belongs,
* eg the id of the containing EHR.
*
* @return OwnerID
*/
public ObjectReference getOwnerID() {
return ownerID;
}
/**
* Time of initial creation of this versioned object.
*
* @return time of creation
*/
public DvDateTime getTimeCreated() {
return timeCreated;
}
/**
* Return a list of all versions in this object.
*
* @return all versions
*/
public synchronized List<Version<T>> allVersions() {
// todo: fix the order of this list
return new ArrayList<Version<T>>(idVersionMap.values());
}
/**
* Return a list of ids of all versions in this object.
*
* @return List<String>
*/
public synchronized List<ObjectVersionID> allVersionIDs() {
// todo: fix the order of list
return new ArrayList<ObjectVersionID>(idVersionMap.keySet());
}
/**
* Return the total number of versions in this object
*
* @return version count
*/
public synchronized int versionCount() {
return idVersionMap.size();
}
/**
* True if a version with given id exists.
*
* @param id
* @return true if has
* @throws IllegalArgumentException
*/
public synchronized boolean hasVersionID(ObjectVersionID id) {
if (id == null) {
throw new IllegalArgumentException("null id");
}
return idVersionMap.containsKey(id);
}
/**
* True if a version for given time exists.
*
* @param time
* @return true if has version
* @throws IllegalArgumentException if time null
*/
public synchronized boolean hasVersionAtTime(DvDateTime time) {
if (time == null) {
throw new IllegalArgumentException("null time");
}
return timeVersionMap.containsKey(time);
}
/**
* True if version with an id is an OriginalVersion
*
* @param uid
*/
public boolean isOriginalVersion(ObjectVersionID uid) {
if (!idVersionMap.containsKey(uid)) {
throw new IllegalArgumentException("versionID not found");
}
Version<T> version = idVersionMap.get(uid);
return version instanceof OriginalVersion;
}
/**
* Return the version with given id
*
* @param id
* @return null if not found
* @throws IllegalArgumentException if id null
*/
public synchronized Version<T> versionWithID(ObjectVersionID id) {
if (id == null) {
throw new IllegalArgumentException("null id");
}
return idVersionMap.get(id);
}
/**
* Return the version for given time
*
* @param time
* @return null if not found
* @throws IllegalArgumentException if time null
*/
public synchronized Version<T> versionAtTime(DvDateTime time) {
if (time == null) {
throw new IllegalArgumentException("null time");
}
return timeVersionMap.get(time);
}
/**
* Return the latest version.
*
* @return lastest version
*/
public synchronized Version<T> latestVersion() {
return (Version<T>) timeVersionMap.get(timeVersionMap.lastKey());
}
/**
* Return the most recetly added trunk version
*
*/
public synchronized Version<T> latestTrunkVersion() {
return (Version<T>) idVersionMap.get(latestTrunkUid);
}
/**
* Return the lifecycle state from the latest trunk version.
*
*/
public DvCodedText latestTrunkLifeCycleSate() {
Version<T> trunk = latestTrunkVersion();
return latestTrunkVersion().getLifeCycleState();
}
/**
* History of all audits and attestations in this versioned repository
*
* @return revisionHistory
*/
public RevisionHistory revisionHistory() {
ArrayList<Version<T>> versions = new ArrayList<Version<T>> (timeVersionMap.values());
ArrayList<RevisionHistoryItem> revHistoryItems = new ArrayList<RevisionHistoryItem>();
for(Version<T> version : versions) {
ArrayList<AuditDetails> audits = new ArrayList<AuditDetails>();
audits.add(version.getCommitAudit());
if (version instanceof OriginalVersion) {
OriginalVersion<T> orgVersion = (OriginalVersion<T>) version;
audits.addAll(orgVersion.getAttestations());
}
revHistoryItems.add(new RevisionHistoryItem(audits, version.getUid()));
}
return new RevisionHistory(revHistoryItems);
}
/**
* Add a new attestation to the specified version. Attestations can only
* be added to OriginalVersion
*
* @param attestation
* @param versionID
*/
public synchronized void commitAttestation(Attestation attestation,
ObjectVersionID versionID) {
if (attestation == null) {
throw new IllegalArgumentException("null attestation");
}
if (isOriginalVersion(versionID)) {
OriginalVersion<T> oVersion = (OriginalVersion<T>) idVersionMap.get(versionID);
oVersion.getAttestations().add(attestation);
} else {
throw new IllegalArgumentException("attestatios cannot be added to importedVersion");
}
}
//POJO start
protected VersionedObject() {
}
private Long id;
protected Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
void setUid(HierarchicalObjectID uid) {
this.uid = uid;
}
void setOwnerID(ObjectReference ownerID) {
this.ownerID = ownerID;
}
void setTimeCreated(DvDateTime timeCreated) {
this.timeCreated = timeCreated;
}
// in order to skip map timeVersionMap to table
void setVersions(Set<Version<T>> versions) {
idVersionMap = new HashMap<ObjectVersionID, Version<T>>();
timeVersionMap = new TreeMap<DvDateTime, Version<T>>();
for(Version<T> version : versions) {
addVersion(version);
}
}
// required to map bidirectional one-to-many relationship
Set<Version<T>> getVersions() {
return new HashSet<Version<T>>(timeVersionMap.values());
}
/**
* version id for the version before the first version
*/
//public static final String NONE = "0";
//public static final String FIRST = "1";
/* fields */
private HierarchicalObjectID uid;
private ObjectReference ownerID;
private DvDateTime timeCreated;
private SortedMap<DvDateTime, Version<T>> timeVersionMap;
//change to hashmap because ObjectVersionID doesn't implement Comparable
private HashMap<ObjectVersionID, Version<T>> idVersionMap;
private int trunkCounter;
private ObjectVersionID latestTrunkUid;
}
/*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an 'AS IS' basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is VersionedObject.java
*
* The Initial Developer of the Original Code is Yin Su Lim.
* Portions created by the Initial Developer are Copyright (C) 2003-2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Software distributed under the License is distributed on an 'AS IS' basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* ***** END LICENSE BLOCK *****
*/
|
UTF-8
|
Java
| 17,426 |
java
|
21_e5d96001c75a9dc610f8bb1cb00713be1e6964d0_VersionedObject_s.java
|
Java
|
[
{
"context": "\"\n * keywords: \"common\"\n *\n * author: \"Yin Su Lim <y.lim@chime.ucl.ac.uk>\"\n * support: \"CHIME,",
"end": 155,
"score": 0.9996730089187622,
"start": 145,
"tag": "NAME",
"value": "Yin Su Lim"
},
{
"context": "ds: \"common\"\n *\n * author: \"Yin Su Lim <y.lim@chime.ucl.ac.uk>\"\n * support: \"CHIME, UCL\"\n * copyright: ",
"end": 178,
"score": 0.9999331831932068,
"start": 157,
"tag": "EMAIL",
"value": "y.lim@chime.ucl.ac.uk"
},
{
"context": "terminology.TerminologyService;\n \n /**\n * @author yinsulim\n *\n */\n /**\n * @author yinsulim\n *\n * @param",
"end": 1592,
"score": 0.998971164226532,
"start": 1584,
"tag": "USERNAME",
"value": "yinsulim"
},
{
"context": "/**\n * @author yinsulim\n *\n */\n /**\n * @author yinsulim\n *\n * @param <T>\n */\n public class VersionedOb",
"end": 1627,
"score": 0.9984092712402344,
"start": 1619,
"tag": "USERNAME",
"value": "yinsulim"
},
{
"context": " * The Initial Developer of the Original Code is Yin Su Lim.\n * Portions created by the Initial Developer a",
"end": 16985,
"score": 0.99969881772995,
"start": 16975,
"tag": "NAME",
"value": "Yin Su Lim"
}
] | null |
[] |
/*
* component: "openEHR Reference Implementation"
* description: "Class VersionedObject"
* keywords: "common"
*
* author: "<NAME> <<EMAIL>>"
* support: "CHIME, UCL"
* copyright: "Copyright (c) 2006 UCL, UK"
* license: "See notice at bottom of class"
*
* file: "$URL: http://svn.openehr.org/ref_impl_java/TRUNK/libraries/src/java/org/openehr/rm/common/changecontrol/VersionedObject.java $"
* revision: "$LastChangedRevision: 53 $"
* last_change: "$LastChangedDate: 2006-08-11 13:20:08 +0100 (Fri, 11 Aug 2006) $"
*/
package org.openehr.rm.common.changecontrol;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.openehr.rm.RMObject;
import org.openehr.rm.common.generic.Attestation;
import org.openehr.rm.common.generic.AuditDetails;
import org.openehr.rm.common.generic.RevisionHistory;
import org.openehr.rm.common.generic.RevisionHistoryItem;
import org.openehr.rm.datatypes.quantity.datetime.DvDateTime;
import org.openehr.rm.datatypes.text.DvCodedText;
import org.openehr.rm.support.identification.HierarchicalObjectID;
import org.openehr.rm.support.identification.ObjectID;
import org.openehr.rm.support.identification.ObjectReference;
import org.openehr.rm.support.identification.ObjectVersionID;
import org.openehr.rm.support.identification.VersionTreeID;
import org.openehr.rm.support.terminology.TerminologyService;
/**
* @author yinsulim
*
*/
/**
* @author yinsulim
*
* @param <T>
*/
public class VersionedObject<T> extends RMObject {
/**
* Constructs a VersionObject with first originalVersion
*/
public VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated, ObjectVersionID versionID, T data,
DvCodedText lifecycleState, AuditDetails commitAudit,
ObjectReference contribution, String signature,
TerminologyService terminologyService) {
this(uid, ownerID, timeCreated);
commitOriginalVersion(versionID, null, data, commitAudit, contribution,
lifecycleState, signature, terminologyService);
}
/**
* Constructs a VersionObject with first importedVersion
*/
public VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated, OriginalVersion<T> item, AuditDetails commitAudit,
ObjectReference contribution, String signature) {
this(uid, ownerID, timeCreated);
commitImportedVersion(item, commitAudit, contribution, signature);
}
/**
* Constructs a VersionObject with first merged Version
*/
public VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated, ObjectVersionID versionID,
ObjectVersionID precedingVersionID, T data, DvCodedText lifecycleState,
AuditDetails commitAudit, ObjectReference contribution,
Set<ObjectVersionID> otherInputVersionUids, String signature,
TerminologyService terminologyService) {
this(uid, ownerID, timeCreated);
commitOriginalMergedVersion(versionID, precedingVersionID, data, lifecycleState,
commitAudit, contribution, otherInputVersionUids, signature,
terminologyService);
}
private VersionedObject(HierarchicalObjectID uid, ObjectReference ownerID,
DvDateTime timeCreated) {
if (uid == null) {
throw new IllegalArgumentException("null uid");
}
if (ownerID == null) {
throw new IllegalArgumentException("null ownerID");
}
if (timeCreated == null) {
throw new IllegalArgumentException("null timeCreated");
}
this.uid = uid;
this.ownerID = ownerID;
this.timeCreated = timeCreated;
timeVersionMap = new TreeMap<DvDateTime, Version<T>>();
idVersionMap = new HashMap<ObjectVersionID, Version<T>>();
}
/**
* Add a new ImportedVersion
*
* @param commitAudit
* @param contribution
* @param item
*/
public synchronized void commitImportedVersion(OriginalVersion<T> item, AuditDetails commitAudit,
ObjectReference contribution, String signature) {
commitVersionCheck(item.getUid(), item.getPrecedingVersionID());
Version<T> version = new ImportedVersion<T>(item, commitAudit, contribution, signature);
addVersion(version);
}
private synchronized void commitVersionCheck(ObjectVersionID vUid, ObjectVersionID precedingVUid) {
if (versionCount() > 0 && !hasVersionID(precedingVUid)) {
throw new IllegalArgumentException("precedingVersionID not found");
}
if(!vUid.objectID().equals(this.uid.root())) {
throw new IllegalArgumentException("ownerID different from versionedObject");
}
}
private synchronized void addVersion(Version<T> version) {
if (!version.getUid().versionTreeID().isBranch()) {
int trunkNo = Integer.parseInt(version.getUid().versionTreeID().trunkVersion());
if (trunkNo != trunkCounter + 1) {
throw new IllegalArgumentException("invlalid trunk no in uid");
} else {
trunkCounter++;
latestTrunkUid = version.getUid();
}
}
timeVersionMap.put(version.getCommitAudit().getTimeCommitted(), version);
idVersionMap.put(version.getUid(), version);
}
/**
* Add a new original Version
* @param versionID
* @param precedingVersionID
* @param data
* @param commitAudit
* @param contribution
* @param lifecycleState
* @param terminologyService
*/
public synchronized void commitOriginalVersion(ObjectVersionID versionID,
ObjectVersionID precedingVersionID, T data, AuditDetails commitAudit,
ObjectReference contribution, DvCodedText lifecycleState, String signature,
TerminologyService terminologyService) {
commitVersionCheck(versionID, precedingVersionID);
Version<T> version = new OriginalVersion<T>(versionID, precedingVersionID,
data, lifecycleState, commitAudit, contribution, signature, null, null,
false, terminologyService);
addVersion(version);
}
/**
* Add a new original MergedVersion
* @param versionID
* @param precedingVersionID
* @param data
* @param commitAudit
* @param contribution
* @param lifecycleState
* @param terminologyService
*/
public synchronized void commitOriginalMergedVersion(ObjectVersionID versionID,
ObjectVersionID precedingVersionID, T data, DvCodedText lifecycleState,
AuditDetails commitAudit, ObjectReference contribution,
Set<ObjectVersionID> otherInputVersionUids, String signature,
TerminologyService terminologyService) {
//if (versionCount() > 0 && !hasVersionID(precedingVersionID)) {
// throw new IllegalArgumentException("precedingVersionID not found");
//}
commitVersionCheck(versionID, precedingVersionID);
Version<T> version = new OriginalVersion<T>(versionID, precedingVersionID,
data, lifecycleState, commitAudit, contribution, signature, otherInputVersionUids,
null, true, terminologyService);
addVersion(version);
}
/**
* Create a next logical uid for a Version based on precedingVersionID
*
* @param precedingVersionID
* @param systemID
* @return
*/
//TODO: delete this
/* private ObjectVersionID nextUid(ObjectVersionID precedingVersionID, String systemID) {
VersionTreeID vTreeId = null;
HierarchicalObjectID creatingSystemID = null;
if (precedingVersionID != null) {
vTreeId = precedingVersionID.versionTreeID().next();
creatingSystemID = precedingVersionID.creatingSystemID();
} else {
vTreeId = new VersionTreeID(Integer.toString(1));
creatingSystemID = new HierarchicalObjectID(systemID);
}
return new ObjectVersionID(uid.root(), creatingSystemID, vTreeId);
}*/
/**
* Unique identifier of this version repository.
*
* @return UID
*/
public HierarchicalObjectID getUid() {
return uid;
}
/**
* Reference to object to which this versioned repository belongs,
* eg the id of the containing EHR.
*
* @return OwnerID
*/
public ObjectReference getOwnerID() {
return ownerID;
}
/**
* Time of initial creation of this versioned object.
*
* @return time of creation
*/
public DvDateTime getTimeCreated() {
return timeCreated;
}
/**
* Return a list of all versions in this object.
*
* @return all versions
*/
public synchronized List<Version<T>> allVersions() {
// todo: fix the order of this list
return new ArrayList<Version<T>>(idVersionMap.values());
}
/**
* Return a list of ids of all versions in this object.
*
* @return List<String>
*/
public synchronized List<ObjectVersionID> allVersionIDs() {
// todo: fix the order of list
return new ArrayList<ObjectVersionID>(idVersionMap.keySet());
}
/**
* Return the total number of versions in this object
*
* @return version count
*/
public synchronized int versionCount() {
return idVersionMap.size();
}
/**
* True if a version with given id exists.
*
* @param id
* @return true if has
* @throws IllegalArgumentException
*/
public synchronized boolean hasVersionID(ObjectVersionID id) {
if (id == null) {
throw new IllegalArgumentException("null id");
}
return idVersionMap.containsKey(id);
}
/**
* True if a version for given time exists.
*
* @param time
* @return true if has version
* @throws IllegalArgumentException if time null
*/
public synchronized boolean hasVersionAtTime(DvDateTime time) {
if (time == null) {
throw new IllegalArgumentException("null time");
}
return timeVersionMap.containsKey(time);
}
/**
* True if version with an id is an OriginalVersion
*
* @param uid
*/
public boolean isOriginalVersion(ObjectVersionID uid) {
if (!idVersionMap.containsKey(uid)) {
throw new IllegalArgumentException("versionID not found");
}
Version<T> version = idVersionMap.get(uid);
return version instanceof OriginalVersion;
}
/**
* Return the version with given id
*
* @param id
* @return null if not found
* @throws IllegalArgumentException if id null
*/
public synchronized Version<T> versionWithID(ObjectVersionID id) {
if (id == null) {
throw new IllegalArgumentException("null id");
}
return idVersionMap.get(id);
}
/**
* Return the version for given time
*
* @param time
* @return null if not found
* @throws IllegalArgumentException if time null
*/
public synchronized Version<T> versionAtTime(DvDateTime time) {
if (time == null) {
throw new IllegalArgumentException("null time");
}
return timeVersionMap.get(time);
}
/**
* Return the latest version.
*
* @return lastest version
*/
public synchronized Version<T> latestVersion() {
return (Version<T>) timeVersionMap.get(timeVersionMap.lastKey());
}
/**
* Return the most recetly added trunk version
*
*/
public synchronized Version<T> latestTrunkVersion() {
return (Version<T>) idVersionMap.get(latestTrunkUid);
}
/**
* Return the lifecycle state from the latest trunk version.
*
*/
public DvCodedText latestTrunkLifeCycleSate() {
Version<T> trunk = latestTrunkVersion();
return latestTrunkVersion().getLifeCycleState();
}
/**
* History of all audits and attestations in this versioned repository
*
* @return revisionHistory
*/
public RevisionHistory revisionHistory() {
ArrayList<Version<T>> versions = new ArrayList<Version<T>> (timeVersionMap.values());
ArrayList<RevisionHistoryItem> revHistoryItems = new ArrayList<RevisionHistoryItem>();
for(Version<T> version : versions) {
ArrayList<AuditDetails> audits = new ArrayList<AuditDetails>();
audits.add(version.getCommitAudit());
if (version instanceof OriginalVersion) {
OriginalVersion<T> orgVersion = (OriginalVersion<T>) version;
audits.addAll(orgVersion.getAttestations());
}
revHistoryItems.add(new RevisionHistoryItem(audits, version.getUid()));
}
return new RevisionHistory(revHistoryItems);
}
/**
* Add a new attestation to the specified version. Attestations can only
* be added to OriginalVersion
*
* @param attestation
* @param versionID
*/
public synchronized void commitAttestation(Attestation attestation,
ObjectVersionID versionID) {
if (attestation == null) {
throw new IllegalArgumentException("null attestation");
}
if (isOriginalVersion(versionID)) {
OriginalVersion<T> oVersion = (OriginalVersion<T>) idVersionMap.get(versionID);
oVersion.getAttestations().add(attestation);
} else {
throw new IllegalArgumentException("attestatios cannot be added to importedVersion");
}
}
//POJO start
protected VersionedObject() {
}
private Long id;
protected Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
void setUid(HierarchicalObjectID uid) {
this.uid = uid;
}
void setOwnerID(ObjectReference ownerID) {
this.ownerID = ownerID;
}
void setTimeCreated(DvDateTime timeCreated) {
this.timeCreated = timeCreated;
}
// in order to skip map timeVersionMap to table
void setVersions(Set<Version<T>> versions) {
idVersionMap = new HashMap<ObjectVersionID, Version<T>>();
timeVersionMap = new TreeMap<DvDateTime, Version<T>>();
for(Version<T> version : versions) {
addVersion(version);
}
}
// required to map bidirectional one-to-many relationship
Set<Version<T>> getVersions() {
return new HashSet<Version<T>>(timeVersionMap.values());
}
/**
* version id for the version before the first version
*/
//public static final String NONE = "0";
//public static final String FIRST = "1";
/* fields */
private HierarchicalObjectID uid;
private ObjectReference ownerID;
private DvDateTime timeCreated;
private SortedMap<DvDateTime, Version<T>> timeVersionMap;
//change to hashmap because ObjectVersionID doesn't implement Comparable
private HashMap<ObjectVersionID, Version<T>> idVersionMap;
private int trunkCounter;
private ObjectVersionID latestTrunkUid;
}
/*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an 'AS IS' basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is VersionedObject.java
*
* The Initial Developer of the Original Code is <NAME>.
* Portions created by the Initial Developer are Copyright (C) 2003-2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Software distributed under the License is distributed on an 'AS IS' basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* ***** END LICENSE BLOCK *****
*/
| 17,404 | 0.62533 | 0.622346 | 498 | 33.98996 | 27.641964 | 145 | false | false | 0 | 0 | 0 | 0 | 81 | 0.004648 | 0.465863 | false | false |
7
|
ab0266ae3ea84fed09d2ec32f4411f2a88216b43
| 27,341,761,856,007 |
bff4710cb3d155a8b7351ca4cddc1550377b5341
|
/src/Chapter_05/Exercise_10.java
|
bbe4fe0686794b35668515183965ad667134be11
|
[] |
no_license
|
DanielHornos/Java-Programming-10th-edition
|
https://github.com/DanielHornos/Java-Programming-10th-edition
|
168578188a20d11e5c3cff7f8844ac57886198da
|
5d1f124892736d157e90d523b0a456c2e7d4c929
|
refs/heads/master
| 2021-01-20T00:34:03.770000 | 2017-04-23T16:25:21 | 2017-04-23T16:25:21 | 89,151,745 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Chapter_05;
/**
* Chapter 5 Exercise 10:
*
* (Find numbers divisible by 5 and 6)
* Write a program that displays all the numbers from 100 to 1,000,
* ten per line, that are divisible by 5 and 6. Numbers are separated
* by exactly one space.
*
* Created by Daniel Hornos Valiente on 8/24/16.
*/
public class Exercise_10 {
public static void main(String[] args) {
int numCount = 1;
for (int i = 100; i <= 1000; i++) {
if (i % 5 == 0 && i % 6 == 0)
System.out.print((numCount++ % 10 != 0) ? i + " " : i + "\n");
}
}
}
|
UTF-8
|
Java
| 616 |
java
|
Exercise_10.java
|
Java
|
[
{
"context": "ted\n * by exactly one space.\n *\n * Created by Daniel Hornos Valiente on 8/24/16.\n */\npublic class Exercise_10 {\n\n p",
"end": 315,
"score": 0.9998746514320374,
"start": 293,
"tag": "NAME",
"value": "Daniel Hornos Valiente"
}
] | null |
[] |
package Chapter_05;
/**
* Chapter 5 Exercise 10:
*
* (Find numbers divisible by 5 and 6)
* Write a program that displays all the numbers from 100 to 1,000,
* ten per line, that are divisible by 5 and 6. Numbers are separated
* by exactly one space.
*
* Created by <NAME> on 8/24/16.
*/
public class Exercise_10 {
public static void main(String[] args) {
int numCount = 1;
for (int i = 100; i <= 1000; i++) {
if (i % 5 == 0 && i % 6 == 0)
System.out.print((numCount++ % 10 != 0) ? i + " " : i + "\n");
}
}
}
| 600 | 0.538961 | 0.477273 | 24 | 24.666666 | 25.017771 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
7
|
58fddc2bd36e2efb8413ddd92ccffa98d92a1d24
| 20,547,123,614,308 |
208924523aaba7baa60118f20d2da395fa34ec73
|
/api/portal/src/main/java/store/tacomall/apiportal/service/CouponService.java
|
84ac0da522da932bfd185a6123d77c852c879537
|
[
"Apache-2.0"
] |
permissive
|
nowanys/tacomall-springboot
|
https://github.com/nowanys/tacomall-springboot
|
3b6cef50236e2af9f47bebe538890e1664f9a5b3
|
ecc7d9feb79b7a311421da0efde695e91528748a
|
refs/heads/master
| 2023-02-24T19:10:35.547000 | 2021-01-25T01:03:17 | 2021-01-25T01:03:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/***
* @Author: 码上talk|RC
* @Date: 2020-07-13 14:38:51
* @LastEditTime: 2020-07-13 14:38:52
* @LastEditors: 码上talk|RC
* @Description:
* @FilePath: /tacomall-springboot/tacomall-api/tacomall-api-portal/src/main/java/store/tacomall/apiportal/service/CouponService.java
* @Just do what I think it is right
*/
package store.tacomall.apiportal.service;
public class CouponService {
}
|
UTF-8
|
Java
| 398 |
java
|
CouponService.java
|
Java
|
[
{
"context": "/***\n * @Author: 码上talk|RC\n * @Date: 2020-07-13 14:38:51\n * @LastEditTime",
"end": 23,
"score": 0.9073969721794128,
"start": 17,
"tag": "USERNAME",
"value": "码上talk"
},
{
"context": "astEditTime: 2020-07-13 14:38:52\n * @LastEditors: 码上talk|RC\n * @Description: \n * @FilePath: /tacomall-spri",
"end": 118,
"score": 0.8867689967155457,
"start": 112,
"tag": "USERNAME",
"value": "码上talk"
}
] | null |
[] |
/***
* @Author: 码上talk|RC
* @Date: 2020-07-13 14:38:51
* @LastEditTime: 2020-07-13 14:38:52
* @LastEditors: 码上talk|RC
* @Description:
* @FilePath: /tacomall-springboot/tacomall-api/tacomall-api-portal/src/main/java/store/tacomall/apiportal/service/CouponService.java
* @Just do what I think it is right
*/
package store.tacomall.apiportal.service;
public class CouponService {
}
| 398 | 0.728205 | 0.65641 | 14 | 26.857143 | 32.725826 | 133 | false | false | 0 | 0 | 0 | 0 | 67 | 0.171795 | 0.214286 | false | false |
7
|
4bbce09fb0dc0272f75e1a6f1844ab4bf41b6679
| 20,547,123,614,054 |
05f4d1e83c6b4ed5b58cef01411ed80b22f50f33
|
/Net 173/downloader/src/main/java/local/net173/utils/web/downloader/v2/youtube/model/MediaList.java
|
b8f5604326997c6fab5637fdd0bd7002b13fba26
|
[] |
no_license
|
ZhukovAN/ECLIPSE.JAVA
|
https://github.com/ZhukovAN/ECLIPSE.JAVA
|
f7d57dd75f244b890a88fbc7e9d4017fbe9487dd
|
59dedf1e9e1319174d47c4a550f66b72141fb111
|
refs/heads/master
| 2020-03-11T01:21:27.934000 | 2018-04-18T11:23:03 | 2018-04-18T11:23:03 | 129,689,432 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package local.net173.utils.web.downloader.v2.youtube.model;
import java.util.ArrayList;
import java.util.List;
import local.net173.utils.web.downloader.v2.youtube.model.Thumbnail;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class MediaList {
protected String title;
protected Thumbnail thumbnail;
protected List<Media> items = new ArrayList<Media>();
}
|
UTF-8
|
Java
| 391 |
java
|
MediaList.java
|
Java
|
[] | null |
[] |
package local.net173.utils.web.downloader.v2.youtube.model;
import java.util.ArrayList;
import java.util.List;
import local.net173.utils.web.downloader.v2.youtube.model.Thumbnail;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class MediaList {
protected String title;
protected Thumbnail thumbnail;
protected List<Media> items = new ArrayList<Media>();
}
| 391 | 0.777494 | 0.757033 | 15 | 25.066668 | 21.151728 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
7
|
64492369e9564362af82efb5d9e9b5c964026e47
| 14,748,917,719,546 |
74608e7ea83dec63dac95c9478ea4164e241cd53
|
/javalearn/src/main/java/com/cn/idota/singleton/SingleHungry.java
|
aa85116d81174fb8195c10f2c980c2a90a5e25ad
|
[] |
no_license
|
idota126/Java-Learn
|
https://github.com/idota126/Java-Learn
|
6a515cb0aafc2c7a3349446dcb70eaf341bf55dd
|
cee1121b264fd3e62ad95315fc32699c79fce116
|
refs/heads/master
| 2020-03-17T11:06:35.035000 | 2019-03-28T02:40:49 | 2019-03-28T02:40:49 | 133,538,499 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cn.idota.singleton;
/**
* @Description: 饿汉模式
* @Author idota
* @Date 2019/3/27
*/
public class SingleHungry {
private static SingleHungry s = new SingleHungry();
private SingleHungry(){}
public static SingleHungry getInstance(){
return s;
}
}
|
UTF-8
|
Java
| 301 |
java
|
SingleHungry.java
|
Java
|
[
{
"context": "a.singleton;\n\n/**\n * @Description: 饿汉模式\n * @Author idota\n * @Date 2019/3/27\n */\npublic class SingleHungry ",
"end": 75,
"score": 0.9993760585784912,
"start": 70,
"tag": "USERNAME",
"value": "idota"
}
] | null |
[] |
package com.cn.idota.singleton;
/**
* @Description: 饿汉模式
* @Author idota
* @Date 2019/3/27
*/
public class SingleHungry {
private static SingleHungry s = new SingleHungry();
private SingleHungry(){}
public static SingleHungry getInstance(){
return s;
}
}
| 301 | 0.641638 | 0.617747 | 21 | 12.952381 | 16.299215 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false |
7
|
7695c0d1d5b0148b450ea302f4edddc0c542139e
| 15,187,004,426,918 |
5ae614fe3540d5f292823c8051c7dd4433952917
|
/数据结构与算法/DS/存储结构/src/Tree/SplayTree.java
|
a21da803fd06306c3682110f62c1fa77559a477a
|
[] |
no_license
|
yesbutter/code-skills
|
https://github.com/yesbutter/code-skills
|
423921d9283e4895c23163cc4db95ff93d0d49a0
|
95a92bcc2b80c57c2166ebddf90490db7fb79812
|
refs/heads/master
| 2023-06-01T16:54:22.784000 | 2021-06-24T06:47:37 | 2021-06-24T06:47:37 | 260,665,088 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Tree;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* @description: 伸展树。每次插入,查找的节点会被放入到根节点。并且满足二叉搜索树的性质
* 实现相对简单,程序局部性原理,适合访问一段段连续的空间。
* @author: lhg
* @email: 1296821114@qq.com
* @create: 2020-05-18 13:42
*/
public class SplayTree<E extends Comparable<E>> {
// PriorityQueue
private TreeNode<E> mRoot;
private int size = 0;
public void insert(E data) {
if (data == null)
throw new NullPointerException();
mRoot = insert(mRoot, data);
}
/**
* 每次插入之后返回根节点。
* 插入后通过旋转操作来将插入节结点放到根结点
*
* @param node
* @param data
* @return
*/
//TODO 相同结点的考虑
private TreeNode<E> insert(TreeNode<E> node, E data) {
int cmp = 0;
TreeNode<E> parent = node;
while (node != null) {
parent = node;
cmp = data.compareTo(node.data);
if (cmp < 0) {
node = node.lChild;
} else {
node = node.rChild;
}
}
TreeNode<E> newNode = new TreeNode<>(data);
newNode.parent = parent;
if (parent != null) {
cmp = data.compareTo(parent.data);
if (cmp < 0) {
parent.lChild = newNode;
} else {
parent.rChild = newNode;
}
}
size++;
upNode2Root(newNode);
return newNode;
}
public TreeNode<E> search(E data) {
TreeNode<E> node = search(mRoot, data);
if (node == null)
return null;
//将node递归上移,进行平衡。
upNode2Root(node);
return mRoot;
}
private void upNode2Root(TreeNode<E> node) {
TreeNode<E> grandFather;
while (node.parent != null) {
if (node.parent.lChild == node) {
//当前结点是左孩子,右旋父结点
rightRotate(node.parent);
} else {
//当前结点是右孩子,左旋父结点
leftRotate(node.parent);
}
}
}
/**
* 查找data元素所在的位置,并将这个位置通过旋转上升到根结点
*
* @param node 查找结点
* @param data 查找数据
* @return 根节点
*/
private TreeNode<E> search(TreeNode<E> node, E data) {
if (node == null)
return null;
int cmp = data.compareTo(node.data);
if (cmp < 0) {
return search(node.lChild, data);
} else if (cmp > 0) {
return search(node.rChild, data);
} else {
return node;
}
}
/**
* 移除元素
*
* @param data
*/
public void remove(E data) {
if (mRoot == null)
return;
TreeNode<E> node = search(mRoot, data);
if (node == null)
return;
upNode2Root(node);
//找后继结点
remove(node);
--size;
}
/**
* 删除在结点中的第一次查找到的这个元素
* 先把这个元素放到根结点,然后再进行删除
*
* @param node
* @param
*/
private void remove(TreeNode<E> node) {
if (node.lChild != null && node.rChild != null) {
TreeNode<E> tmp = successor(node);
node.data = tmp.data;
node = tmp;
}
TreeNode<E> replace;
if (node.lChild != null) {
replace = node.lChild;
} else {
replace = node.rChild;
}
if (replace != null) {
if (node.parent == null) {
mRoot = replace;
} else if (node == node.parent.lChild) {
node.parent.lChild = replace;
} else {
node.parent.rChild = replace;
}
node.lChild = node.rChild = node.parent = null;
} else if (node.parent == null) {
mRoot = null;
} else {
//删除结点没有子节点,而且存在夫结点
if (node.parent.lChild == node) {
node.parent.lChild = null;
} else {
node.parent.rChild = null;
}
node.parent = null;
}
}
private TreeNode<E> successor(TreeNode<E> node) {
if (node == null) return null;
TreeNode<E> replace;
if (node.rChild != null) {
replace = node.rChild;
while (replace.lChild != null) {
replace = replace.lChild;
}
} else {
replace = node.lChild;
while (replace.rChild != null) {
replace = replace.rChild;
}
}
return replace;
}
public void levelTraversal() {
levelTraversal(mRoot);
}
public void mid() {
mid(mRoot);
System.out.println();
}
private void mid(TreeNode<E> node) {
if (node == null)
return;
mid(node.lChild);
System.out.print(node.data + " ");
mid(node.rChild);
}
private void levelTraversal(TreeNode<E> node) {
TreeNode<E> nlast = node;
TreeNode<E> last = node;
Queue<TreeNode<E>> queue = new LinkedList<>();
queue.add(node);
TreeNode<E> tmp;
while (!queue.isEmpty()) {
tmp = queue.poll();
System.out.print(tmp.data + " ");
if (tmp.lChild != null) {
queue.add(tmp.lChild);
nlast = tmp.lChild;
}
if (tmp.rChild != null) {
queue.add(tmp.rChild);
nlast = tmp.rChild;
}
if (tmp == last) {
System.out.println();
last = nlast;
}
}
}
/**
* y结点想上位
* 类似与红黑树的左旋
*
* @param x
* @return
*/
private void leftRotate(TreeNode<E> x) {
if (x != null) {
TreeNode<E> y = x.rChild;
//建立x和t2的关系
x.rChild = y.lChild;
if (y.lChild != null) {
y.lChild.parent = x;
}
//修改y和x父结点指针关系
y.parent = x.parent;
if (x.parent == null) {
//说明当前结点是根结点
mRoot = y;
} else if (x.parent.lChild == x) {
x.parent.lChild = y;
} else {
x.parent.rChild = y;
}
//建立x,y的关系
y.lChild = x;
x.parent = y;
}
}
/**
* y想上位 x
* y t3
*
* @param x t1 t2
*/
private void rightRotate(TreeNode<E> x) {
if (x != null) {
TreeNode<E> y = x.lChild;
x.lChild = y.rChild;
if (y.rChild != null) {
y.rChild.parent = x;
}
y.parent = x.parent;
if (x.parent == null) {
//当前结点是根结点
mRoot = y;
} else if (x.parent.lChild == x) {
x.parent.lChild = y;
} else {
x.parent.rChild = y;
}
//建立xy关系
y.rChild = x;
x.parent = y;
}
}
public static void main(String[] args) {
SplayTree<Integer> tree = new SplayTree<>();
tree.insert(5);
tree.mid();
tree.insert(6);
tree.mid();
tree.insert(8);
tree.mid();
tree.insert(9);
tree.mid();
tree.insert(10);
tree.mid();
tree.insert(15);
tree.mid();
tree.insert(7);
tree.insert(12);
tree.insert(14);
tree.mid();
tree.remove(8);
tree.mid();
}
}
|
UTF-8
|
Java
| 8,101 |
java
|
SplayTree.java
|
Java
|
[
{
"context": "搜索树的性质\n * 实现相对简单,程序局部性原理,适合访问一段段连续的空间。\n * @author: lhg\n * @email: 1296821114@qq.com\n * @create: 2020-05-",
"end": 205,
"score": 0.9996589422225952,
"start": 202,
"tag": "USERNAME",
"value": "lhg"
},
{
"context": ",程序局部性原理,适合访问一段段连续的空间。\n * @author: lhg\n * @email: 1296821114@qq.com\n * @create: 2020-05-18 13:42\n */\npublic class Spl",
"end": 234,
"score": 0.999790370464325,
"start": 217,
"tag": "EMAIL",
"value": "1296821114@qq.com"
}
] | null |
[] |
package Tree;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* @description: 伸展树。每次插入,查找的节点会被放入到根节点。并且满足二叉搜索树的性质
* 实现相对简单,程序局部性原理,适合访问一段段连续的空间。
* @author: lhg
* @email: <EMAIL>
* @create: 2020-05-18 13:42
*/
public class SplayTree<E extends Comparable<E>> {
// PriorityQueue
private TreeNode<E> mRoot;
private int size = 0;
public void insert(E data) {
if (data == null)
throw new NullPointerException();
mRoot = insert(mRoot, data);
}
/**
* 每次插入之后返回根节点。
* 插入后通过旋转操作来将插入节结点放到根结点
*
* @param node
* @param data
* @return
*/
//TODO 相同结点的考虑
private TreeNode<E> insert(TreeNode<E> node, E data) {
int cmp = 0;
TreeNode<E> parent = node;
while (node != null) {
parent = node;
cmp = data.compareTo(node.data);
if (cmp < 0) {
node = node.lChild;
} else {
node = node.rChild;
}
}
TreeNode<E> newNode = new TreeNode<>(data);
newNode.parent = parent;
if (parent != null) {
cmp = data.compareTo(parent.data);
if (cmp < 0) {
parent.lChild = newNode;
} else {
parent.rChild = newNode;
}
}
size++;
upNode2Root(newNode);
return newNode;
}
public TreeNode<E> search(E data) {
TreeNode<E> node = search(mRoot, data);
if (node == null)
return null;
//将node递归上移,进行平衡。
upNode2Root(node);
return mRoot;
}
private void upNode2Root(TreeNode<E> node) {
TreeNode<E> grandFather;
while (node.parent != null) {
if (node.parent.lChild == node) {
//当前结点是左孩子,右旋父结点
rightRotate(node.parent);
} else {
//当前结点是右孩子,左旋父结点
leftRotate(node.parent);
}
}
}
/**
* 查找data元素所在的位置,并将这个位置通过旋转上升到根结点
*
* @param node 查找结点
* @param data 查找数据
* @return 根节点
*/
private TreeNode<E> search(TreeNode<E> node, E data) {
if (node == null)
return null;
int cmp = data.compareTo(node.data);
if (cmp < 0) {
return search(node.lChild, data);
} else if (cmp > 0) {
return search(node.rChild, data);
} else {
return node;
}
}
/**
* 移除元素
*
* @param data
*/
public void remove(E data) {
if (mRoot == null)
return;
TreeNode<E> node = search(mRoot, data);
if (node == null)
return;
upNode2Root(node);
//找后继结点
remove(node);
--size;
}
/**
* 删除在结点中的第一次查找到的这个元素
* 先把这个元素放到根结点,然后再进行删除
*
* @param node
* @param
*/
private void remove(TreeNode<E> node) {
if (node.lChild != null && node.rChild != null) {
TreeNode<E> tmp = successor(node);
node.data = tmp.data;
node = tmp;
}
TreeNode<E> replace;
if (node.lChild != null) {
replace = node.lChild;
} else {
replace = node.rChild;
}
if (replace != null) {
if (node.parent == null) {
mRoot = replace;
} else if (node == node.parent.lChild) {
node.parent.lChild = replace;
} else {
node.parent.rChild = replace;
}
node.lChild = node.rChild = node.parent = null;
} else if (node.parent == null) {
mRoot = null;
} else {
//删除结点没有子节点,而且存在夫结点
if (node.parent.lChild == node) {
node.parent.lChild = null;
} else {
node.parent.rChild = null;
}
node.parent = null;
}
}
private TreeNode<E> successor(TreeNode<E> node) {
if (node == null) return null;
TreeNode<E> replace;
if (node.rChild != null) {
replace = node.rChild;
while (replace.lChild != null) {
replace = replace.lChild;
}
} else {
replace = node.lChild;
while (replace.rChild != null) {
replace = replace.rChild;
}
}
return replace;
}
public void levelTraversal() {
levelTraversal(mRoot);
}
public void mid() {
mid(mRoot);
System.out.println();
}
private void mid(TreeNode<E> node) {
if (node == null)
return;
mid(node.lChild);
System.out.print(node.data + " ");
mid(node.rChild);
}
private void levelTraversal(TreeNode<E> node) {
TreeNode<E> nlast = node;
TreeNode<E> last = node;
Queue<TreeNode<E>> queue = new LinkedList<>();
queue.add(node);
TreeNode<E> tmp;
while (!queue.isEmpty()) {
tmp = queue.poll();
System.out.print(tmp.data + " ");
if (tmp.lChild != null) {
queue.add(tmp.lChild);
nlast = tmp.lChild;
}
if (tmp.rChild != null) {
queue.add(tmp.rChild);
nlast = tmp.rChild;
}
if (tmp == last) {
System.out.println();
last = nlast;
}
}
}
/**
* y结点想上位
* 类似与红黑树的左旋
*
* @param x
* @return
*/
private void leftRotate(TreeNode<E> x) {
if (x != null) {
TreeNode<E> y = x.rChild;
//建立x和t2的关系
x.rChild = y.lChild;
if (y.lChild != null) {
y.lChild.parent = x;
}
//修改y和x父结点指针关系
y.parent = x.parent;
if (x.parent == null) {
//说明当前结点是根结点
mRoot = y;
} else if (x.parent.lChild == x) {
x.parent.lChild = y;
} else {
x.parent.rChild = y;
}
//建立x,y的关系
y.lChild = x;
x.parent = y;
}
}
/**
* y想上位 x
* y t3
*
* @param x t1 t2
*/
private void rightRotate(TreeNode<E> x) {
if (x != null) {
TreeNode<E> y = x.lChild;
x.lChild = y.rChild;
if (y.rChild != null) {
y.rChild.parent = x;
}
y.parent = x.parent;
if (x.parent == null) {
//当前结点是根结点
mRoot = y;
} else if (x.parent.lChild == x) {
x.parent.lChild = y;
} else {
x.parent.rChild = y;
}
//建立xy关系
y.rChild = x;
x.parent = y;
}
}
public static void main(String[] args) {
SplayTree<Integer> tree = new SplayTree<>();
tree.insert(5);
tree.mid();
tree.insert(6);
tree.mid();
tree.insert(8);
tree.mid();
tree.insert(9);
tree.mid();
tree.insert(10);
tree.mid();
tree.insert(15);
tree.mid();
tree.insert(7);
tree.insert(12);
tree.insert(14);
tree.mid();
tree.remove(8);
tree.mid();
}
}
| 8,091 | 0.443408 | 0.436742 | 311 | 23.118971 | 14.594475 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411576 | false | false |
7
|
6bc72913501159c55190e07a5a7c54219ef7a5f9
| 6,124,623,372,094 |
2e775f51aa630bb7960b921489fd8afd20ea65e2
|
/tp/p1/logic/SunflowerList.java
|
b8641775bdb66f5a17884599ee8a1c40d73a7fd6
|
[] |
no_license
|
TP-Pascua-Valencia/TP-Projects
|
https://github.com/TP-Pascua-Valencia/TP-Projects
|
b1dcaa19cdb4a030ee40c7a5ba7e5fafce8c2d7b
|
5eddeab3faa71af0b9ca7d8cd2a0b0e689c6b8ab
|
refs/heads/master
| 2020-03-30T16:40:59.282000 | 2018-10-03T14:16:08 | 2018-10-03T14:16:08 | 151,421,141 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tp.p1.logic;
public class SunflowerList { // Lists elements of the class Sunflower
}
|
UTF-8
|
Java
| 95 |
java
|
SunflowerList.java
|
Java
|
[] | null |
[] |
package tp.p1.logic;
public class SunflowerList { // Lists elements of the class Sunflower
}
| 95 | 0.757895 | 0.747368 | 5 | 18 | 26.615786 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
7
|
eb2391dad70b5f6ed59b8b3ae0372d21ede1bfd9
| 833,223,692,706 |
88783b8e30d9712be9b7f1be759c49781cc9a71f
|
/app/src/main/java/com/example/employeecard/models/EmployeeSkill.java
|
555864cbc101070a64ab3c449460ebf89600dc04
|
[] |
no_license
|
asalybek/EmployeeCardNew
|
https://github.com/asalybek/EmployeeCardNew
|
651441423b960b363288a4dc08f458fc4a174bbb
|
152a1f48a76fae78b8f76b5ae59db50444b691fb
|
refs/heads/master
| 2021-03-14T09:31:21.962000 | 2020-05-01T16:26:59 | 2020-05-01T16:26:59 | 246,755,943 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.employeecard.models;
public class EmployeeSkill {
public static final String TABLE_SKILL = "skills";
public static final String SKILL_ID = "skill_id";
public static final String SKILL_NAME = "skill_name";
public static final String CREATE_TABLE_SKILL =
"CREATE TABLE " + TABLE_SKILL + "("
+ SKILL_ID + " INTEGER,"
+ SKILL_NAME + " TEXT"
+ ")";
private int skill_id;
private String skill_name;
public EmployeeSkill(){}
public EmployeeSkill(int skill_id, String skill_name) {
this.skill_id = skill_id;
this.skill_name = skill_name;
}
public int getSkill_id() {
return skill_id;
}
public void setSkill_id(int skill_id) {
this.skill_id = skill_id;
}
public String getSkill_name() {
return skill_name;
}
public void setSkill_name(String skill_name) {
this.skill_name = skill_name;
}
}
|
UTF-8
|
Java
| 998 |
java
|
EmployeeSkill.java
|
Java
|
[] | null |
[] |
package com.example.employeecard.models;
public class EmployeeSkill {
public static final String TABLE_SKILL = "skills";
public static final String SKILL_ID = "skill_id";
public static final String SKILL_NAME = "skill_name";
public static final String CREATE_TABLE_SKILL =
"CREATE TABLE " + TABLE_SKILL + "("
+ SKILL_ID + " INTEGER,"
+ SKILL_NAME + " TEXT"
+ ")";
private int skill_id;
private String skill_name;
public EmployeeSkill(){}
public EmployeeSkill(int skill_id, String skill_name) {
this.skill_id = skill_id;
this.skill_name = skill_name;
}
public int getSkill_id() {
return skill_id;
}
public void setSkill_id(int skill_id) {
this.skill_id = skill_id;
}
public String getSkill_name() {
return skill_name;
}
public void setSkill_name(String skill_name) {
this.skill_name = skill_name;
}
}
| 998 | 0.584168 | 0.584168 | 40 | 23.950001 | 20.098446 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
7
|
dab335fb7c650efcfc253dca82449ae2a12e9601
| 17,214,228,986,425 |
dd5dc19bc75af793bc184f12cff9fb48e1235dde
|
/src/test/java/com/management/appuser/UserManagementServiceTest.java
|
32a6ebfdfe956ccd6dd8ad952cd5725251592861
|
[] |
no_license
|
jmlejarriaga/app-user
|
https://github.com/jmlejarriaga/app-user
|
bb8f386497e03bd1e2da1ed296ab1949d2c190a4
|
f8e2a9667f1de14f0a631969e4b3a0d957fea328
|
refs/heads/master
| 2020-04-29T11:00:00.529000 | 2019-03-17T09:35:23 | 2019-03-17T09:35:23 | 176,080,883 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.management.appuser;
import com.management.appuser.exception.UserBadRequestException;
import com.management.appuser.exception.UserNotFoundException;
import com.management.appuser.management.UserManagementService;
import com.management.appuser.model.User;
import com.management.appuser.model.UserDTO;
import com.management.appuser.model.UserPostDTO;
import com.management.appuser.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.ResponseEntity;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
@RunWith(MockitoJUnitRunner.class)
public class UserManagementServiceTest extends TestUtil {
@InjectMocks
private UserManagementService userManagementService;
@Mock
private UserService userService;
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFoundException_when_dataBaseIsEmpty() {
when(userService.getAllUsers()).thenReturn(Optional.empty());
userManagementService.getAllExistingUsers();
}
@Test
public void shouldReturnListOfUsers_when_dataBaseIsFull() {
List<User> expectedList = aListOfUsers();
when(userService.getAllUsers()).thenReturn(Optional.of(expectedList));
ResponseEntity<List<UserDTO>> response = userManagementService.getAllExistingUsers();
assertEquals(expectedList.size(), response.getBody().size());
assertEquals("name1", response.getBody().get(0).getName());
assertEquals("name2", response.getBody().get(1).getName());
}
@Test
public void shouldReturnUser_when_providedUserIdExists() {
when(userService.getUser(anyInt())).thenReturn(Optional.of(aUser(1, "Pepe", "1980-01-01")));
ResponseEntity<UserDTO> response = userManagementService.getOneUser("1");
assertEquals("Pepe", response.getBody().getName());
}
@Test(expected = UserBadRequestException.class)
public void shouldReturnBadRequestException_when_providedUserIdIsNotNumeric() {
userManagementService.getOneUser("zzz");
}
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFound_when_providedUserIdDoesNotExist() {
when(userService.getUser(anyInt())).thenReturn(Optional.empty());
userManagementService.getOneUser("1");
}
@Test(expected = UserBadRequestException.class)
public void shouldReturnBadRequestException_when_updatingUserIdIsNotNumeric() {
userManagementService.updateUser("zzz", aModifiedUser("Any", "1111-22-33"));
}
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFound_when_updatingNotExistingUser() {
when(userService.getUser(anyInt())).thenReturn(Optional.empty());
userManagementService.updateUser("1", aModifiedUser("Any", "1111-22-33"));
}
@Test
public void shouldCreateNewUser_when_inputIsOk() {
User newUser = aUser(1, "name", "1980-01-01");
when(userService.createNewUser(any(User.class))).thenReturn(Optional.of(newUser));
UserPostDTO userPostDTO = UserPostDTO.builder()
.id(String.valueOf(newUser.getId()))
.name(newUser.getName())
.birthDate(newUser.getBirthDate())
.build();
ResponseEntity<UserDTO> response = userManagementService.createUser(userPostDTO);
assertEquals(CREATED, response.getStatusCode());
}
@Test(expected = UserBadRequestException.class)
public void shouldReturn500_when_userNotCreated() {
User newUser = aUser(1, "name", "1980-01-01");
when(userService.createNewUser(any(User.class))).thenReturn(Optional.empty());
UserPostDTO userPostDTO = UserPostDTO.builder()
.id(String.valueOf(newUser.getId()))
.name(newUser.getName())
.birthDate(newUser.getBirthDate())
.build();
userManagementService.createUser(userPostDTO);
}
@Test(expected = UserBadRequestException.class)
public void shouldReturn400_when_newUserHasInvalidData() {
User newUser = aUser(1, null, "1980-01-01");
UserPostDTO userPostDTO = UserPostDTO.builder()
.id(null)
.name(null)
.birthDate(newUser.getBirthDate())
.build();
userManagementService.createUser(userPostDTO);
}
@Test
public void shouldModifyData_when_updatingExistingUser() {
User existingUser = aUser(1, "name", "1980-01-01");
User modifiedUser = aUser(1, "newName", "1980-01-30");
when(userService.getUser(anyInt())).thenReturn(Optional.of(existingUser));
when(userService.updateUser(any(User.class))).thenReturn(Optional.of(modifiedUser));
ResponseEntity<UserDTO> response = userManagementService.updateUser("1", aModifiedUser("newName", "1980-01-30"));
assertEquals(OK, response.getStatusCode());
assertEquals("newName", response.getBody().getName());
assertEquals("1980-01-30", response.getBody().getBirthDate().format(DateTimeFormatter.ISO_DATE));
}
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFound_when_deletingNotExistingUser() {
when(userService.getUser(anyInt())).thenReturn(Optional.empty());
userManagementService.deleteUser("1");
}
@Test(expected = UserBadRequestException.class)
public void shouldReturnBadRequestException_when_deletingUserIdIsNotNumeric() {
userManagementService.deleteUser("zzz");
}
@Test
public void shouldReturnOk_when_deletingExistingUser() {
User userToDelete = aUser(1, "name", "1980-01-01");
when(userService.getUser(anyInt())).thenReturn(Optional.of(userToDelete));
ResponseEntity<UserDTO> response = userManagementService.deleteUser("1");
assertEquals(OK, response.getStatusCode());
}
}
|
UTF-8
|
Java
| 6,349 |
java
|
UserManagementServiceTest.java
|
Java
|
[
{
"context": "tUser(anyInt())).thenReturn(Optional.of(aUser(1, \"Pepe\", \"1980-01-01\")));\n\n ResponseEntity<UserDT",
"end": 2146,
"score": 0.9997106194496155,
"start": 2142,
"tag": "NAME",
"value": "Pepe"
}
] | null |
[] |
package com.management.appuser;
import com.management.appuser.exception.UserBadRequestException;
import com.management.appuser.exception.UserNotFoundException;
import com.management.appuser.management.UserManagementService;
import com.management.appuser.model.User;
import com.management.appuser.model.UserDTO;
import com.management.appuser.model.UserPostDTO;
import com.management.appuser.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.ResponseEntity;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
@RunWith(MockitoJUnitRunner.class)
public class UserManagementServiceTest extends TestUtil {
@InjectMocks
private UserManagementService userManagementService;
@Mock
private UserService userService;
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFoundException_when_dataBaseIsEmpty() {
when(userService.getAllUsers()).thenReturn(Optional.empty());
userManagementService.getAllExistingUsers();
}
@Test
public void shouldReturnListOfUsers_when_dataBaseIsFull() {
List<User> expectedList = aListOfUsers();
when(userService.getAllUsers()).thenReturn(Optional.of(expectedList));
ResponseEntity<List<UserDTO>> response = userManagementService.getAllExistingUsers();
assertEquals(expectedList.size(), response.getBody().size());
assertEquals("name1", response.getBody().get(0).getName());
assertEquals("name2", response.getBody().get(1).getName());
}
@Test
public void shouldReturnUser_when_providedUserIdExists() {
when(userService.getUser(anyInt())).thenReturn(Optional.of(aUser(1, "Pepe", "1980-01-01")));
ResponseEntity<UserDTO> response = userManagementService.getOneUser("1");
assertEquals("Pepe", response.getBody().getName());
}
@Test(expected = UserBadRequestException.class)
public void shouldReturnBadRequestException_when_providedUserIdIsNotNumeric() {
userManagementService.getOneUser("zzz");
}
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFound_when_providedUserIdDoesNotExist() {
when(userService.getUser(anyInt())).thenReturn(Optional.empty());
userManagementService.getOneUser("1");
}
@Test(expected = UserBadRequestException.class)
public void shouldReturnBadRequestException_when_updatingUserIdIsNotNumeric() {
userManagementService.updateUser("zzz", aModifiedUser("Any", "1111-22-33"));
}
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFound_when_updatingNotExistingUser() {
when(userService.getUser(anyInt())).thenReturn(Optional.empty());
userManagementService.updateUser("1", aModifiedUser("Any", "1111-22-33"));
}
@Test
public void shouldCreateNewUser_when_inputIsOk() {
User newUser = aUser(1, "name", "1980-01-01");
when(userService.createNewUser(any(User.class))).thenReturn(Optional.of(newUser));
UserPostDTO userPostDTO = UserPostDTO.builder()
.id(String.valueOf(newUser.getId()))
.name(newUser.getName())
.birthDate(newUser.getBirthDate())
.build();
ResponseEntity<UserDTO> response = userManagementService.createUser(userPostDTO);
assertEquals(CREATED, response.getStatusCode());
}
@Test(expected = UserBadRequestException.class)
public void shouldReturn500_when_userNotCreated() {
User newUser = aUser(1, "name", "1980-01-01");
when(userService.createNewUser(any(User.class))).thenReturn(Optional.empty());
UserPostDTO userPostDTO = UserPostDTO.builder()
.id(String.valueOf(newUser.getId()))
.name(newUser.getName())
.birthDate(newUser.getBirthDate())
.build();
userManagementService.createUser(userPostDTO);
}
@Test(expected = UserBadRequestException.class)
public void shouldReturn400_when_newUserHasInvalidData() {
User newUser = aUser(1, null, "1980-01-01");
UserPostDTO userPostDTO = UserPostDTO.builder()
.id(null)
.name(null)
.birthDate(newUser.getBirthDate())
.build();
userManagementService.createUser(userPostDTO);
}
@Test
public void shouldModifyData_when_updatingExistingUser() {
User existingUser = aUser(1, "name", "1980-01-01");
User modifiedUser = aUser(1, "newName", "1980-01-30");
when(userService.getUser(anyInt())).thenReturn(Optional.of(existingUser));
when(userService.updateUser(any(User.class))).thenReturn(Optional.of(modifiedUser));
ResponseEntity<UserDTO> response = userManagementService.updateUser("1", aModifiedUser("newName", "1980-01-30"));
assertEquals(OK, response.getStatusCode());
assertEquals("newName", response.getBody().getName());
assertEquals("1980-01-30", response.getBody().getBirthDate().format(DateTimeFormatter.ISO_DATE));
}
@Test(expected = UserNotFoundException.class)
public void shouldReturnNotFound_when_deletingNotExistingUser() {
when(userService.getUser(anyInt())).thenReturn(Optional.empty());
userManagementService.deleteUser("1");
}
@Test(expected = UserBadRequestException.class)
public void shouldReturnBadRequestException_when_deletingUserIdIsNotNumeric() {
userManagementService.deleteUser("zzz");
}
@Test
public void shouldReturnOk_when_deletingExistingUser() {
User userToDelete = aUser(1, "name", "1980-01-01");
when(userService.getUser(anyInt())).thenReturn(Optional.of(userToDelete));
ResponseEntity<UserDTO> response = userManagementService.deleteUser("1");
assertEquals(OK, response.getStatusCode());
}
}
| 6,349 | 0.708931 | 0.691447 | 164 | 37.713413 | 30.308529 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597561 | false | false |
7
|
ab78a7a565191eb638dd28cd0e6f9f0748cf1d99
| 558,345,749,108 |
1f2257c77bdba088d624fa59be8eb8eb6ceafac5
|
/Section08/leetcode_Partition_Labels_kgh.java
|
17f3fd627966fe96435c09d4a67f1d90c093353d
|
[] |
no_license
|
Catch-Study/algorithm-study
|
https://github.com/Catch-Study/algorithm-study
|
07bdeffcc402fb07c729430e6977112840748e08
|
401534bbf76469e0b51afcd8c4bb9cf04aca6b78
|
refs/heads/main
| 2023-04-12T21:41:59.221000 | 2021-04-22T05:50:57 | 2021-04-22T05:50:57 | 310,211,435 | 0 | 0 | null | false | 2021-04-22T05:50:57 | 2020-11-05T06:38:58 | 2021-04-21T11:06:45 | 2021-04-22T05:50:57 | 487 | 0 | 1 | 0 |
Java
| false | false |
package 스터디.스터디_SNU.Section08;
import java.util.*;
/**
* 🔥Amazon CodingInterview🔥
* 1.풀이시간: 초과
* 2.컴퓨팅사고
* (1) 하나의 배열을 만들어서 인덱스값에는 해당 알파벳의 숫자(a일 경우 0, b일경우 1 ...)를 담고 배열의 값에는 인덱스를 담습니다.
* (2)해당 알파벳이 위치해있는 값을 계속 갱신하여 마지막인덱스를 찾아줍니다.
* (3) start,end 포인트점을 하나두어 처음시작값부터 가장 마지막 인덱스에 있는 값을 갱신하여 end에 업데이트 해줍니다.
예시) ababcbacadefegdehijhklij
각 문자별 가지고 있는 배열의 값이 주어졌다고 할때 다음과 같이 배열에 담겨있는것을 확인할 수 있습니다.
ababcbaca defegde hijhklij
---------------------------------------------------------------------------------
a = [0] = 8, b = [1] = 5, c = [2] = 7, d = [3] = 14, e = [4] = 15, f = [5] = 11, g = [6] = 13
h = [7] = 19, i = [8] = 22, j = [9] = 23, k = [10] = 20, l = [11] = 21
---------------------------------------------------------------------------------
a,b 비교 => 8,5 => max = 8
max,c 비교 => 8,7 => max = 8 .....
----------------------------------------------------------------------------------
a부터 진행하면서 Math.max() end인덱스 값을 갱신하면서 어디지점까지 파티션을 나눌 것인지를 확인합니다.
다음과 진행하면서 end값이 문자의 개수 i까지 정확히 도달하였다는것은 파티션으로 나눌 수 있는 의미가 됩니다.
해당 조건에서 파티션의 개수 (end-start+1)를 넣어주고, start의 범위를 end+1 다음파티션 시작점으로 옮겨줍니다.
계속해서 값들을 갱신해나가면서 구해준다면 최종적으로 answer 리스트에는 값들이 모두 담겨있게 될 것입니다.
3.시간복잡도
O(S), S^3일 경우 1억2천 정도이므로 O(S^3) 미만까지 가능
*/
public class leetcode_Partition_Labels_kgh {
public static void main(String[] args) {
partitionLabels("ababcbacadefegdehijhklij");
}
static List<Integer> partitionLabels(String S) {
List<Integer> answer = new ArrayList<>();
// 알파벳 개수만큼 할당. a-z
int[] lastIdx = new int[26];
for(int i=0; i<S.length(); i++){
lastIdx[S.charAt(i)-'a'] = i; // 숫자로 변경
}
int start = 0;
int end = 0;
// 모든 문자에 대해서 확인
for(int i=0; i<S.length(); i++){
// 처음부터 시작하는 모든문자의 마지막 인덱스값의 최댓값을 끝지점으로 설정
end = Math.max(end, lastIdx[S.charAt(i)-'a']);
// 제대로 값이 도달하였으면(그 하위문자들이 모두 포함되는 경우)
if(i == end){
answer.add(end-start+1);
System.out.println(end-start+1);
// 다음 파티션을 처리
start = end+1;
}
}
return answer;
}
}
// 4 , 3, 2 => 9
// 2, 3 , 1 ,1 => 7
// 2,2,2,1,1 => 8
|
UTF-8
|
Java
| 3,141 |
java
|
leetcode_Partition_Labels_kgh.java
|
Java
|
[] | null |
[] |
package 스터디.스터디_SNU.Section08;
import java.util.*;
/**
* 🔥Amazon CodingInterview🔥
* 1.풀이시간: 초과
* 2.컴퓨팅사고
* (1) 하나의 배열을 만들어서 인덱스값에는 해당 알파벳의 숫자(a일 경우 0, b일경우 1 ...)를 담고 배열의 값에는 인덱스를 담습니다.
* (2)해당 알파벳이 위치해있는 값을 계속 갱신하여 마지막인덱스를 찾아줍니다.
* (3) start,end 포인트점을 하나두어 처음시작값부터 가장 마지막 인덱스에 있는 값을 갱신하여 end에 업데이트 해줍니다.
예시) ababcbacadefegdehijhklij
각 문자별 가지고 있는 배열의 값이 주어졌다고 할때 다음과 같이 배열에 담겨있는것을 확인할 수 있습니다.
ababcbaca defegde hijhklij
---------------------------------------------------------------------------------
a = [0] = 8, b = [1] = 5, c = [2] = 7, d = [3] = 14, e = [4] = 15, f = [5] = 11, g = [6] = 13
h = [7] = 19, i = [8] = 22, j = [9] = 23, k = [10] = 20, l = [11] = 21
---------------------------------------------------------------------------------
a,b 비교 => 8,5 => max = 8
max,c 비교 => 8,7 => max = 8 .....
----------------------------------------------------------------------------------
a부터 진행하면서 Math.max() end인덱스 값을 갱신하면서 어디지점까지 파티션을 나눌 것인지를 확인합니다.
다음과 진행하면서 end값이 문자의 개수 i까지 정확히 도달하였다는것은 파티션으로 나눌 수 있는 의미가 됩니다.
해당 조건에서 파티션의 개수 (end-start+1)를 넣어주고, start의 범위를 end+1 다음파티션 시작점으로 옮겨줍니다.
계속해서 값들을 갱신해나가면서 구해준다면 최종적으로 answer 리스트에는 값들이 모두 담겨있게 될 것입니다.
3.시간복잡도
O(S), S^3일 경우 1억2천 정도이므로 O(S^3) 미만까지 가능
*/
public class leetcode_Partition_Labels_kgh {
public static void main(String[] args) {
partitionLabels("ababcbacadefegdehijhklij");
}
static List<Integer> partitionLabels(String S) {
List<Integer> answer = new ArrayList<>();
// 알파벳 개수만큼 할당. a-z
int[] lastIdx = new int[26];
for(int i=0; i<S.length(); i++){
lastIdx[S.charAt(i)-'a'] = i; // 숫자로 변경
}
int start = 0;
int end = 0;
// 모든 문자에 대해서 확인
for(int i=0; i<S.length(); i++){
// 처음부터 시작하는 모든문자의 마지막 인덱스값의 최댓값을 끝지점으로 설정
end = Math.max(end, lastIdx[S.charAt(i)-'a']);
// 제대로 값이 도달하였으면(그 하위문자들이 모두 포함되는 경우)
if(i == end){
answer.add(end-start+1);
System.out.println(end-start+1);
// 다음 파티션을 처리
start = end+1;
}
}
return answer;
}
}
// 4 , 3, 2 => 9
// 2, 3 , 1 ,1 => 7
// 2,2,2,1,1 => 8
| 3,141 | 0.481749 | 0.445246 | 64 | 33.6875 | 25.695253 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703125 | false | false |
7
|
5d0d1aa52f03b1416870e6f57e698bd673a5a289
| 10,273,561,801,243 |
99aa1b050bdb3f1dc645a00651c4318ee0c21e2b
|
/src/business/PurchaseRequestDB.java
|
5f94baa685b313b42eeed676cbfd4103f8dc7e6e
|
[] |
no_license
|
sean-blessing/jpa_demo
|
https://github.com/sean-blessing/jpa_demo
|
25c73169919dc5eebfa4bd116a4a5eac52e421ff
|
a2578acad5c79dade3e6644ffed0d651d633617c
|
refs/heads/master
| 2022-12-17T10:02:09.731000 | 2020-09-03T18:18:58 | 2020-09-03T18:18:58 | 112,395,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package business;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import db.DBUtil;
public class PurchaseRequestDB {
public static PurchaseRequest getPRById(int prId) {
EntityManager em = DBUtil.getEmFactory().createEntityManager();
PurchaseRequest pr = null;
try {
pr = em.find(PurchaseRequest.class, prId);
}
finally {
em.close();
}
return pr;
}
public static boolean addPurchaseRequest(PurchaseRequest pr){
boolean success = false;
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction et = em.getTransaction();
try {
et.begin();
em.persist(pr);
et.commit();
success = true;
}
catch (Exception e) {
e.printStackTrace();
et.rollback();
}
finally {
em.close();
}
return success;
}
public static boolean updatePurchaseRequest(PurchaseRequest pr){
boolean success = false;
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction et = em.getTransaction();
try {
et.begin();
em.merge(pr);
et.commit();
success = true;
}
catch (Exception e) {
e.printStackTrace();
et.rollback();
}
finally {
em.close();
}
return success;
}
public static boolean addPurchaseRequestLineItems(ArrayList<PurchaseRequestLineItem> prlis){
boolean success = false;
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction et = em.getTransaction();
try {
et.begin();
// insert prlis
for (PurchaseRequestLineItem prli:prlis) {
//prli.setPurchaseRequestID(pr.getId()); --> should already be done in app
em.persist(prli);
}
et.commit();
success = true;
}
catch (Exception e) {
e.printStackTrace();
et.rollback();
}
finally {
em.close();
}
return success;
}
}
|
UTF-8
|
Java
| 1,957 |
java
|
PurchaseRequestDB.java
|
Java
|
[] | null |
[] |
package business;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import db.DBUtil;
public class PurchaseRequestDB {
public static PurchaseRequest getPRById(int prId) {
EntityManager em = DBUtil.getEmFactory().createEntityManager();
PurchaseRequest pr = null;
try {
pr = em.find(PurchaseRequest.class, prId);
}
finally {
em.close();
}
return pr;
}
public static boolean addPurchaseRequest(PurchaseRequest pr){
boolean success = false;
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction et = em.getTransaction();
try {
et.begin();
em.persist(pr);
et.commit();
success = true;
}
catch (Exception e) {
e.printStackTrace();
et.rollback();
}
finally {
em.close();
}
return success;
}
public static boolean updatePurchaseRequest(PurchaseRequest pr){
boolean success = false;
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction et = em.getTransaction();
try {
et.begin();
em.merge(pr);
et.commit();
success = true;
}
catch (Exception e) {
e.printStackTrace();
et.rollback();
}
finally {
em.close();
}
return success;
}
public static boolean addPurchaseRequestLineItems(ArrayList<PurchaseRequestLineItem> prlis){
boolean success = false;
EntityManager em = DBUtil.getEmFactory().createEntityManager();
EntityTransaction et = em.getTransaction();
try {
et.begin();
// insert prlis
for (PurchaseRequestLineItem prli:prlis) {
//prli.setPurchaseRequestID(pr.getId()); --> should already be done in app
em.persist(prli);
}
et.commit();
success = true;
}
catch (Exception e) {
e.printStackTrace();
et.rollback();
}
finally {
em.close();
}
return success;
}
}
| 1,957 | 0.684211 | 0.6837 | 95 | 19.6 | 20.997444 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.463158 | false | false |
7
|
cb42b0b232a6e09bf0403c6a42af099282120e0a
| 962,072,745,349 |
02c13987c8e42419167b4686096112350c9e90ed
|
/TiJOSApp/OneNetApplication/src/net/tijos/gas/base/modules/SmokeDetector.java
|
b3f77019bd35be28bc6a22e46841beb56629ab17
|
[] |
no_license
|
LoneGunnerMe/tijos-mqtt-onenet-iot
|
https://github.com/LoneGunnerMe/tijos-mqtt-onenet-iot
|
9c8e4308cd2628c71b3d515630b7223d49e1a01b
|
7a6fb8ee9a3a9797f75bdf2f199396151ddf3610
|
refs/heads/master
| 2020-04-11T16:17:24.025000 | 2018-05-30T00:36:37 | 2018-05-30T00:36:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.tijos.gas.base.modules;
import java.io.IOException;
import net.tijos.gas.base.Collector;
import net.tijos.gas.base.Listener;
import net.tijos.gas.base.Module;
/**
* ÑÌÎí±¨¾¯Æ÷³éÏóÀà
* @author Mars
*
*/
public abstract class SmokeDetector extends Collector {
public interface AlarmListener extends Listener {
void onAlarm(Module m);
void onRecovery(Module m);
}
public SmokeDetector(int id, String name) {
super(id, name);
}
public abstract boolean isReady();
public abstract void setAlarmListener(AlarmListener l) throws IOException;
public abstract boolean isAlarm() throws IOException;
}
|
WINDOWS-1252
|
Java
| 652 |
java
|
SmokeDetector.java
|
Java
|
[
{
"context": "s.base.Module;\n\n/**\n * ÑÌÎí±¨¾¯Æ÷³éÏóÀà\n * @author Mars \n *\n */\npublic abstract class SmokeDetector exten",
"end": 213,
"score": 0.9995152354240417,
"start": 209,
"tag": "NAME",
"value": "Mars"
}
] | null |
[] |
package net.tijos.gas.base.modules;
import java.io.IOException;
import net.tijos.gas.base.Collector;
import net.tijos.gas.base.Listener;
import net.tijos.gas.base.Module;
/**
* ÑÌÎí±¨¾¯Æ÷³éÏóÀà
* @author Mars
*
*/
public abstract class SmokeDetector extends Collector {
public interface AlarmListener extends Listener {
void onAlarm(Module m);
void onRecovery(Module m);
}
public SmokeDetector(int id, String name) {
super(id, name);
}
public abstract boolean isReady();
public abstract void setAlarmListener(AlarmListener l) throws IOException;
public abstract boolean isAlarm() throws IOException;
}
| 652 | 0.743711 | 0.740566 | 32 | 18.875 | 20.749624 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
7
|
abd978da54054f4a9e7024ca71ed533e9757d81e
| 31,456,340,513,647 |
964148c9179b093544cf8e40fc9914ba503d9c3b
|
/Session4.3/src/controllers/ControllerController.java
|
238918a32e8945b23286e81eae4e32f5889e8446
|
[] |
no_license
|
lehuyduc/HuyDuc-techkids-android6
|
https://github.com/lehuyduc/HuyDuc-techkids-android6
|
4c2b23a0b9cd6976e76ab5ecb1147421c82ab2f4
|
f75e74db900f5306a0413907d4fa0bf510b2fce0
|
refs/heads/master
| 2021-01-11T08:15:08.896000 | 2016-10-26T12:28:04 | 2016-10-26T12:28:04 | 69,803,605 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package controllers;
import controllers.Enemy.EnemyPlaneControllerManager;
import java.awt.*;
/**
* Created by Le Huy Duc on 13/10/2016.
*/
public class ControllerController {
private ControllerController() {
}
public synchronized void draw(Graphics g) {
PlaneController.instance1.draw(g);
PlaneController.instance2.draw(g);
EnemyPlaneControllerManager.instance.draw(g);
ExplosionControllerManager.instance.draw(g);
CollisionManager.instance.draw(g);
}
public synchronized void run() {
PlaneController.instance1.run();
PlaneController.instance2.run();
EnemyPlaneControllerManager.instance.run();
ExplosionControllerManager.instance.run();
CollisionManager.instance.run();
}
public static final ControllerController instance = new ControllerController();
}
|
UTF-8
|
Java
| 874 |
java
|
ControllerController.java
|
Java
|
[
{
"context": "lerManager;\n\nimport java.awt.*;\n\n/**\n * Created by Le Huy Duc on 13/10/2016.\n */\npublic class ControllerControl",
"end": 125,
"score": 0.9996696710586548,
"start": 115,
"tag": "NAME",
"value": "Le Huy Duc"
}
] | null |
[] |
package controllers;
import controllers.Enemy.EnemyPlaneControllerManager;
import java.awt.*;
/**
* Created by <NAME> on 13/10/2016.
*/
public class ControllerController {
private ControllerController() {
}
public synchronized void draw(Graphics g) {
PlaneController.instance1.draw(g);
PlaneController.instance2.draw(g);
EnemyPlaneControllerManager.instance.draw(g);
ExplosionControllerManager.instance.draw(g);
CollisionManager.instance.draw(g);
}
public synchronized void run() {
PlaneController.instance1.run();
PlaneController.instance2.run();
EnemyPlaneControllerManager.instance.run();
ExplosionControllerManager.instance.run();
CollisionManager.instance.run();
}
public static final ControllerController instance = new ControllerController();
}
| 870 | 0.703661 | 0.689931 | 33 | 25.484848 | 22.920311 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424242 | false | false |
7
|
f9832d31586c6dd2294b16a1882f7918ad0b8966
| 5,514,738,049,385 |
d5aea50d0da58263c5105bd2248b997696a0c515
|
/domains/MemberBeanTest.java
|
661134987daed628799cd3de33c045e1603ed8c3
|
[] |
no_license
|
yejee1228/java-oop
|
https://github.com/yejee1228/java-oop
|
0869e64b1028e378299f493c5588dcf16cb40f3d
|
72b5f68344cc48fcf462596fcf38ff73bd6ce9a1
|
refs/heads/master
| 2020-07-08T19:47:14.030000 | 2019-08-26T11:51:30 | 2019-08-26T11:51:30 | 203,759,899 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bitcamp.domains;
public class MemberBeanTest {
private String name, id, pw, birth;
private double height, weight;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getPw() {
return pw;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getBirth() {
return birth;
}
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return height;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
@Override
public String toString() {
return String.format("[회원정보]\n"
+ "이름: %s \n"
+ "id: %s \n"
+ "pw: %s \n"
+ "생년월일: %s \n"
+ "키: %f \n"
+ "몸무게: %f \n", name, id, pw, birth, height, weight);
}
}
|
UTF-8
|
Java
| 1,016 |
java
|
MemberBeanTest.java
|
Java
|
[] | null |
[] |
package com.bitcamp.domains;
public class MemberBeanTest {
private String name, id, pw, birth;
private double height, weight;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getPw() {
return pw;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getBirth() {
return birth;
}
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return height;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
@Override
public String toString() {
return String.format("[회원정보]\n"
+ "이름: %s \n"
+ "id: %s \n"
+ "pw: %s \n"
+ "생년월일: %s \n"
+ "키: %f \n"
+ "몸무게: %f \n", name, id, pw, birth, height, weight);
}
}
| 1,016 | 0.623482 | 0.623482 | 53 | 17.64151 | 13.250979 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
7
|
d35d984715353b57d2b6973404d761555f212f4b
| 14,680,198,250,919 |
73899aaa0d74dc9e7766085ff81b8791ba6e7d56
|
/src/test/java/com/sen/test/user/TestUpdateUserDetail.java
|
34d2e0125f1e681bb33eda0554372bc26dc1a579
|
[] |
no_license
|
senthilgdr/SenTask-Core
|
https://github.com/senthilgdr/SenTask-Core
|
ea713f4ab7b9f44a9c1b4f6525ad3e2a0387bae8
|
f86f72b4218ab797351eea2a75e67ac7c5081301
|
refs/heads/master
| 2021-01-12T06:01:40.490000 | 2016-12-24T13:04:04 | 2016-12-24T13:04:04 | 77,279,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sen.test.user;
import com.sen.dao.UserDetailDAO;
import com.sen.dao.impl.UserDetailDAOJdbcImpl;
import com.sen.view.UserDetail;
import com.sen.view.UserType;
public class TestUpdateUserDetail {
public static void main(String[] args) throws Exception {
UserDetail ud = new UserDetailDAOJdbcImpl().findByOne(Long.valueOf(61));
ud.setName("Senthil");
ud.setUserName("senthilkumar");
ud.setPassWord("admin");
ud.setEmailId("kaja@gmail.com");
UserType ut = new UserType();
ut.setUserTypeId(Long.valueOf(1));
ud.setUserType(ut);
ud.setCreatedBy(Long.valueOf(1));
UserDetailDAO dao1 = new UserDetailDAOJdbcImpl();
dao1.update(ud);
System.out.println("Updated:" + dao1);
}
}
|
UTF-8
|
Java
| 715 |
java
|
TestUpdateUserDetail.java
|
Java
|
[
{
"context": "mpl().findByOne(Long.valueOf(61));\n\n\t\tud.setName(\"Senthil\");\n\t\tud.setUserName(\"senthilkumar\");\n\t\tud.setPass",
"end": 366,
"score": 0.9981125593185425,
"start": 359,
"tag": "NAME",
"value": "Senthil"
},
{
"context": "61));\n\n\t\tud.setName(\"Senthil\");\n\t\tud.setUserName(\"senthilkumar\");\n\t\tud.setPassWord(\"admin\");\n\t\tud.setEmailId(\"ka",
"end": 400,
"score": 0.9996627569198608,
"start": 388,
"tag": "USERNAME",
"value": "senthilkumar"
},
{
"context": "ud.setUserName(\"senthilkumar\");\n\t\tud.setPassWord(\"admin\");\n\t\tud.setEmailId(\"kaja@gmail.com\");\n\n\t\tUserType",
"end": 427,
"score": 0.9992069602012634,
"start": 422,
"tag": "PASSWORD",
"value": "admin"
},
{
"context": "ar\");\n\t\tud.setPassWord(\"admin\");\n\t\tud.setEmailId(\"kaja@gmail.com\");\n\n\t\tUserType ut = new UserType();\n\t\tut.setUserT",
"end": 462,
"score": 0.9999203085899353,
"start": 448,
"tag": "EMAIL",
"value": "kaja@gmail.com"
}
] | null |
[] |
package com.sen.test.user;
import com.sen.dao.UserDetailDAO;
import com.sen.dao.impl.UserDetailDAOJdbcImpl;
import com.sen.view.UserDetail;
import com.sen.view.UserType;
public class TestUpdateUserDetail {
public static void main(String[] args) throws Exception {
UserDetail ud = new UserDetailDAOJdbcImpl().findByOne(Long.valueOf(61));
ud.setName("Senthil");
ud.setUserName("senthilkumar");
ud.setPassWord("<PASSWORD>");
ud.setEmailId("<EMAIL>");
UserType ut = new UserType();
ut.setUserTypeId(Long.valueOf(1));
ud.setUserType(ut);
ud.setCreatedBy(Long.valueOf(1));
UserDetailDAO dao1 = new UserDetailDAOJdbcImpl();
dao1.update(ud);
System.out.println("Updated:" + dao1);
}
}
| 713 | 0.734266 | 0.724476 | 31 | 22.064516 | 20.165342 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.387097 | false | false |
7
|
db4c07fd536312aea81cd61908bdae16b14e033b
| 3,023,657,014,380 |
bbbf6604350d64623fc72f227641ec36268e43d7
|
/src/com/annot/gui/MyCanvas3D.java
|
b61965a36da802c06cb61c16eec90065f32d3dc2
|
[
"BSD-2-Clause"
] |
permissive
|
vdel/RoomAnnotTool
|
https://github.com/vdel/RoomAnnotTool
|
c455e0c17fcd820a8d74c72db8bbd867a56b46e5
|
c3f5b0f307aac267e0c89d502f4118bec7ca9a30
|
refs/heads/master
| 2021-01-01T06:05:40.330000 | 2014-11-07T14:09:15 | 2014-11-07T14:09:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.annot.gui;
import Jama.Matrix;
import com.annot.gui.MyBox3D.J3DBox;
import com.annot.room.ObjectInstance.NoSupportFaceException;
import com.annot.room.ObjectManager.FaceType;
import com.annot.room.Room.NoSuchObjectException;
import com.annot.room.RoomParameters;
import com.pose.Pose3DVisu;
import com.sun.j3d.utils.picking.PickCanvas;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.PickTool;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.universe.ViewInfo;
import com.sun.j3d.utils.universe.ViewingPlatform;
import com.common.J3DHelper;
import com.common.MyMatrix;
import com.common.MyVect;
import com.sun.j3d.utils.geometry.Primitive;
import com.sun.j3d.utils.geometry.Sphere;
import java.awt.Color;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Vector;
import javax.media.j3d.Background;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.Node;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.media.j3d.View;
import javax.media.j3d.ViewPlatform;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3f;
/**
*
* @author vdelaitr
*/
public class MyCanvas3D extends Canvas3D implements DropTargetListener {
public interface MyCanvas3DListener {
void setModified(ObjectInstance3D object);
void objectSelected(ObjectInstance3D object);
void objectDeselected(ObjectInstance3D object);
}
static final long serialVersionUID = 0L;
private Room3D room;
private SimpleUniverse universe;
private BranchGroup rootGroup;
private TransformGroup rootTransform;
private TransformGroup floorTransform;
private BranchGroup cloudGroup;
private boolean cloudVisible;
private MyBehavior behavior;
private View view;
private ViewInfo viewInfo;
private MyPanel panel;
private PickCanvas pickCanvas;
private ObjectInstance3D object;
private Shape3D attachedShape;
private ConstrainedMotion motion;
private LinkedList<MyCanvas3DListener> listeners;
private LinkedList<BranchGroup> poses;
private Canvas3D offscreen;
static public class MyPickResult {
MyBox3D box;
Shape3D shape;
MyPickResult(MyBox3D b, Shape3D s) {
box = b;
shape = s;
}
static MyPickResult pick(PickCanvas pc, ObjectInstance3D currentObject, int x, int y) {
try {
pc.setShapeLocation(x, y);
PickResult[] result = pc.pickAllSorted();
if (result != null) {
for (int i = 0; i < result.length; i++) {
Node n = result[i].getNode(PickResult.PRIMITIVE);
if (n.getClass().isAssignableFrom(J3DBox.class)) {
MyBox3D b = ((J3DBox)n).me;
Shape3D s = (Shape3D) result[i].getNode(PickResult.SHAPE3D);
if (b != null && s != null) {
ObjectInstance3D o = b.getParentObject();
if (o != currentObject) {
return new MyPickResult(b, s);
}
}
}
}
return null;
} else {
return null;
}
} catch (NullPointerException e) {
return null;
}
}
};
public MyCanvas3D(Room3D r, MyPanel p) {
super(SimpleUniverse.getPreferredConfiguration());
room = r;
panel = p;
attachedShape = null;
motion = null;
listeners = new LinkedList<MyCanvas3DListener>();
poses = new LinkedList<BranchGroup>();
// initialize universe
createUniverse();
// Set mouse and keyboard
createBehaviourInteractors(room);
// Centrate floor center on origin
Transform3D t = new Transform3D();
t.setTranslation(new MyVect(-room.getParams().depth / 2,
-room.getParams().width / 2, 0));
floorTransform.setTransform(t);
room.getFloor().branchGroupAttach(floorTransform);
// Set up point cloud
if (room.getCloud() != null) {
RoomParameters params = room.getParams();
Vector<MyVect> cloud = room.getCloud();
BufferedImage image = room.getImage().getImage();
for (int i = 0; i < room.getCloud().size(); i += 16) {
MyVect vpos = params.K.mul(params.R.mul(cloud.get(i)).add(params.t));
Point pos = room.getImage().directToImageCoord(vpos).toPoint();
Color3f color;
if (0 <= pos.x && pos.x < room.getImage().getWidth() &&
0 <= pos.y && pos.y < room.getImage().getHeight()) {
color = new Color3f(new Color(image.getRGB(pos.x, pos.y)));
}
else {
color = new Color3f(1.f, 1.f, 1.f);
}
t = new Transform3D();
t.setTranslation(cloud.get(i));
TransformGroup tg = J3DHelper.newTransformGroup(t);
tg.addChild(new Sphere(0.025f, Primitive.GENERATE_NORMALS,
4, J3DHelper.getDefaultAppearance(color)));
cloudGroup.addChild(tg);
}
}
floorTransform.addChild(cloudGroup);
cloudVisible = true;
// Attach to universe
universe.addBranchGraph(rootGroup);
// Add offscreen canvas for rendering
offscreen = new Canvas3D(SimpleUniverse.getPreferredConfiguration(), true);
}
public void close() {
super.stopRenderer();
behavior.clear();
universe.getViewingPlatform().detach();
rootGroup.detach();
rootGroup = null;
rootTransform = null;
floorTransform = null;
cloudGroup = null;
behavior = null;
view = null;
viewInfo = null;
panel = null;
pickCanvas = null;
if (object != null) {
object.clear();
}
object = null;
attachedShape = null;
motion = null;
listeners = null;
poses = null;
universe.cleanup();
universe = null;
}
public Canvas3D getOffscrenCanvas() {
offscreen.getScreen3D().setSize(getScreen3D().getSize());
offscreen.getScreen3D().setPhysicalScreenWidth(
getScreen3D().getPhysicalScreenWidth());
offscreen.getScreen3D().setPhysicalScreenHeight(
getScreen3D().getPhysicalScreenHeight());
offscreen.setOffScreenLocation(getLocation());
offscreen.setSize(getWidth(), getHeight());
return offscreen;
}
private void createUniverse() {
universe = new SimpleUniverse(this);
view = universe.getViewer().getView();
//view.setCompatibilityModeEnable(true);
viewInfo = new ViewInfo(view, ViewInfo.PLATFORM_AUTO_UPDATE
| ViewInfo.CANVAS_AUTO_UPDATE);
if (view.getCompatibilityModeEnable()) {
Transform3D t = new Transform3D();
viewInfo.getViewPlatformToEye(this, t, null);
view.setVpcToEc(t);
}
ViewingPlatform viewingPlatform = universe.getViewingPlatform();
ViewPlatform vp = viewingPlatform.getViewPlatform();
viewingPlatform.detach();
vp.setCapability(ViewPlatform.ALLOW_POLICY_READ);
vp.setCapability(Node.ALLOW_LOCAL_TO_VWORLD_READ);
universe.addBranchGraph(viewingPlatform);
rootGroup = J3DHelper.newBranchGroup();
rootTransform = J3DHelper.newTransformGroup();
floorTransform = J3DHelper.newTransformGroup();
cloudGroup = J3DHelper.newBranchGroup();
rootGroup.addChild(rootTransform);
rootTransform.addChild(floorTransform);
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), Double.POSITIVE_INFINITY);
// Light 1
DirectionalLight light = new DirectionalLight(new Color3f(1f, 1f, 1f), new Vector3f(-4.0f, -7.0f, -12.0f));
light.setInfluencingBounds(bounds);
floorTransform.addChild(light);
// Light 2
light = new DirectionalLight(new Color3f(1f, 1f, 1f), new Vector3f(8.0f, 9.0f, 2.0f));
light.setInfluencingBounds(bounds);
floorTransform.addChild(light);
// Background
Background back = new Background(0.57f, 0.66f, 1f);
back.setApplicationBounds(bounds);
rootGroup.addChild(back);
}
private void createBehaviourInteractors(Room3D room) {
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), Double.POSITIVE_INFINITY);
behavior = new MyBehavior(room, this, rootTransform);
behavior.setSchedulingBounds(bounds);
rootGroup.addChild(behavior);
}
public void togglePointCloud() {
if (cloudVisible) {
cloudGroup.detach();
cloudVisible = false;
}
else {
floorTransform.addChild(cloudGroup);
cloudVisible = true;
}
}
public void setPickTool() {
pickCanvas = new PickCanvas(this, room.getFloor().getBranchGroup());
pickCanvas.setMode(PickTool.GEOMETRY_INTERSECT_INFO);
pickCanvas.setTolerance(0f);
}
public void addMyCanvas3DListener(MyCanvas3DListener l) {
listeners.add(l);
}
public void removeMyCanvas3DListener(MyCanvas3DListener l) {
listeners.remove(l);
}
void setModified(ObjectInstance3D object) {
if (panel != null) { // panel may be null for 3D visualization only
object.drawOnPanel(panel, room);
}
for (MyCanvas3DListener l : listeners) {
l.setModified(object);
}
}
void objectSelected(ObjectInstance3D object) {
if (panel != null) { // panel may be null for 3D visualization only
object.drawOnPanel(panel, room);
}
if (!object.isPrivate()) {
for (MyCanvas3DListener l : listeners) {
l.objectSelected(object);
}
}
}
void objectDeselected(ObjectInstance3D object) {
if (panel != null) { // panel may be null for 3D visualization only
panel.clearLines();
panel.repaint();
}
for (MyCanvas3DListener l : listeners) {
l.objectDeselected(object);
}
}
@Override
public void dragEnter(DropTargetDragEvent dtde) {
if (behavior.selectedBox != null) {
behavior.deselect();
}
try {
if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String name = (String) dtde.getTransferable().getTransferData(DataFlavor.stringFlavor);
try {
object = room.newObject(name);
object.select();
} catch (NoSuchObjectException e) {
dtde.rejectDrag();
}
} else {
dtde.rejectDrag();
}
} catch (IOException e) {
dtde.rejectDrag();
} catch (UnsupportedFlavorException e) {
dtde.rejectDrag();
}
}
@Override
public void dragExit(DropTargetEvent dte) {
detach();
object.clear();
object = null;
}
@Override
public void dragOver(DropTargetDragEvent dtde) {
MyPickResult r = pick(dtde.getLocation().x, dtde.getLocation().y);
if (r == null) {
dtde.rejectDrag();
detach();
} else if (attachedShape == null || attachedShape != r.shape) {
FaceType ft = r.box.getFaceType(r.shape);
if ((r.box.getParentObject().isFloor() && ft != FaceType.TOP)
|| (r.box.getParentObject().isWall() &&
r.box.getParentObject().isPrivate() &&
ft != FaceType.FRONT)
|| (r.box.getParentObject().isWall() &&
!r.box.getParentObject().isPrivate() &&
(ft == FaceType.TOP || ft == FaceType.BOTTOM))
|| (r.box.getParentObject().isCeiling() &&
ft != FaceType.BOTTOM)) {
dtde.rejectDrag();
detach();
} else {
try {
FaceType suppf = object.getSupportForAttach(ft);
dtde.acceptDrag(dtde.getDropAction());
MyVect ray = getRay(dtde.getLocation().x, dtde.getLocation().y);
MyVect p = r.box.getIntersection(ft, behavior.getCameraPos(), ray, true);
if (attachedShape != r.shape) {
object.detach();
}
attachedShape = r.shape;
object.attachTo(r.box, ft);
object.setFacePosition(p.x, p.y);
p = r.box.getIntersection(ft, behavior.getCameraPos(), ray);
motion = object.getMotion(p, null); // 2nd argument won't be used
} catch (NoSupportFaceException e) {
dtde.rejectDrag();
detach();
}
}
} else if (motion != null) {
MyVect ray = getRay(dtde.getLocation().x, dtde.getLocation().y);
motion.update(behavior.getCameraPos(), ray);
if (panel != null) { // panel may be null for 3D visualization only
object.drawOnPanel(panel, room);
}
}
}
@Override
public void drop(DropTargetDropEvent dtde) {
if (object != null) {
setModified(object);
requestFocus();
} else if (panel != null) { // panel may be null for 3D visualization only
panel.clearLines();
panel.repaint();
}
object = null;
motion = null;
}
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
detach();
}
MyPickResult pick(int x, int y) {
return MyPickResult.pick(pickCanvas, object, x, y);
}
void detach() {
if (attachedShape != null) {
object.detach();
if (panel != null) { // panel may be null for 3D visualization only
panel.clearLines();
panel.repaint();
}
attachedShape = null;
motion = null;
}
}
public void removeSelectedObject() {
behavior.removeSelectedObject();
}
MyVect getRay(int x, int y) {
Point3d eyePos = new Point3d();
Point3d mousePos = new Point3d();
getCenterEyeInImagePlate(eyePos);
getPixelLocationInImagePlate(x, y, mousePos);
Transform3D screen2cam = new Transform3D();
getImagePlateToVworld(screen2cam);
MyVect v = new MyVect();
v.sub(mousePos, eyePos);
MyMatrix rot = new MyMatrix();
J3DHelper.extractRotTrans(screen2cam, rot, null, null);
v = behavior.getInvR().mul(rot.mul(v));
return v;
}
public void setDefaultView(RoomParameters params) {
Transform3D t = new Transform3D();
double fovx = 1 / room.getParams().fx;
double aspect = ((double) room.getImage().getWidth()) / room.getImage().getHeight();
double znear = 0.001;
double zfar = 1000;
double alpha = (zfar - znear) / (2 * znear * zfar);
double beta = (zfar + znear) / (2 * znear * zfar);
view.setFieldOfView(Math.atan(fovx) * 2);
view.setFrontClipDistance(znear);
view.setBackClipDistance(zfar);
if (view.getCompatibilityModeEnable()) {
Matrix P = new Matrix(4, 4);
P.set(0, 0, fovx);
P.set(1, 1, fovx / aspect * room.getParams().fx / room.getParams().fy);
//P.set(0, 1, f * room.params.g);
P.set(2, 2, 1);
P.set(3, 2, alpha);
P.set(3, 3, beta);
P = P.inverse();
t.set(P.getRowPackedCopy());
view.setLeftProjection(t);
view.setRightProjection(t);
double[] c = new double[16];
viewInfo.getEyeToImagePlate(this, t, null);
t.get(c);
setLeftManualEyeInImagePlate(new Point3d(c[3], c[7], c[11]));
setRightManualEyeInImagePlate(new Point3d(c[3], c[7], c[11]));
}
behavior.setRotation(params.cameraAngle);
behavior.setCameraPos(params.cameraPosition);
}
public MyBehavior getBehavior() {
return behavior;
}
public void addPose(double[] pose) {
Pose3DVisu p = new Pose3DVisu(pose);
floorTransform.addChild(p.getBranchGroup());
poses.add(p.getBranchGroup());
}
public void clearPoses() {
for (BranchGroup bg : poses) {
bg.detach();
}
poses.clear();
}
}
|
UTF-8
|
Java
| 17,962 |
java
|
MyCanvas3D.java
|
Java
|
[
{
"context": "\nimport javax.vecmath.Vector3f;\n\n/**\n *\n * @author vdelaitr\n */\npublic class MyCanvas3D extends Canvas3D impl",
"end": 1778,
"score": 0.999428391456604,
"start": 1770,
"tag": "USERNAME",
"value": "vdelaitr"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.annot.gui;
import Jama.Matrix;
import com.annot.gui.MyBox3D.J3DBox;
import com.annot.room.ObjectInstance.NoSupportFaceException;
import com.annot.room.ObjectManager.FaceType;
import com.annot.room.Room.NoSuchObjectException;
import com.annot.room.RoomParameters;
import com.pose.Pose3DVisu;
import com.sun.j3d.utils.picking.PickCanvas;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.PickTool;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.universe.ViewInfo;
import com.sun.j3d.utils.universe.ViewingPlatform;
import com.common.J3DHelper;
import com.common.MyMatrix;
import com.common.MyVect;
import com.sun.j3d.utils.geometry.Primitive;
import com.sun.j3d.utils.geometry.Sphere;
import java.awt.Color;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Vector;
import javax.media.j3d.Background;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.Node;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.media.j3d.View;
import javax.media.j3d.ViewPlatform;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3f;
/**
*
* @author vdelaitr
*/
public class MyCanvas3D extends Canvas3D implements DropTargetListener {
public interface MyCanvas3DListener {
void setModified(ObjectInstance3D object);
void objectSelected(ObjectInstance3D object);
void objectDeselected(ObjectInstance3D object);
}
static final long serialVersionUID = 0L;
private Room3D room;
private SimpleUniverse universe;
private BranchGroup rootGroup;
private TransformGroup rootTransform;
private TransformGroup floorTransform;
private BranchGroup cloudGroup;
private boolean cloudVisible;
private MyBehavior behavior;
private View view;
private ViewInfo viewInfo;
private MyPanel panel;
private PickCanvas pickCanvas;
private ObjectInstance3D object;
private Shape3D attachedShape;
private ConstrainedMotion motion;
private LinkedList<MyCanvas3DListener> listeners;
private LinkedList<BranchGroup> poses;
private Canvas3D offscreen;
static public class MyPickResult {
MyBox3D box;
Shape3D shape;
MyPickResult(MyBox3D b, Shape3D s) {
box = b;
shape = s;
}
static MyPickResult pick(PickCanvas pc, ObjectInstance3D currentObject, int x, int y) {
try {
pc.setShapeLocation(x, y);
PickResult[] result = pc.pickAllSorted();
if (result != null) {
for (int i = 0; i < result.length; i++) {
Node n = result[i].getNode(PickResult.PRIMITIVE);
if (n.getClass().isAssignableFrom(J3DBox.class)) {
MyBox3D b = ((J3DBox)n).me;
Shape3D s = (Shape3D) result[i].getNode(PickResult.SHAPE3D);
if (b != null && s != null) {
ObjectInstance3D o = b.getParentObject();
if (o != currentObject) {
return new MyPickResult(b, s);
}
}
}
}
return null;
} else {
return null;
}
} catch (NullPointerException e) {
return null;
}
}
};
public MyCanvas3D(Room3D r, MyPanel p) {
super(SimpleUniverse.getPreferredConfiguration());
room = r;
panel = p;
attachedShape = null;
motion = null;
listeners = new LinkedList<MyCanvas3DListener>();
poses = new LinkedList<BranchGroup>();
// initialize universe
createUniverse();
// Set mouse and keyboard
createBehaviourInteractors(room);
// Centrate floor center on origin
Transform3D t = new Transform3D();
t.setTranslation(new MyVect(-room.getParams().depth / 2,
-room.getParams().width / 2, 0));
floorTransform.setTransform(t);
room.getFloor().branchGroupAttach(floorTransform);
// Set up point cloud
if (room.getCloud() != null) {
RoomParameters params = room.getParams();
Vector<MyVect> cloud = room.getCloud();
BufferedImage image = room.getImage().getImage();
for (int i = 0; i < room.getCloud().size(); i += 16) {
MyVect vpos = params.K.mul(params.R.mul(cloud.get(i)).add(params.t));
Point pos = room.getImage().directToImageCoord(vpos).toPoint();
Color3f color;
if (0 <= pos.x && pos.x < room.getImage().getWidth() &&
0 <= pos.y && pos.y < room.getImage().getHeight()) {
color = new Color3f(new Color(image.getRGB(pos.x, pos.y)));
}
else {
color = new Color3f(1.f, 1.f, 1.f);
}
t = new Transform3D();
t.setTranslation(cloud.get(i));
TransformGroup tg = J3DHelper.newTransformGroup(t);
tg.addChild(new Sphere(0.025f, Primitive.GENERATE_NORMALS,
4, J3DHelper.getDefaultAppearance(color)));
cloudGroup.addChild(tg);
}
}
floorTransform.addChild(cloudGroup);
cloudVisible = true;
// Attach to universe
universe.addBranchGraph(rootGroup);
// Add offscreen canvas for rendering
offscreen = new Canvas3D(SimpleUniverse.getPreferredConfiguration(), true);
}
public void close() {
super.stopRenderer();
behavior.clear();
universe.getViewingPlatform().detach();
rootGroup.detach();
rootGroup = null;
rootTransform = null;
floorTransform = null;
cloudGroup = null;
behavior = null;
view = null;
viewInfo = null;
panel = null;
pickCanvas = null;
if (object != null) {
object.clear();
}
object = null;
attachedShape = null;
motion = null;
listeners = null;
poses = null;
universe.cleanup();
universe = null;
}
public Canvas3D getOffscrenCanvas() {
offscreen.getScreen3D().setSize(getScreen3D().getSize());
offscreen.getScreen3D().setPhysicalScreenWidth(
getScreen3D().getPhysicalScreenWidth());
offscreen.getScreen3D().setPhysicalScreenHeight(
getScreen3D().getPhysicalScreenHeight());
offscreen.setOffScreenLocation(getLocation());
offscreen.setSize(getWidth(), getHeight());
return offscreen;
}
private void createUniverse() {
universe = new SimpleUniverse(this);
view = universe.getViewer().getView();
//view.setCompatibilityModeEnable(true);
viewInfo = new ViewInfo(view, ViewInfo.PLATFORM_AUTO_UPDATE
| ViewInfo.CANVAS_AUTO_UPDATE);
if (view.getCompatibilityModeEnable()) {
Transform3D t = new Transform3D();
viewInfo.getViewPlatformToEye(this, t, null);
view.setVpcToEc(t);
}
ViewingPlatform viewingPlatform = universe.getViewingPlatform();
ViewPlatform vp = viewingPlatform.getViewPlatform();
viewingPlatform.detach();
vp.setCapability(ViewPlatform.ALLOW_POLICY_READ);
vp.setCapability(Node.ALLOW_LOCAL_TO_VWORLD_READ);
universe.addBranchGraph(viewingPlatform);
rootGroup = J3DHelper.newBranchGroup();
rootTransform = J3DHelper.newTransformGroup();
floorTransform = J3DHelper.newTransformGroup();
cloudGroup = J3DHelper.newBranchGroup();
rootGroup.addChild(rootTransform);
rootTransform.addChild(floorTransform);
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), Double.POSITIVE_INFINITY);
// Light 1
DirectionalLight light = new DirectionalLight(new Color3f(1f, 1f, 1f), new Vector3f(-4.0f, -7.0f, -12.0f));
light.setInfluencingBounds(bounds);
floorTransform.addChild(light);
// Light 2
light = new DirectionalLight(new Color3f(1f, 1f, 1f), new Vector3f(8.0f, 9.0f, 2.0f));
light.setInfluencingBounds(bounds);
floorTransform.addChild(light);
// Background
Background back = new Background(0.57f, 0.66f, 1f);
back.setApplicationBounds(bounds);
rootGroup.addChild(back);
}
private void createBehaviourInteractors(Room3D room) {
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), Double.POSITIVE_INFINITY);
behavior = new MyBehavior(room, this, rootTransform);
behavior.setSchedulingBounds(bounds);
rootGroup.addChild(behavior);
}
public void togglePointCloud() {
if (cloudVisible) {
cloudGroup.detach();
cloudVisible = false;
}
else {
floorTransform.addChild(cloudGroup);
cloudVisible = true;
}
}
public void setPickTool() {
pickCanvas = new PickCanvas(this, room.getFloor().getBranchGroup());
pickCanvas.setMode(PickTool.GEOMETRY_INTERSECT_INFO);
pickCanvas.setTolerance(0f);
}
public void addMyCanvas3DListener(MyCanvas3DListener l) {
listeners.add(l);
}
public void removeMyCanvas3DListener(MyCanvas3DListener l) {
listeners.remove(l);
}
void setModified(ObjectInstance3D object) {
if (panel != null) { // panel may be null for 3D visualization only
object.drawOnPanel(panel, room);
}
for (MyCanvas3DListener l : listeners) {
l.setModified(object);
}
}
void objectSelected(ObjectInstance3D object) {
if (panel != null) { // panel may be null for 3D visualization only
object.drawOnPanel(panel, room);
}
if (!object.isPrivate()) {
for (MyCanvas3DListener l : listeners) {
l.objectSelected(object);
}
}
}
void objectDeselected(ObjectInstance3D object) {
if (panel != null) { // panel may be null for 3D visualization only
panel.clearLines();
panel.repaint();
}
for (MyCanvas3DListener l : listeners) {
l.objectDeselected(object);
}
}
@Override
public void dragEnter(DropTargetDragEvent dtde) {
if (behavior.selectedBox != null) {
behavior.deselect();
}
try {
if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String name = (String) dtde.getTransferable().getTransferData(DataFlavor.stringFlavor);
try {
object = room.newObject(name);
object.select();
} catch (NoSuchObjectException e) {
dtde.rejectDrag();
}
} else {
dtde.rejectDrag();
}
} catch (IOException e) {
dtde.rejectDrag();
} catch (UnsupportedFlavorException e) {
dtde.rejectDrag();
}
}
@Override
public void dragExit(DropTargetEvent dte) {
detach();
object.clear();
object = null;
}
@Override
public void dragOver(DropTargetDragEvent dtde) {
MyPickResult r = pick(dtde.getLocation().x, dtde.getLocation().y);
if (r == null) {
dtde.rejectDrag();
detach();
} else if (attachedShape == null || attachedShape != r.shape) {
FaceType ft = r.box.getFaceType(r.shape);
if ((r.box.getParentObject().isFloor() && ft != FaceType.TOP)
|| (r.box.getParentObject().isWall() &&
r.box.getParentObject().isPrivate() &&
ft != FaceType.FRONT)
|| (r.box.getParentObject().isWall() &&
!r.box.getParentObject().isPrivate() &&
(ft == FaceType.TOP || ft == FaceType.BOTTOM))
|| (r.box.getParentObject().isCeiling() &&
ft != FaceType.BOTTOM)) {
dtde.rejectDrag();
detach();
} else {
try {
FaceType suppf = object.getSupportForAttach(ft);
dtde.acceptDrag(dtde.getDropAction());
MyVect ray = getRay(dtde.getLocation().x, dtde.getLocation().y);
MyVect p = r.box.getIntersection(ft, behavior.getCameraPos(), ray, true);
if (attachedShape != r.shape) {
object.detach();
}
attachedShape = r.shape;
object.attachTo(r.box, ft);
object.setFacePosition(p.x, p.y);
p = r.box.getIntersection(ft, behavior.getCameraPos(), ray);
motion = object.getMotion(p, null); // 2nd argument won't be used
} catch (NoSupportFaceException e) {
dtde.rejectDrag();
detach();
}
}
} else if (motion != null) {
MyVect ray = getRay(dtde.getLocation().x, dtde.getLocation().y);
motion.update(behavior.getCameraPos(), ray);
if (panel != null) { // panel may be null for 3D visualization only
object.drawOnPanel(panel, room);
}
}
}
@Override
public void drop(DropTargetDropEvent dtde) {
if (object != null) {
setModified(object);
requestFocus();
} else if (panel != null) { // panel may be null for 3D visualization only
panel.clearLines();
panel.repaint();
}
object = null;
motion = null;
}
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
detach();
}
MyPickResult pick(int x, int y) {
return MyPickResult.pick(pickCanvas, object, x, y);
}
void detach() {
if (attachedShape != null) {
object.detach();
if (panel != null) { // panel may be null for 3D visualization only
panel.clearLines();
panel.repaint();
}
attachedShape = null;
motion = null;
}
}
public void removeSelectedObject() {
behavior.removeSelectedObject();
}
MyVect getRay(int x, int y) {
Point3d eyePos = new Point3d();
Point3d mousePos = new Point3d();
getCenterEyeInImagePlate(eyePos);
getPixelLocationInImagePlate(x, y, mousePos);
Transform3D screen2cam = new Transform3D();
getImagePlateToVworld(screen2cam);
MyVect v = new MyVect();
v.sub(mousePos, eyePos);
MyMatrix rot = new MyMatrix();
J3DHelper.extractRotTrans(screen2cam, rot, null, null);
v = behavior.getInvR().mul(rot.mul(v));
return v;
}
public void setDefaultView(RoomParameters params) {
Transform3D t = new Transform3D();
double fovx = 1 / room.getParams().fx;
double aspect = ((double) room.getImage().getWidth()) / room.getImage().getHeight();
double znear = 0.001;
double zfar = 1000;
double alpha = (zfar - znear) / (2 * znear * zfar);
double beta = (zfar + znear) / (2 * znear * zfar);
view.setFieldOfView(Math.atan(fovx) * 2);
view.setFrontClipDistance(znear);
view.setBackClipDistance(zfar);
if (view.getCompatibilityModeEnable()) {
Matrix P = new Matrix(4, 4);
P.set(0, 0, fovx);
P.set(1, 1, fovx / aspect * room.getParams().fx / room.getParams().fy);
//P.set(0, 1, f * room.params.g);
P.set(2, 2, 1);
P.set(3, 2, alpha);
P.set(3, 3, beta);
P = P.inverse();
t.set(P.getRowPackedCopy());
view.setLeftProjection(t);
view.setRightProjection(t);
double[] c = new double[16];
viewInfo.getEyeToImagePlate(this, t, null);
t.get(c);
setLeftManualEyeInImagePlate(new Point3d(c[3], c[7], c[11]));
setRightManualEyeInImagePlate(new Point3d(c[3], c[7], c[11]));
}
behavior.setRotation(params.cameraAngle);
behavior.setCameraPos(params.cameraPosition);
}
public MyBehavior getBehavior() {
return behavior;
}
public void addPose(double[] pose) {
Pose3DVisu p = new Pose3DVisu(pose);
floorTransform.addChild(p.getBranchGroup());
poses.add(p.getBranchGroup());
}
public void clearPoses() {
for (BranchGroup bg : poses) {
bg.detach();
}
poses.clear();
}
}
| 17,962 | 0.57076 | 0.558902 | 520 | 33.544231 | 23.214426 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736538 | false | false |
7
|
6dc941ecc0f78a59ec6c610c59fb2b9ab94f370c
| 2,267,742,784,346 |
0fb27c009220c40235142ca5a37548475df8e9d5
|
/src/otimizacao/OtimizadorConcreto1.java
|
5fc9d9b66bf32c83db419570fe024abaa6389989
|
[] |
no_license
|
matheusbarrosp/SimuladorOtimizadorSemaforico
|
https://github.com/matheusbarrosp/SimuladorOtimizadorSemaforico
|
d0c0c4264892ed0956696d08e7512a0beade7cb6
|
95c089da39ea0ee74a4818046809fc92e3fbcd69
|
refs/heads/master
| 2021-01-20T08:49:18.039000 | 2018-03-08T17:33:33 | 2018-03-08T17:33:33 | 90,190,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package otimizacao;
import entidades.Cruzamento;
import entidades.Rua;
import entidades.ViaEntradaComSemaforo;
import java.util.ArrayList;
import java.util.Random;
import simulacao.Chegada;
import simulacao.Rede;
public class OtimizadorConcreto1 implements Otimizador
{
public ArrayList<Chegada> chegadas;
public OtimizadorConcreto1(ArrayList<Chegada> chegadas)
{
this.chegadas = chegadas;
}
public int[] geraConfiguracaoAleatoria(int tam)
{
int[] configuracao = new int[tam];
int max = 120 - (10*(tam-1));
for (int i = 0; i < tam; i++)
{
Random rand = new Random();
configuracao[i] = rand.nextInt(max + 1 - 10) + 10;
max -= (configuracao[i] - 10);
}
return configuracao;
}
public IndividuoGenetico criaIndividuo()
{
ArrayList<int[]> configuracoes = new ArrayList<>();
int numCruzamentosSinalizados = 0;
for (Cruzamento c : Rede.getInstance().getCruzamentos())
{
if (c.getTemSemaforo() == 1)
{
numCruzamentosSinalizados++;
}
}
int[] abertura = new int[numCruzamentosSinalizados];
Random rand = new Random();
int i = 0;
for (Cruzamento c : Rede.getInstance().getCruzamentos())
{
if (c.getTemSemaforo() == 1)
{
int[] configuracao = geraConfiguracaoAleatoria(c.getGrupos().size());
configuracoes.add(configuracao);
int somatorio = 0;
for (int j = 1; j < configuracao.length; j++)
{
somatorio += configuracao[j];
}
abertura[i] = rand.nextInt(somatorio + 1);
i++;
}
}
return new IndividuoGenetico(configuracoes, abertura);
}
private ArrayList<double[]> getTemposEntreChegadas()
{
ArrayList<double[]> temposEntreChegadas = new ArrayList<double[]>();
for (Cruzamento c : Rede.getInstance().getCruzamentos())
{
if (c.getTemSemaforo() == 1)
{
double[] tempos = new double[c.getNumViasEntrada()];
int cont = 0;
for (Rua r : c.getRuas())
{
if (r.getViaEntrada() != null)
{
ViaEntradaComSemaforo via = (ViaEntradaComSemaforo) r.getViaEntrada();
tempos[cont] = via.getMediaEntreChegadas();
cont++;
}
}
temposEntreChegadas.add(tempos);
}
}
return temposEntreChegadas;
}
public ArrayList<int[]> otimizarCruzamentosIndividuais(ArrayList<double[]> temposEntreChegadas)
{
ArrayList<int[]> configuracoes = new ArrayList<int[]>();
Contexto contexto = new Contexto();
int cont = 0;
for(Cruzamento c: Rede.getInstance().getCruzamentos())
{
if(c.getTemSemaforo() == 1)
{
contexto.setAlgoritmo(new GeneticoConcretoCruzamento(c,
temposEntreChegadas.get(cont), Rede.getInstance().getTempoSimulacao()));
IndividuoCruzamento individuo = contexto.otimizarCruzamento(null);
configuracoes.add(individuo.getConfiguracoes().get(0));
cont++;
}
}
return configuracoes;
}
@Override
public IndividuoGenetico otimizar(Individuo base)
{
IndividuoGenetico individuoGenetico = this.criaIndividuo();
individuoGenetico.simular(Rede.getInstance().cloneChegadas(this.chegadas));
System.out.println("Individuo Aleatorio Inicial: ");
System.out.println(individuoGenetico.toString());
ArrayList<double[]> temposEntreChegadas;
ArrayList<int[]> configuracoes;
Contexto contexto = new Contexto();
for (int i = 0; i < 3; i++)
{
temposEntreChegadas = this.getTemposEntreChegadas();
System.out.println("Tempos entre chegadas:");
for(int j=0; j<temposEntreChegadas.size(); j++)
{
for(int k=0; k<temposEntreChegadas.get(j).length; k++)
{
System.out.printf("%.2f ",temposEntreChegadas.get(j)[k]);
}
System.out.println("");
}
configuracoes = this.otimizarCruzamentosIndividuais(temposEntreChegadas);
System.out.println("Configuracoes individuais otimizadas");
for(int j=0; j<configuracoes.size(); j++)
{
for(int k=0; k<configuracoes.get(j).length; k++)
{
System.out.printf("%d ",configuracoes.get(j)[k]);
}
System.out.println("");
}
contexto.setAlgoritmo(new GeneticoOtimizadorAtraso(Rede.getInstance().cloneChegadas(this.chegadas), configuracoes));
individuoGenetico = contexto.otimizarGenetico(null);
//individuoGenetico.simular(Rede.getInstance().cloneChegadas(this.chegadas));
System.out.println("Individuo otimizado: ");
System.out.println(individuoGenetico.toString());
}
return individuoGenetico;
}
}
|
UTF-8
|
Java
| 5,541 |
java
|
OtimizadorConcreto1.java
|
Java
|
[] | null |
[] |
package otimizacao;
import entidades.Cruzamento;
import entidades.Rua;
import entidades.ViaEntradaComSemaforo;
import java.util.ArrayList;
import java.util.Random;
import simulacao.Chegada;
import simulacao.Rede;
public class OtimizadorConcreto1 implements Otimizador
{
public ArrayList<Chegada> chegadas;
public OtimizadorConcreto1(ArrayList<Chegada> chegadas)
{
this.chegadas = chegadas;
}
public int[] geraConfiguracaoAleatoria(int tam)
{
int[] configuracao = new int[tam];
int max = 120 - (10*(tam-1));
for (int i = 0; i < tam; i++)
{
Random rand = new Random();
configuracao[i] = rand.nextInt(max + 1 - 10) + 10;
max -= (configuracao[i] - 10);
}
return configuracao;
}
public IndividuoGenetico criaIndividuo()
{
ArrayList<int[]> configuracoes = new ArrayList<>();
int numCruzamentosSinalizados = 0;
for (Cruzamento c : Rede.getInstance().getCruzamentos())
{
if (c.getTemSemaforo() == 1)
{
numCruzamentosSinalizados++;
}
}
int[] abertura = new int[numCruzamentosSinalizados];
Random rand = new Random();
int i = 0;
for (Cruzamento c : Rede.getInstance().getCruzamentos())
{
if (c.getTemSemaforo() == 1)
{
int[] configuracao = geraConfiguracaoAleatoria(c.getGrupos().size());
configuracoes.add(configuracao);
int somatorio = 0;
for (int j = 1; j < configuracao.length; j++)
{
somatorio += configuracao[j];
}
abertura[i] = rand.nextInt(somatorio + 1);
i++;
}
}
return new IndividuoGenetico(configuracoes, abertura);
}
private ArrayList<double[]> getTemposEntreChegadas()
{
ArrayList<double[]> temposEntreChegadas = new ArrayList<double[]>();
for (Cruzamento c : Rede.getInstance().getCruzamentos())
{
if (c.getTemSemaforo() == 1)
{
double[] tempos = new double[c.getNumViasEntrada()];
int cont = 0;
for (Rua r : c.getRuas())
{
if (r.getViaEntrada() != null)
{
ViaEntradaComSemaforo via = (ViaEntradaComSemaforo) r.getViaEntrada();
tempos[cont] = via.getMediaEntreChegadas();
cont++;
}
}
temposEntreChegadas.add(tempos);
}
}
return temposEntreChegadas;
}
public ArrayList<int[]> otimizarCruzamentosIndividuais(ArrayList<double[]> temposEntreChegadas)
{
ArrayList<int[]> configuracoes = new ArrayList<int[]>();
Contexto contexto = new Contexto();
int cont = 0;
for(Cruzamento c: Rede.getInstance().getCruzamentos())
{
if(c.getTemSemaforo() == 1)
{
contexto.setAlgoritmo(new GeneticoConcretoCruzamento(c,
temposEntreChegadas.get(cont), Rede.getInstance().getTempoSimulacao()));
IndividuoCruzamento individuo = contexto.otimizarCruzamento(null);
configuracoes.add(individuo.getConfiguracoes().get(0));
cont++;
}
}
return configuracoes;
}
@Override
public IndividuoGenetico otimizar(Individuo base)
{
IndividuoGenetico individuoGenetico = this.criaIndividuo();
individuoGenetico.simular(Rede.getInstance().cloneChegadas(this.chegadas));
System.out.println("Individuo Aleatorio Inicial: ");
System.out.println(individuoGenetico.toString());
ArrayList<double[]> temposEntreChegadas;
ArrayList<int[]> configuracoes;
Contexto contexto = new Contexto();
for (int i = 0; i < 3; i++)
{
temposEntreChegadas = this.getTemposEntreChegadas();
System.out.println("Tempos entre chegadas:");
for(int j=0; j<temposEntreChegadas.size(); j++)
{
for(int k=0; k<temposEntreChegadas.get(j).length; k++)
{
System.out.printf("%.2f ",temposEntreChegadas.get(j)[k]);
}
System.out.println("");
}
configuracoes = this.otimizarCruzamentosIndividuais(temposEntreChegadas);
System.out.println("Configuracoes individuais otimizadas");
for(int j=0; j<configuracoes.size(); j++)
{
for(int k=0; k<configuracoes.get(j).length; k++)
{
System.out.printf("%d ",configuracoes.get(j)[k]);
}
System.out.println("");
}
contexto.setAlgoritmo(new GeneticoOtimizadorAtraso(Rede.getInstance().cloneChegadas(this.chegadas), configuracoes));
individuoGenetico = contexto.otimizarGenetico(null);
//individuoGenetico.simular(Rede.getInstance().cloneChegadas(this.chegadas));
System.out.println("Individuo otimizado: ");
System.out.println(individuoGenetico.toString());
}
return individuoGenetico;
}
}
| 5,541 | 0.536907 | 0.53059 | 151 | 34.695366 | 26.817507 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569536 | false | false |
7
|
c3cbfe4a4b48ecc7ff3c4937c00ab9f9ae007356
| 25,769,803,779,621 |
da26a3562d6b26c29e33cd5781a91b142dbae5cd
|
/ShoppingSubjects/Etsy/decompile/sources/com/facebook/appevents/a.java
|
f4cb6a4c998e1d28a7f33389ba576462a8cbf1f5
|
[] |
no_license
|
MiragTechnology/TestCasesBenchmark
|
https://github.com/MiragTechnology/TestCasesBenchmark
|
d4628c8f6f5e0499302f9aaf5a5113f79a766a3e
|
6291613301d02009c4b713c2ddfbf1a0fef4e375
|
refs/heads/master
| 2022-01-22T22:43:22.458000 | 2019-07-15T19:51:17 | 2019-07-15T19:51:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.facebook.appevents;
import android.preference.PreferenceManager;
import android.util.Log;
import com.facebook.f;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/* compiled from: AnalyticsUserIDStore */
class a {
private static final String a = "a";
private static ReentrantReadWriteLock b = new ReentrantReadWriteLock();
private static String c = null;
private static volatile boolean d = false;
a() {
}
public static void a() {
if (!d) {
AppEventsLogger.g().execute(new Runnable() {
public void run() {
a.d();
}
});
}
}
public static String b() {
if (!d) {
Log.w(a, "initStore should have been called before calling setUserID");
d();
}
b.readLock().lock();
try {
return c;
} finally {
b.readLock().unlock();
}
}
/* access modifiers changed from: private */
public static void d() {
if (!d) {
b.writeLock().lock();
try {
if (!d) {
c = PreferenceManager.getDefaultSharedPreferences(f.f()).getString("com.facebook.appevents.AnalyticsUserIDStore.userID", null);
d = true;
b.writeLock().unlock();
}
} finally {
b.writeLock().unlock();
}
}
}
}
|
UTF-8
|
Java
| 1,480 |
java
|
a.java
|
Java
|
[] | null |
[] |
package com.facebook.appevents;
import android.preference.PreferenceManager;
import android.util.Log;
import com.facebook.f;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/* compiled from: AnalyticsUserIDStore */
class a {
private static final String a = "a";
private static ReentrantReadWriteLock b = new ReentrantReadWriteLock();
private static String c = null;
private static volatile boolean d = false;
a() {
}
public static void a() {
if (!d) {
AppEventsLogger.g().execute(new Runnable() {
public void run() {
a.d();
}
});
}
}
public static String b() {
if (!d) {
Log.w(a, "initStore should have been called before calling setUserID");
d();
}
b.readLock().lock();
try {
return c;
} finally {
b.readLock().unlock();
}
}
/* access modifiers changed from: private */
public static void d() {
if (!d) {
b.writeLock().lock();
try {
if (!d) {
c = PreferenceManager.getDefaultSharedPreferences(f.f()).getString("com.facebook.appevents.AnalyticsUserIDStore.userID", null);
d = true;
b.writeLock().unlock();
}
} finally {
b.writeLock().unlock();
}
}
}
}
| 1,480 | 0.510811 | 0.510811 | 56 | 25.428572 | 24.598822 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410714 | false | false |
7
|
0ced03a217dabd1ea5c920df042567ab23da5e49
| 10,342,281,297,561 |
3423b7b121b1c5c70c44bdddc24dd224e2ce61bd
|
/app/src/main/java/cn/sampson/android/xiandou/utils/widget/adapter/baseadapter/SelectBase.java
|
dba3fa5ff15501fdb857e6957bc64e398376fdd7
|
[] |
no_license
|
hupozhu/xiandou
|
https://github.com/hupozhu/xiandou
|
3a9a3f54bf9bd1308145534bbb687de60ec6130c
|
603f3e0e68caedf22a175e86d9312acd5ce68a5d
|
refs/heads/master
| 2021-01-24T07:45:31.476000 | 2017-06-20T09:44:22 | 2017-06-20T09:44:22 | 93,355,247 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.sampson.android.xiandou.utils.widget.adapter.baseadapter;
/**
* Created by Administrator on 2016/4/18.
*/
public class SelectBase implements ISelectable {
protected boolean isSelect;
@Override
public void setSelected(boolean selected) {
isSelect = selected;
}
@Override
public boolean isSelected() {
return isSelect;
}
}
|
UTF-8
|
Java
| 382 |
java
|
SelectBase.java
|
Java
|
[] | null |
[] |
package cn.sampson.android.xiandou.utils.widget.adapter.baseadapter;
/**
* Created by Administrator on 2016/4/18.
*/
public class SelectBase implements ISelectable {
protected boolean isSelect;
@Override
public void setSelected(boolean selected) {
isSelect = selected;
}
@Override
public boolean isSelected() {
return isSelect;
}
}
| 382 | 0.683246 | 0.664921 | 19 | 19.105263 | 20.130875 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | false | false |
7
|
9bce0b563eeb485421e73cb3ff46f9d030eff812
| 10,342,281,300,249 |
e0fcf8246b85651eb37b98032ec974e48e610d82
|
/src/main/java/com/piotrwalkusz/timemarker/storage/entity/TimeMarkerEntity.java
|
404291de02508cf46e9e0b9d526a50d01477358a
|
[] |
no_license
|
piotrwalkusz1/TimeMarker
|
https://github.com/piotrwalkusz1/TimeMarker
|
154a4299bfceea97f7e74e5ab84236c3de6c770f
|
a870f5275ead114d66b500fd4ba358d795c3d48b
|
refs/heads/master
| 2021-01-16T19:23:45.319000 | 2017-08-13T07:09:42 | 2017-08-13T07:09:42 | 100,159,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.piotrwalkusz.timemarker.storage.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import java.time.LocalDateTime;
@Entity
public class TimeMarkerEntity extends BaseEntity {
private LocalDateTime startTime;
private LocalDateTime endTime;
@ManyToOne(fetch = FetchType.LAZY)
private ActivityEntity activity;
protected TimeMarkerEntity() {}
public TimeMarkerEntity(LocalDateTime startTime, LocalDateTime endTime, ActivityEntity activity) {
this.startTime = startTime;
this.endTime = endTime;
this.activity = activity;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
}
|
UTF-8
|
Java
| 986 |
java
|
TimeMarkerEntity.java
|
Java
|
[
{
"context": "package com.piotrwalkusz.timemarker.storage.entity;\n\nimport javax.persiste",
"end": 24,
"score": 0.8979910016059875,
"start": 12,
"tag": "USERNAME",
"value": "piotrwalkusz"
}
] | null |
[] |
package com.piotrwalkusz.timemarker.storage.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import java.time.LocalDateTime;
@Entity
public class TimeMarkerEntity extends BaseEntity {
private LocalDateTime startTime;
private LocalDateTime endTime;
@ManyToOne(fetch = FetchType.LAZY)
private ActivityEntity activity;
protected TimeMarkerEntity() {}
public TimeMarkerEntity(LocalDateTime startTime, LocalDateTime endTime, ActivityEntity activity) {
this.startTime = startTime;
this.endTime = endTime;
this.activity = activity;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
}
| 986 | 0.717039 | 0.717039 | 39 | 24.282051 | 22.060463 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.435897 | false | false |
7
|
910dd7d94a64d12aab2764298934ff1b889a361f
| 31,559,419,730,085 |
cf6ad441bb2f4a79478d4e12bb5ad9525f8458e6
|
/src/main/java/validator/UserValidator.java
|
578782600e9f9f0049465676ea967e9e95a967d2
|
[] |
no_license
|
Viggo97/ShopManagementApp
|
https://github.com/Viggo97/ShopManagementApp
|
173c74caa8229508ba5c95c09cac58fe00046da4
|
495386ad21db44777f6f76694695f2296e5984ec
|
refs/heads/master
| 2023-01-13T13:01:31.618000 | 2020-11-23T17:58:39 | 2020-11-23T17:58:39 | 315,372,326 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package validator;
import entity.User;
import exception.UserLoginAlreadyExistException;
import exception.UserShortLengthLoginException;
import exception.UserShortLengthPasswordException;
import java.io.IOException;
public class UserValidator {
private final int MIN_LOGIN_LENGTH = 4;
private final int MIN_PASSWORD_LENGTH = 6;
private static UserValidator instance = null;
private UserValidator () throws IOException {
}
public static UserValidator getInstance() throws IOException {
if (instance == null) {
instance = new UserValidator();
}
return instance;
}
public boolean isValidate(User user) throws UserShortLengthLoginException, UserShortLengthPasswordException {
if (isLoginLengthEnough(user.getLogin()))
throw new UserShortLengthLoginException("Login is too short.");
if (isPasswordLengthEnough(user.getPassword()))
throw new UserShortLengthPasswordException("Password is too short.");
return true;
}
private boolean isLoginLengthEnough(String login) {
return login.length() < MIN_LOGIN_LENGTH;
}
private boolean isPasswordLengthEnough(String password) {
return password.length() < MIN_PASSWORD_LENGTH;
}
}
|
UTF-8
|
Java
| 1,282 |
java
|
UserValidator.java
|
Java
|
[] | null |
[] |
package validator;
import entity.User;
import exception.UserLoginAlreadyExistException;
import exception.UserShortLengthLoginException;
import exception.UserShortLengthPasswordException;
import java.io.IOException;
public class UserValidator {
private final int MIN_LOGIN_LENGTH = 4;
private final int MIN_PASSWORD_LENGTH = 6;
private static UserValidator instance = null;
private UserValidator () throws IOException {
}
public static UserValidator getInstance() throws IOException {
if (instance == null) {
instance = new UserValidator();
}
return instance;
}
public boolean isValidate(User user) throws UserShortLengthLoginException, UserShortLengthPasswordException {
if (isLoginLengthEnough(user.getLogin()))
throw new UserShortLengthLoginException("Login is too short.");
if (isPasswordLengthEnough(user.getPassword()))
throw new UserShortLengthPasswordException("Password is too short.");
return true;
}
private boolean isLoginLengthEnough(String login) {
return login.length() < MIN_LOGIN_LENGTH;
}
private boolean isPasswordLengthEnough(String password) {
return password.length() < MIN_PASSWORD_LENGTH;
}
}
| 1,282 | 0.709828 | 0.708268 | 46 | 26.869566 | 27.846325 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369565 | false | false |
7
|
f0409ce1fc4dbbc49334e87b7365b5e2f147f242
| 6,253,472,387,195 |
25c336e80617c8ddd1d0c7f2517077074de34447
|
/Flashcards/task/src/flashcards/SystemIO.java
|
4941ce3c578ec88e33df919378dc1df96d91fc18
|
[] |
no_license
|
gitbic/Hyperskill_5_Flashcards
|
https://github.com/gitbic/Hyperskill_5_Flashcards
|
b68dc66edd3af87872ffbb2a47e539e63f4477bc
|
e93a3cd2796a75a0588ff747cd351f972f5ec79e
|
refs/heads/master
| 2022-12-12T07:26:26.906000 | 2020-08-24T10:09:53 | 2020-08-24T10:09:53 | 289,875,621 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package flashcards;
import java.util.Scanner;
class SystemIO {
private static Scanner scanner = new Scanner(System.in);
private static LogBuilder log = new LogBuilder();
static String scan() {
String str = scanner.nextLine();
log.add(str);
log.add(System.lineSeparator());
return str;
}
static void println(String str) {
log.add(str);
log.add(System.lineSeparator());
System.out.println(str);
}
static void println() {
log.add(System.lineSeparator());
System.out.println();
}
static void printf(String s, String... args) {
String str = String.format(s, args);
System.out.print(str);
log.add(str);
}
}
|
UTF-8
|
Java
| 743 |
java
|
SystemIO.java
|
Java
|
[] | null |
[] |
package flashcards;
import java.util.Scanner;
class SystemIO {
private static Scanner scanner = new Scanner(System.in);
private static LogBuilder log = new LogBuilder();
static String scan() {
String str = scanner.nextLine();
log.add(str);
log.add(System.lineSeparator());
return str;
}
static void println(String str) {
log.add(str);
log.add(System.lineSeparator());
System.out.println(str);
}
static void println() {
log.add(System.lineSeparator());
System.out.println();
}
static void printf(String s, String... args) {
String str = String.format(s, args);
System.out.print(str);
log.add(str);
}
}
| 743 | 0.592194 | 0.592194 | 32 | 22.21875 | 17.689569 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false |
7
|
a61ff53f59468df4436d17a8d40c51208455847a
| 4,999,341,987,341 |
9a5ded1845d1e090717abb42f1dd41f57d5968ee
|
/myrpc-spring-boot-starter/src/main/java/com/wj/client/balance/WeigthBalance.java
|
85ee85133fe698cc2934abcea81b216e387ddb2a
|
[] |
no_license
|
shuixiou1/myrpc-spring-boot-starter
|
https://github.com/shuixiou1/myrpc-spring-boot-starter
|
027311c8de62b5e0203d0b83f24b634b2d2d7318
|
6c6e7eb137b7774e25ffee68ece908a45f6f8f5c
|
refs/heads/master
| 2023-04-02T02:25:57.056000 | 2021-04-13T09:18:14 | 2021-04-13T09:18:14 | 353,551,120 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wj.client.balance;
import java.util.ArrayList;
import java.util.List;
import com.wj.annotation.LoadBalanceAno;
import com.wj.common.constants.RpcConstant;
import com.wj.common.model.MyService;
/**
* 加权轮询
*/
@LoadBalanceAno(RpcConstant.BALANCE_WEIGHT)
public class WeigthBalance implements LoadBalance{
private volatile static int index;
@Override
public synchronized MyService chooseOne(List<MyService> services) {
int size = services.stream().mapToInt(MyService::getWeight).sum();
int temp = index++ % size;
int current = 0;
for (MyService myMyService : services) {
current += myMyService.getWeight();
if (temp < current) {
return myMyService;
}
}
return null;
}
public static void main(String[] args) {
List<MyService> services = new ArrayList<>(3);
MyService service1 = new MyService();
service1.setAddress("196.128.6.1");
service1.setWeight(1);
services.add(service1);
MyService service2 = new MyService();
service2.setAddress("196.128.6.2");
service2.setWeight(3);
services.add(service2);
MyService service3 = new MyService();
service3.setAddress("196.128.6.3");
service3.setWeight(5);
services.add(service3);
LoadBalance loadBalance = new WeigthBalance();
System.out.println("20次请求负载均衡结果为:");
for (int i = 1; i <= 20; i++) {
System.out.println("第" + i + "次请求服务ip为:" + loadBalance.chooseOne(services).getAddress());
}
}
}
|
UTF-8
|
Java
| 1,493 |
java
|
WeigthBalance.java
|
Java
|
[
{
"context": "ervice1 = new MyService();\n\t\tservice1.setAddress(\"196.128.6.1\");\n\t\tservice1.setWeight(1);\n\t\tservices.add(servic",
"end": 907,
"score": 0.9997278451919556,
"start": 896,
"tag": "IP_ADDRESS",
"value": "196.128.6.1"
},
{
"context": "ervice2 = new MyService();\n\t\tservice2.setAddress(\"196.128.6.2\");\n\t\tservice2.setWeight(3);\n\t\tservices.add(servic",
"end": 1037,
"score": 0.9997317790985107,
"start": 1026,
"tag": "IP_ADDRESS",
"value": "196.128.6.2"
},
{
"context": "ervice3 = new MyService();\n\t\tservice3.setAddress(\"196.128.6.3\");\n\t\tservice3.setWeight(5);\n\t\tservices.add(servic",
"end": 1167,
"score": 0.9997097253799438,
"start": 1156,
"tag": "IP_ADDRESS",
"value": "196.128.6.3"
}
] | null |
[] |
package com.wj.client.balance;
import java.util.ArrayList;
import java.util.List;
import com.wj.annotation.LoadBalanceAno;
import com.wj.common.constants.RpcConstant;
import com.wj.common.model.MyService;
/**
* 加权轮询
*/
@LoadBalanceAno(RpcConstant.BALANCE_WEIGHT)
public class WeigthBalance implements LoadBalance{
private volatile static int index;
@Override
public synchronized MyService chooseOne(List<MyService> services) {
int size = services.stream().mapToInt(MyService::getWeight).sum();
int temp = index++ % size;
int current = 0;
for (MyService myMyService : services) {
current += myMyService.getWeight();
if (temp < current) {
return myMyService;
}
}
return null;
}
public static void main(String[] args) {
List<MyService> services = new ArrayList<>(3);
MyService service1 = new MyService();
service1.setAddress("172.16.17.32");
service1.setWeight(1);
services.add(service1);
MyService service2 = new MyService();
service2.setAddress("172.16.58.3");
service2.setWeight(3);
services.add(service2);
MyService service3 = new MyService();
service3.setAddress("172.16.58.3");
service3.setWeight(5);
services.add(service3);
LoadBalance loadBalance = new WeigthBalance();
System.out.println("20次请求负载均衡结果为:");
for (int i = 1; i <= 20; i++) {
System.out.println("第" + i + "次请求服务ip为:" + loadBalance.chooseOne(services).getAddress());
}
}
}
| 1,494 | 0.694962 | 0.663216 | 56 | 24.875 | 20.86698 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.678571 | false | false |
7
|
7c3474f9425914dcfbe6138d9f320628f8a039ab
| 32,487,132,661,028 |
cf04964eae92ce4531c7f1cf703270a82fe315d8
|
/src/java/servlet/reservas/SvReservasCrear.java
|
32746d999f95936d636448b570bf83a00e443228
|
[] |
no_license
|
MatiasEJ/java-tpof-Polotic
|
https://github.com/MatiasEJ/java-tpof-Polotic
|
c6a176116320255c046e63eb4b4d84045c470a82
|
77914131a89efee7f03bcd235f9b407405d52e8e
|
refs/heads/main
| 2023-06-30T22:11:38.106000 | 2021-08-13T13:30:53 | 2021-08-13T13:30:53 | 391,468,966 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package servlet.reservas;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import logica.controladoras.ControladoraCliente;
import logica.util.Paginas;
import logica.controladoras.ControladoraHabitacion;
import logica.controladoras.ControladoraReservas;
import logica.entidades.habitaciones.Habitacion;
import logica.entidades.personas.Cliente;
import logica.util.DatosReservas;
import logica.util.Utilidades;
@WebServlet(name = "SvReservasCrear", urlPatterns = {"/SvReservasCrear"})
public class SvReservasCrear extends HttpServlet {
ControladoraReservas controladoraReserva = new ControladoraReservas();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ControladoraHabitacion ch = new ControladoraHabitacion();
ControladoraReservas cr = new ControladoraReservas();
HttpSession mySession = request.getSession();
mySession.setAttribute("listaReservas", cr.findAllReserva());
mySession.setAttribute("listaHabitacion", ch.findAllHabitacion());
response.sendRedirect(Paginas.ALTA_RESERVAS);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fechaIn = request.getParameter(DatosReservas.FECHA_IN);
String fechaOut = request.getParameter(DatosReservas.FECHA_OUT);
int cantHuespedesReserva = Integer.parseInt(request.getParameter(DatosReservas.CANT_HUESPEDES));
int cantDiasReserva = Utilidades.cantidadDiasEstadia(fechaIn, fechaOut);
int idHabitacion = Integer.parseInt(request.getParameter("idHabitacion"));
String dniCliente = request.getParameter("dniCliente");
int idCliente = Integer.parseInt(request.getParameter("idCliente"));
ControladoraHabitacion controladoraHabitaciones = new ControladoraHabitacion();
ControladoraCliente controladoraCliente = new ControladoraCliente();
Cliente cliente;
if(dniCliente != null && !dniCliente.isEmpty()){
cliente = controladoraCliente.findClienteByDni(dniCliente);
}else{
cliente= controladoraCliente.findClienteById(idCliente);
}
Habitacion habitacion = controladoraHabitaciones.findHabitacionById(idHabitacion);
boolean authCantHuespedes = controladoraHabitaciones.cantidadCorrectaHuespedes(cantHuespedesReserva, idHabitacion);
double monto = habitacion.calcularMontoEstadia(cantDiasReserva);
boolean authFechaReserva = controladoraReserva.isFechaReservaDisponible(fechaIn, fechaOut);
String error = "";
if (!authFechaReserva){
error = error.concat("Error fecha reserva. ");
}
if(!authCantHuespedes){
error = error.concat("Cantidad erronea de huespedes. ");
}
if(authFechaReserva && authCantHuespedes){
if (cliente != null) {
request.getSession().setAttribute("objCliente", cliente);
request.getSession().setAttribute("objHabitacion", habitacion);
request.getSession().setAttribute(DatosReservas.FECHA_IN, fechaIn);
request.getSession().setAttribute(DatosReservas.FECHA_OUT, fechaOut);
request.getSession().setAttribute("cantDiasReserva", cantDiasReserva);
request.getSession().setAttribute(DatosReservas.DIAS_RESERVA, cantDiasReserva);
request.getSession().setAttribute(DatosReservas.CANT_HUESPEDES, cantHuespedesReserva);
request.getSession().setAttribute(DatosReservas.MONTO, monto);
request.getSession().setAttribute("tipoHab", habitacion.getTipoHabitacion().toString());
request.getSession().setAttribute("temaHab", habitacion.getTematica().toString());
request.getSession().setAttribute("listaHabitaciones", controladoraHabitaciones.findAllHabitacion());
response.sendRedirect(Paginas.CONFIRMAR_RESERVA);
} else {
response.sendRedirect(Paginas.ALTA_CLIENTES);
}
} else {
error = error.concat("\n Error reserva, vuelva a intentarlo.");
request.getSession().setAttribute("error", error);
response.sendRedirect(Paginas.ALTA_RESERVAS);
}
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
UTF-8
|
Java
| 4,448 |
java
|
SvReservasCrear.java
|
Java
|
[] | null |
[] |
package servlet.reservas;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import logica.controladoras.ControladoraCliente;
import logica.util.Paginas;
import logica.controladoras.ControladoraHabitacion;
import logica.controladoras.ControladoraReservas;
import logica.entidades.habitaciones.Habitacion;
import logica.entidades.personas.Cliente;
import logica.util.DatosReservas;
import logica.util.Utilidades;
@WebServlet(name = "SvReservasCrear", urlPatterns = {"/SvReservasCrear"})
public class SvReservasCrear extends HttpServlet {
ControladoraReservas controladoraReserva = new ControladoraReservas();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ControladoraHabitacion ch = new ControladoraHabitacion();
ControladoraReservas cr = new ControladoraReservas();
HttpSession mySession = request.getSession();
mySession.setAttribute("listaReservas", cr.findAllReserva());
mySession.setAttribute("listaHabitacion", ch.findAllHabitacion());
response.sendRedirect(Paginas.ALTA_RESERVAS);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fechaIn = request.getParameter(DatosReservas.FECHA_IN);
String fechaOut = request.getParameter(DatosReservas.FECHA_OUT);
int cantHuespedesReserva = Integer.parseInt(request.getParameter(DatosReservas.CANT_HUESPEDES));
int cantDiasReserva = Utilidades.cantidadDiasEstadia(fechaIn, fechaOut);
int idHabitacion = Integer.parseInt(request.getParameter("idHabitacion"));
String dniCliente = request.getParameter("dniCliente");
int idCliente = Integer.parseInt(request.getParameter("idCliente"));
ControladoraHabitacion controladoraHabitaciones = new ControladoraHabitacion();
ControladoraCliente controladoraCliente = new ControladoraCliente();
Cliente cliente;
if(dniCliente != null && !dniCliente.isEmpty()){
cliente = controladoraCliente.findClienteByDni(dniCliente);
}else{
cliente= controladoraCliente.findClienteById(idCliente);
}
Habitacion habitacion = controladoraHabitaciones.findHabitacionById(idHabitacion);
boolean authCantHuespedes = controladoraHabitaciones.cantidadCorrectaHuespedes(cantHuespedesReserva, idHabitacion);
double monto = habitacion.calcularMontoEstadia(cantDiasReserva);
boolean authFechaReserva = controladoraReserva.isFechaReservaDisponible(fechaIn, fechaOut);
String error = "";
if (!authFechaReserva){
error = error.concat("Error fecha reserva. ");
}
if(!authCantHuespedes){
error = error.concat("Cantidad erronea de huespedes. ");
}
if(authFechaReserva && authCantHuespedes){
if (cliente != null) {
request.getSession().setAttribute("objCliente", cliente);
request.getSession().setAttribute("objHabitacion", habitacion);
request.getSession().setAttribute(DatosReservas.FECHA_IN, fechaIn);
request.getSession().setAttribute(DatosReservas.FECHA_OUT, fechaOut);
request.getSession().setAttribute("cantDiasReserva", cantDiasReserva);
request.getSession().setAttribute(DatosReservas.DIAS_RESERVA, cantDiasReserva);
request.getSession().setAttribute(DatosReservas.CANT_HUESPEDES, cantHuespedesReserva);
request.getSession().setAttribute(DatosReservas.MONTO, monto);
request.getSession().setAttribute("tipoHab", habitacion.getTipoHabitacion().toString());
request.getSession().setAttribute("temaHab", habitacion.getTematica().toString());
request.getSession().setAttribute("listaHabitaciones", controladoraHabitaciones.findAllHabitacion());
response.sendRedirect(Paginas.CONFIRMAR_RESERVA);
} else {
response.sendRedirect(Paginas.ALTA_CLIENTES);
}
} else {
error = error.concat("\n Error reserva, vuelva a intentarlo.");
request.getSession().setAttribute("error", error);
response.sendRedirect(Paginas.ALTA_RESERVAS);
}
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 4,448 | 0.791592 | 0.791367 | 107 | 40.570095 | 30.727962 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.429907 | false | false |
3
|
d791ad02816c413ada3b2166432632b0230cd3af
| 2,688,649,580,838 |
d900c8bf1d1db51d50fcf920d54edb44e906adf1
|
/src/main/java/com/dugbel/wunderground/model/weather/Weather.java
|
80c63f47e693c72403260774fcd71b9d450814c4
|
[
"Apache-2.0"
] |
permissive
|
douglasbell/wunderground-api
|
https://github.com/douglasbell/wunderground-api
|
1741ae8fa16a2005e2430ac7bb0296f1e5a34f25
|
ac6073bb38a9168122a884870520202e6e292016
|
refs/heads/master
| 2016-09-05T09:47:00.247000 | 2014-08-05T23:30:44 | 2014-08-05T23:30:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dugbel.wunderground.model.weather;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Weather Model
*
* @author dbell
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Weather {
/** {@link History} */
private History history;
/**
* Return the {@link History}
*
* @return {@link History}
*/
public History getHistory() {
return history;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
}
|
UTF-8
|
Java
| 726 |
java
|
Weather.java
|
Java
|
[
{
"context": "reProperties;\n\n/**\n * Weather Model\n * \n * @author dbell\n *\n */\n@JsonIgnoreProperties(ignoreUnknown = true",
"end": 275,
"score": 0.9992107152938843,
"start": 270,
"tag": "USERNAME",
"value": "dbell"
}
] | null |
[] |
package com.dugbel.wunderground.model.weather;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Weather Model
*
* @author dbell
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Weather {
/** {@link History} */
private History history;
/**
* Return the {@link History}
*
* @return {@link History}
*/
public History getHistory() {
return history;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
}
| 726 | 0.712121 | 0.709366 | 38 | 18.131578 | 19.027918 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.894737 | false | false |
3
|
5368c902e3b1784fa6eb7b09685997e3b84bf1a9
| 19,696,720,065,286 |
a7710ce643681112c7810f34a963adcd65c8b61b
|
/lab2/zad4/src/pl/edu/agh/soa/lab2/zad4/car/CarChoiceHelper.java
|
688ba9a38a4b408435732c647415dad784e809b2
|
[] |
no_license
|
anotender/soa
|
https://github.com/anotender/soa
|
26802f88f46c0a453d48a6b9c9534121ee9cf7bf
|
045df5b673700dc97fff8e7ec3ab94b733fb93a4
|
refs/heads/master
| 2021-03-24T11:52:43.463000 | 2017-07-28T09:10:33 | 2017-07-28T09:10:33 | 89,245,563 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.edu.agh.soa.lab2.zad4.car;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CarChoiceHelper {
private List<Car> cars;
public CarChoiceHelper() {
cars = Arrays.asList(
new Car("Mercedes", "luksusowy", 200000),
new Car("Aston Martin", "sportowy", 500000),
new Car("Mini", "miejski", 50000),
new Car("BMW", "luksusowy", 150000)
);
}
public List<String> getSuitableModels(String typ, int min, int max) {
return cars
.stream()
.filter(c -> c.getType().equals(typ))
.filter(c -> min <= c.getPrice() && c.getPrice() <= max)
.map(Car::getName)
.collect(Collectors.toList());
}
}
|
UTF-8
|
Java
| 824 |
java
|
CarChoiceHelper.java
|
Java
|
[
{
"context": " cars = Arrays.asList(\n new Car(\"Mercedes\", \"luksusowy\", 200000),\n new Car(\"",
"end": 279,
"score": 0.9998121857643127,
"start": 271,
"tag": "NAME",
"value": "Mercedes"
},
{
"context": "sList(\n new Car(\"Mercedes\", \"luksusowy\", 200000),\n new Car(\"Aston Martin\"",
"end": 292,
"score": 0.5755428671836853,
"start": 289,
"tag": "NAME",
"value": "owy"
},
{
"context": "\", \"luksusowy\", 200000),\n new Car(\"Aston Martin\", \"sportowy\", 500000),\n new Car(\"M",
"end": 341,
"score": 0.9998469352722168,
"start": 329,
"tag": "NAME",
"value": "Aston Martin"
}
] | null |
[] |
package pl.edu.agh.soa.lab2.zad4.car;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CarChoiceHelper {
private List<Car> cars;
public CarChoiceHelper() {
cars = Arrays.asList(
new Car("Mercedes", "luksusowy", 200000),
new Car("<NAME>", "sportowy", 500000),
new Car("Mini", "miejski", 50000),
new Car("BMW", "luksusowy", 150000)
);
}
public List<String> getSuitableModels(String typ, int min, int max) {
return cars
.stream()
.filter(c -> c.getType().equals(typ))
.filter(c -> min <= c.getPrice() && c.getPrice() <= max)
.map(Car::getName)
.collect(Collectors.toList());
}
}
| 818 | 0.540049 | 0.509709 | 29 | 27.413794 | 22.675396 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false |
3
|
a6b3e6650dc52fb8b56262ff99417c45b8b149b9
| 25,477,746,022,128 |
32405cf2afb0ad6d41f3808e9fba6b585c37e5d6
|
/src/main/java/com/github/sebersole/gradle/quarkus/jandex/IndexingTask.java
|
5d65854fb6843de88b5c5cd8bbaf5c6c1e5f0f07
|
[] |
no_license
|
sebersole/quarkus-poc-buildscript
|
https://github.com/sebersole/quarkus-poc-buildscript
|
5f766483f4f3b26a846f3bdad650ffc0f91291ac
|
4b019ac3e892ed7a7a94798d862a99bd6635a135
|
refs/heads/master
| 2023-01-04T23:57:00.395000 | 2020-10-29T01:54:08 | 2020-10-29T01:54:08 | 302,748,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.sebersole.gradle.quarkus.jandex;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Inject;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.execution.TaskExecutionAdapter;
import org.gradle.api.file.Directory;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.RegularFile;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.SetProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.TaskState;
import com.github.sebersole.gradle.quarkus.QuarkusPlugin;
import com.github.sebersole.gradle.quarkus.QuarkusSpec;
import com.github.sebersole.gradle.quarkus.service.Services;
/**
* Task for managing Jandex indexes for Quarkus
*/
public class IndexingTask extends DefaultTask {
public static final String DSL_NAME = "quarkusJandex";
private final SetProperty<String> externalDependencyCoordinates;
private final DirectoryProperty jandexDirectory;
private final boolean mainProjectHasJavaSources;
@Inject
public IndexingTask(QuarkusSpec dsl, Services services, SourceSet mainSourceSet) {
final ObjectFactory objectFactory = getProject().getObjects();
mainProjectHasJavaSources = mainSourceSet != null;
externalDependencyCoordinates = objectFactory.setProperty( String.class );
externalDependencyCoordinates.set(
getProject().provider(
() -> {
final Set<String> dependencies = new HashSet<>();
services.getIndexingService().forEachIndexManager(
indexManager -> dependencies.add( indexManager.getDependencyIdentifier().groupArtifactVersion() )
);
return dependencies;
}
)
);
jandexDirectory = objectFactory.directoryProperty();
jandexDirectory.set( services.getIndexingService().getJandexDirectoryAccess() );
}
public static IndexingTask apply(QuarkusSpec dsl, Services services, Project project) {
// we also register a task execution listener force load all indexes when
// this task was executed and but did no work
project.getGradle().getTaskGraph().addTaskExecutionListener(
new TaskExecutionAdapter() {
@Override
public void afterExecute(Task task, TaskState state) {
if ( task.getName().equals( DSL_NAME ) ) {
if ( ! state.getDidWork() ) {
// the Jandex task was part of the task graph but did
// no work - that should indicate it is "up-to-date"
assert state.getUpToDate();
// and should imply that all of the
project.getLogger().lifecycle( "Re-loading Jandex indexes" );
services.getIndexingService().forEachIndexManager( IndexManager::readIndex );
}
}
super.afterExecute( task, state );
}
}
);
final SourceSet mainSourceSet = services.getBuildDetails().getMainProjectMainSourceSet();
final IndexingTask indexingTask = project.getTasks().create( DSL_NAME, IndexingTask.class, dsl, services, mainSourceSet );
if ( mainSourceSet != null ) {
indexingTask.dependsOn( mainSourceSet.getCompileJavaTaskName() );
}
return indexingTask;
}
@Input
SetProperty<String> getExternalDependencyCoordinates() {
return externalDependencyCoordinates;
}
@OutputDirectory
public DirectoryProperty getOutputDirectory() {
return jandexDirectory;
}
@TaskAction
void execute() {
getLogger().lifecycle( "Starting {} task", DSL_NAME );
getLogger().trace( "Starting {} task", DSL_NAME );
final Directory directory = getOutputDirectory().get();
final HashSet<RegularFile> existingIndexFiles = new HashSet<>();
getOutputDirectory().getAsFileTree().forEach(
file -> {
final RegularFile indexFileReference = directory.file( file.getName() );
existingIndexFiles.add( indexFileReference );
}
);
final Project project = getProject();
final QuarkusPlugin quarkusPlugin = project.getPlugins().getPlugin( QuarkusPlugin.class );
final Services services = quarkusPlugin.getServices();
services.getIndexingService().forEachIndexManager(
indexManager -> {
indexManager.generateIndex();
existingIndexFiles.remove( indexManager.getIndexFile() );
}
);
existingIndexFiles.forEach( IndexingTask::removeNoLongerIndexedFile );
}
@SuppressWarnings( "ResultOfMethodCallIgnored" )
private static void removeNoLongerIndexedFile(RegularFile noLongerNeededIndexFile) {
noLongerNeededIndexFile.getAsFile().delete();
}
}
|
UTF-8
|
Java
| 4,562 |
java
|
IndexingTask.java
|
Java
|
[
{
"context": "package com.github.sebersole.gradle.quarkus.jandex;\n\nimport java.util.HashSet;",
"end": 28,
"score": 0.9991404414176941,
"start": 19,
"tag": "USERNAME",
"value": "sebersole"
},
{
"context": "rg.gradle.api.tasks.TaskState;\n\nimport com.github.sebersole.gradle.quarkus.QuarkusPlugin;\nimport com.github.s",
"end": 715,
"score": 0.9988918304443359,
"start": 706,
"tag": "USERNAME",
"value": "sebersole"
},
{
"context": "e.gradle.quarkus.QuarkusPlugin;\nimport com.github.sebersole.gradle.quarkus.QuarkusSpec;\nimport com.github.seb",
"end": 773,
"score": 0.998669445514679,
"start": 764,
"tag": "USERNAME",
"value": "sebersole"
},
{
"context": "ole.gradle.quarkus.QuarkusSpec;\nimport com.github.sebersole.gradle.quarkus.service.Services;\n\n/**\n * Task for",
"end": 829,
"score": 0.9988434314727783,
"start": 820,
"tag": "USERNAME",
"value": "sebersole"
}
] | null |
[] |
package com.github.sebersole.gradle.quarkus.jandex;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Inject;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.execution.TaskExecutionAdapter;
import org.gradle.api.file.Directory;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.RegularFile;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.SetProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.TaskState;
import com.github.sebersole.gradle.quarkus.QuarkusPlugin;
import com.github.sebersole.gradle.quarkus.QuarkusSpec;
import com.github.sebersole.gradle.quarkus.service.Services;
/**
* Task for managing Jandex indexes for Quarkus
*/
public class IndexingTask extends DefaultTask {
public static final String DSL_NAME = "quarkusJandex";
private final SetProperty<String> externalDependencyCoordinates;
private final DirectoryProperty jandexDirectory;
private final boolean mainProjectHasJavaSources;
@Inject
public IndexingTask(QuarkusSpec dsl, Services services, SourceSet mainSourceSet) {
final ObjectFactory objectFactory = getProject().getObjects();
mainProjectHasJavaSources = mainSourceSet != null;
externalDependencyCoordinates = objectFactory.setProperty( String.class );
externalDependencyCoordinates.set(
getProject().provider(
() -> {
final Set<String> dependencies = new HashSet<>();
services.getIndexingService().forEachIndexManager(
indexManager -> dependencies.add( indexManager.getDependencyIdentifier().groupArtifactVersion() )
);
return dependencies;
}
)
);
jandexDirectory = objectFactory.directoryProperty();
jandexDirectory.set( services.getIndexingService().getJandexDirectoryAccess() );
}
public static IndexingTask apply(QuarkusSpec dsl, Services services, Project project) {
// we also register a task execution listener force load all indexes when
// this task was executed and but did no work
project.getGradle().getTaskGraph().addTaskExecutionListener(
new TaskExecutionAdapter() {
@Override
public void afterExecute(Task task, TaskState state) {
if ( task.getName().equals( DSL_NAME ) ) {
if ( ! state.getDidWork() ) {
// the Jandex task was part of the task graph but did
// no work - that should indicate it is "up-to-date"
assert state.getUpToDate();
// and should imply that all of the
project.getLogger().lifecycle( "Re-loading Jandex indexes" );
services.getIndexingService().forEachIndexManager( IndexManager::readIndex );
}
}
super.afterExecute( task, state );
}
}
);
final SourceSet mainSourceSet = services.getBuildDetails().getMainProjectMainSourceSet();
final IndexingTask indexingTask = project.getTasks().create( DSL_NAME, IndexingTask.class, dsl, services, mainSourceSet );
if ( mainSourceSet != null ) {
indexingTask.dependsOn( mainSourceSet.getCompileJavaTaskName() );
}
return indexingTask;
}
@Input
SetProperty<String> getExternalDependencyCoordinates() {
return externalDependencyCoordinates;
}
@OutputDirectory
public DirectoryProperty getOutputDirectory() {
return jandexDirectory;
}
@TaskAction
void execute() {
getLogger().lifecycle( "Starting {} task", DSL_NAME );
getLogger().trace( "Starting {} task", DSL_NAME );
final Directory directory = getOutputDirectory().get();
final HashSet<RegularFile> existingIndexFiles = new HashSet<>();
getOutputDirectory().getAsFileTree().forEach(
file -> {
final RegularFile indexFileReference = directory.file( file.getName() );
existingIndexFiles.add( indexFileReference );
}
);
final Project project = getProject();
final QuarkusPlugin quarkusPlugin = project.getPlugins().getPlugin( QuarkusPlugin.class );
final Services services = quarkusPlugin.getServices();
services.getIndexingService().forEachIndexManager(
indexManager -> {
indexManager.generateIndex();
existingIndexFiles.remove( indexManager.getIndexFile() );
}
);
existingIndexFiles.forEach( IndexingTask::removeNoLongerIndexedFile );
}
@SuppressWarnings( "ResultOfMethodCallIgnored" )
private static void removeNoLongerIndexedFile(RegularFile noLongerNeededIndexFile) {
noLongerNeededIndexFile.getAsFile().delete();
}
}
| 4,562 | 0.748794 | 0.748794 | 136 | 32.544117 | 28.565937 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.602941 | false | false |
3
|
618907922af0685835f4fcc55f7636a2d8e4d1ac
| 22,874,995,849,038 |
cd92e740421c32674960b477f7b85b472943c6f6
|
/src/arrays/FunctionDemo.java
|
f99165b001379b3bb191d456fab0df34e4c1587d
|
[] |
no_license
|
grubbycc/Java
|
https://github.com/grubbycc/Java
|
6e6201445d172bd6b173fafb7a38261539be6477
|
122c2b169b12c46eae6fd2ed395ef1ba800ec446
|
refs/heads/master
| 2018-04-02T14:32:05.726000 | 2018-03-29T12:04:11 | 2018-03-29T12:04:11 | 88,578,204 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package arrays;
//函数作用:封装代码,便于复用
public class FunctionDemo {
public static void main(String[] args) {
/**
* 函数也叫方法,是定义在类中具有特定功能的一段小程序
* 函数格式:修饰符 返回值类型 方法名(参数类型 形式参数1,参数类型 形式参数2){
* 执行语句;
* return 返回值; //return用于结束函数,返回值返回给调用者
* }
* 没有具体返回值时,返回值类型用void,return可以省略不写
* 函数两个明确: a、返回值类型;
* b、参数列表
* 注意:返回值类型和参数类型没有直接关系
* 注意事项:1、函数只能调用函数,不可以在函数内部定义函数
* 2、函数的结果应该返回给调用者,交由调用者处理
*/
//int x = add(4,5);
//System.out.println("x="+x);
//draw(3,4);
//boolean res = equal(5,6);
//System.out.println(res);
//int max = getMax(3, 9);
//System.out.println("max="+max);
//print99();
char res = getLevel(88);
System.out.println("result="+res);
}
//需求1:求和功能
public static int add(int a,int b){
return a+b;
}
//需求2:画一个矩形在控制台
public static void draw(int row,int col){
for(int x=1;x<=row;x++){
for(int y=1;y<=col;y++){
System.out.print("*");
}
System.out.println();
}
}
//需求 3:比较两个数是否相等
public static boolean equal(int a,int b){
return a==b;
}
//需求4:比较两个数较大的那个
public static int getMax(int a,int b){
return a>b?a:b;
}
//需求5:打印99乘法表
public static void print99(){
for(int x=1;x<=9;x++){
for(int y=1;y<=x;y++){
System.out.print(y+"*"+x+"="+y*x+"\t");
}
System.out.println();
}
}
//需求6:根据考试成绩获取学生分数对应的等级
/*90~100 A
80~89 B
70~79 res
60~69 D
60以下 E
*/
public static char getLevel(int num){
char res;
if(num>=90 && num<=100){
res = 'A';
}else if(num>=80 && num<=89){
res = 'B';
}else if(num>=70 && num<=79){
res = 'C';
}else if(num>=60 && num<=69){
res = 'D';
}else{
res = 'E';
}
return res;
}
}
|
UTF-8
|
Java
| 2,850 |
java
|
FunctionDemo.java
|
Java
|
[] | null |
[] |
package arrays;
//函数作用:封装代码,便于复用
public class FunctionDemo {
public static void main(String[] args) {
/**
* 函数也叫方法,是定义在类中具有特定功能的一段小程序
* 函数格式:修饰符 返回值类型 方法名(参数类型 形式参数1,参数类型 形式参数2){
* 执行语句;
* return 返回值; //return用于结束函数,返回值返回给调用者
* }
* 没有具体返回值时,返回值类型用void,return可以省略不写
* 函数两个明确: a、返回值类型;
* b、参数列表
* 注意:返回值类型和参数类型没有直接关系
* 注意事项:1、函数只能调用函数,不可以在函数内部定义函数
* 2、函数的结果应该返回给调用者,交由调用者处理
*/
//int x = add(4,5);
//System.out.println("x="+x);
//draw(3,4);
//boolean res = equal(5,6);
//System.out.println(res);
//int max = getMax(3, 9);
//System.out.println("max="+max);
//print99();
char res = getLevel(88);
System.out.println("result="+res);
}
//需求1:求和功能
public static int add(int a,int b){
return a+b;
}
//需求2:画一个矩形在控制台
public static void draw(int row,int col){
for(int x=1;x<=row;x++){
for(int y=1;y<=col;y++){
System.out.print("*");
}
System.out.println();
}
}
//需求 3:比较两个数是否相等
public static boolean equal(int a,int b){
return a==b;
}
//需求4:比较两个数较大的那个
public static int getMax(int a,int b){
return a>b?a:b;
}
//需求5:打印99乘法表
public static void print99(){
for(int x=1;x<=9;x++){
for(int y=1;y<=x;y++){
System.out.print(y+"*"+x+"="+y*x+"\t");
}
System.out.println();
}
}
//需求6:根据考试成绩获取学生分数对应的等级
/*90~100 A
80~89 B
70~79 res
60~69 D
60以下 E
*/
public static char getLevel(int num){
char res;
if(num>=90 && num<=100){
res = 'A';
}else if(num>=80 && num<=89){
res = 'B';
}else if(num>=70 && num<=79){
res = 'C';
}else if(num>=60 && num<=69){
res = 'D';
}else{
res = 'E';
}
return res;
}
}
| 2,850 | 0.411101 | 0.382047 | 96 | 23.020834 | 14.773272 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46875 | false | false |
3
|
09697fdde41ab0dedf908f353472b52b89681351
| 25,821,343,421,493 |
60abe6fcff03427de6424d43668f3a36a58e543f
|
/jyshop-admin/src/main/java/com/qyy/jyshop/admin/giftpackage/service/GiftPackageGalleryService.java
|
c5d49fbd33ade135137e6a669c20999da696441f
|
[] |
no_license
|
git4wuwenping/jyshop
|
https://github.com/git4wuwenping/jyshop
|
dc987b6416b0fb594cb3d248ca1d88fd28a0ce53
|
9ce36394cdcb0514bd49cebddf3a464f6e32b4f6
|
refs/heads/master
| 2020-03-28T14:22:28.619000 | 2018-09-14T13:43:16 | 2018-09-14T13:43:16 | 148,481,972 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.qyy.jyshop.admin.giftpackage.service;
import com.qyy.jyshop.model.GiftPackageGallery;
import java.util.List;
public interface GiftPackageGalleryService {
/**
* 保存礼包相册
* @param imgs
* @param gpId
*/
void saveGiftPackageGallery(String[] imgs, Long gpId);
List<GiftPackageGallery> queryByGpId(Long gpId);
}
|
UTF-8
|
Java
| 364 |
java
|
GiftPackageGalleryService.java
|
Java
|
[] | null |
[] |
package com.qyy.jyshop.admin.giftpackage.service;
import com.qyy.jyshop.model.GiftPackageGallery;
import java.util.List;
public interface GiftPackageGalleryService {
/**
* 保存礼包相册
* @param imgs
* @param gpId
*/
void saveGiftPackageGallery(String[] imgs, Long gpId);
List<GiftPackageGallery> queryByGpId(Long gpId);
}
| 364 | 0.710227 | 0.710227 | 16 | 21 | 20.853657 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
3
|
886f465cb3f88040cd35ce79021eccda5468f2bc
| 21,320,217,705,127 |
43082a87212260403b07f59f2f8c47af474fed9c
|
/tf-enrich/src/main/java/eu/europeana/tf/agreement/EnrichmentAnnotation.java
|
c31920a042710e6d30fd1e2f094142816d4a1634
|
[
"CC0-1.0"
] |
permissive
|
hugomanguinhas/europeana
|
https://github.com/hugomanguinhas/europeana
|
07984067e4ecb72c8cd757460eac6a6efc0f3441
|
2344a06863403c692c1635ec72b522bd3028e6f6
|
refs/heads/master
| 2021-01-17T09:16:23.751000 | 2016-10-26T18:35:02 | 2016-10-26T18:35:02 | 40,169,326 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package eu.europeana.tf.agreement;
/**
* @author Hugo Manguinhas <hugo.manguinhas@europeana.eu>
* @since 23 Sep 2015
*/
public class EnrichmentAnnotation
{
private String _sample;
private Object _source;
private String _annotator;
private String _comments;
private AnnotationParameters _params;
public EnrichmentAnnotation(String sampleID, Object source, String annotator
, AnnotationParameters params, String comments)
{
_sample = sampleID;
_source = source;
_annotator = annotator;
_params = params;
_comments = comments;
}
public EnrichmentAnnotation(String sampleID, String ref, String annotator)
{
this(sampleID, ref, annotator, null, null);
}
public String getSampleID() { return _sample; }
public Object getSource() { return _source; }
public AnnotationParameters getParameters() { return _params; }
}
|
UTF-8
|
Java
| 1,049 |
java
|
EnrichmentAnnotation.java
|
Java
|
[
{
"context": "package eu.europeana.tf.agreement;\n\n/**\n * @author Hugo Manguinhas <hugo.manguinhas@europeana.eu>\n * @since 23 Sep 2",
"end": 66,
"score": 0.9998872876167297,
"start": 51,
"tag": "NAME",
"value": "Hugo Manguinhas"
},
{
"context": "na.tf.agreement;\n\n/**\n * @author Hugo Manguinhas <hugo.manguinhas@europeana.eu>\n * @since 23 Sep 2015\n */\npublic class Enrichmen",
"end": 96,
"score": 0.9999371767044067,
"start": 68,
"tag": "EMAIL",
"value": "hugo.manguinhas@europeana.eu"
}
] | null |
[] |
package eu.europeana.tf.agreement;
/**
* @author <NAME> <<EMAIL>>
* @since 23 Sep 2015
*/
public class EnrichmentAnnotation
{
private String _sample;
private Object _source;
private String _annotator;
private String _comments;
private AnnotationParameters _params;
public EnrichmentAnnotation(String sampleID, Object source, String annotator
, AnnotationParameters params, String comments)
{
_sample = sampleID;
_source = source;
_annotator = annotator;
_params = params;
_comments = comments;
}
public EnrichmentAnnotation(String sampleID, String ref, String annotator)
{
this(sampleID, ref, annotator, null, null);
}
public String getSampleID() { return _sample; }
public Object getSource() { return _source; }
public AnnotationParameters getParameters() { return _params; }
}
| 1,019 | 0.597712 | 0.591992 | 33 | 30.818182 | 26.024994 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.757576 | false | false |
3
|
3120ba9943074d94191ece05745de03d99e87778
| 26,860,725,477,755 |
5dbcf5472817bd024dbf6911bdb3d168d1fde1d7
|
/src/main/java/com/shangma/cn/valid/group/UpdateGroup.java
|
33e0371f717a6ae3e5c1a7f7cbfb4a19a9569734
|
[] |
no_license
|
luozuishuai/crm-project
|
https://github.com/luozuishuai/crm-project
|
d0a22438304f2b9fd7f49b03ce3ea0d7648d9045
|
8587b54509508763663b3c8f4f95cf3b11b9c997
|
refs/heads/master
| 2023-03-02T21:23:43.980000 | 2021-02-04T06:01:24 | 2021-02-04T06:01:24 | 330,087,874 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.shangma.cn.valid.group;
public interface UpdateGroup {
}
|
UTF-8
|
Java
| 70 |
java
|
UpdateGroup.java
|
Java
|
[] | null |
[] |
package com.shangma.cn.valid.group;
public interface UpdateGroup {
}
| 70 | 0.785714 | 0.785714 | 4 | 16.5 | 16.101242 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
3
|
a191bd2bb2168b94be6307ec45fc76eb63d715c3
| 10,677,288,711,343 |
ed865190ed878874174df0493b4268fccb636a29
|
/PuridiomCommon/src/com/tsa/puridiom/doccomment/tasks/DocCommentSetValuesFromStdComment.java
|
33aa9ba2878f6a472ae27045f96f01e4fb66141e
|
[] |
no_license
|
zach-hu/srr_java8
|
https://github.com/zach-hu/srr_java8
|
6841936eda9fdcc2e8185b85b4a524b509ea4b1b
|
9b6096ba76e54da3fe7eba70989978edb5a33d8e
|
refs/heads/master
| 2021-01-10T00:57:42.107000 | 2015-11-06T14:12:56 | 2015-11-06T14:12:56 | 45,641,885 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tsa.puridiom.doccomment.tasks;
import com.tsa.puridiom.entity.StdComment;
import com.tsagate.foundation.processengine.*;
import com.tsagate.foundation.utility.UniqueKeyGenerator;
import com.tsagate.foundation.utility.Utility;
import java.math.BigDecimal;
import java.util.Map;
public class DocCommentSetValuesFromStdComment extends Task
{
public Object executeTask(Object object) throws Exception
{
Map incomingRequest = (Map)object;
Object result = null;
try
{
StdComment stdComment = (StdComment) incomingRequest.get("stdComment");
String commentPublic = stdComment.getCommentPublic();
String icText = "";
BigDecimal bdText = stdComment.getIcText();
if (bdText == null)
{
icText = "0";
}
else
{
icText = bdText.toString();
}
if (commentPublic.equalsIgnoreCase("Y"))
{
UniqueKeyGenerator ukg = UniqueKeyGenerator.getInstance();
icText = ukg.getUniqueKey().toString();
incomingRequest.put("DocComment_commentSource", "ST*");
}
else
{
incomingRequest.put("DocComment_commentSource", "STD");
}
incomingRequest.put("DocComment_icText", icText);
incomingRequest.put("DocComment_referenceType", incomingRequest.get("Default_referenceType"));
incomingRequest.put("DocComment_commentPlace", incomingRequest.get("Default_commentPlace"));
incomingRequest.put("DocComment_icHeader", incomingRequest.get("DocComment_icHeader"));
incomingRequest.put("DocComment_icLine", incomingRequest.get("DocComment_icLine"));
incomingRequest.put("DocComment_commentOrder", "0");
incomingRequest.put("DocComment_commentId", stdComment.getCommentId());
incomingRequest.put("DocComment_commentTitle", stdComment.getCommentTitle());
//incomingRequest.put("DocComment_IcText", stdComment.getIcText());
incomingRequest.put("DocComment_commentPrint", stdComment.getCommentPrint());
//incomingRequest.put("DocComment_commentPlace", stdComment.getCommentPlace());
incomingRequest.put("DocComment_commentBold", stdComment.getCommentBold());
incomingRequest.put("DocComment_commentPublic", stdComment.getCommentPublic());
//incomingRequest.put("DocComment_commentWebpost", stdComment.getCommentWebpost());
this.status = Status.SUCCEEDED;
}
catch (Exception e)
{
this.status = Status.FAILED;
throw e;
}
return result;
}
}
|
UTF-8
|
Java
| 2,369 |
java
|
DocCommentSetValuesFromStdComment.java
|
Java
|
[] | null |
[] |
package com.tsa.puridiom.doccomment.tasks;
import com.tsa.puridiom.entity.StdComment;
import com.tsagate.foundation.processengine.*;
import com.tsagate.foundation.utility.UniqueKeyGenerator;
import com.tsagate.foundation.utility.Utility;
import java.math.BigDecimal;
import java.util.Map;
public class DocCommentSetValuesFromStdComment extends Task
{
public Object executeTask(Object object) throws Exception
{
Map incomingRequest = (Map)object;
Object result = null;
try
{
StdComment stdComment = (StdComment) incomingRequest.get("stdComment");
String commentPublic = stdComment.getCommentPublic();
String icText = "";
BigDecimal bdText = stdComment.getIcText();
if (bdText == null)
{
icText = "0";
}
else
{
icText = bdText.toString();
}
if (commentPublic.equalsIgnoreCase("Y"))
{
UniqueKeyGenerator ukg = UniqueKeyGenerator.getInstance();
icText = ukg.getUniqueKey().toString();
incomingRequest.put("DocComment_commentSource", "ST*");
}
else
{
incomingRequest.put("DocComment_commentSource", "STD");
}
incomingRequest.put("DocComment_icText", icText);
incomingRequest.put("DocComment_referenceType", incomingRequest.get("Default_referenceType"));
incomingRequest.put("DocComment_commentPlace", incomingRequest.get("Default_commentPlace"));
incomingRequest.put("DocComment_icHeader", incomingRequest.get("DocComment_icHeader"));
incomingRequest.put("DocComment_icLine", incomingRequest.get("DocComment_icLine"));
incomingRequest.put("DocComment_commentOrder", "0");
incomingRequest.put("DocComment_commentId", stdComment.getCommentId());
incomingRequest.put("DocComment_commentTitle", stdComment.getCommentTitle());
//incomingRequest.put("DocComment_IcText", stdComment.getIcText());
incomingRequest.put("DocComment_commentPrint", stdComment.getCommentPrint());
//incomingRequest.put("DocComment_commentPlace", stdComment.getCommentPlace());
incomingRequest.put("DocComment_commentBold", stdComment.getCommentBold());
incomingRequest.put("DocComment_commentPublic", stdComment.getCommentPublic());
//incomingRequest.put("DocComment_commentWebpost", stdComment.getCommentWebpost());
this.status = Status.SUCCEEDED;
}
catch (Exception e)
{
this.status = Status.FAILED;
throw e;
}
return result;
}
}
| 2,369 | 0.739553 | 0.738708 | 69 | 33.347828 | 30.622444 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.173913 | false | false |
3
|
ccd7eeacfac9d4d4aacd6ee023fec607b7afa55d
| 9,156,870,299,948 |
652616447f470815b9a4c74ca0fbd661788d66fd
|
/src/main/java/br/com/cfinancial/dao/ChurchDAO.java
|
4a1be89915207a6ce2142f499c8c19f0990d4d6b
|
[] |
no_license
|
widoming/adourinhos
|
https://github.com/widoming/adourinhos
|
3bfa9a352b8a5bef325c4cce125e71776613f515
|
0e5046924d25049b4ba93edcfab6e247ab58ff23
|
refs/heads/master
| 2021-04-18T18:45:39.648000 | 2018-04-06T03:16:02 | 2018-04-06T03:16:02 | 126,909,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.cfinancial.dao;
public class ChurchDAO {
}
|
UTF-8
|
Java
| 65 |
java
|
ChurchDAO.java
|
Java
|
[] | null |
[] |
package br.com.cfinancial.dao;
public class ChurchDAO {
}
| 65 | 0.692308 | 0.692308 | 5 | 11 | 13.206059 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
3
|
3673479dcae0694e5fb05e605955b1354a19d03e
| 18,476,949,337,139 |
24a27cbf7f065d6eb67f70c67bb7d758d70d7415
|
/TeamS355/app/src/main/java/com/cmsc355/teams/EndZoneObject.java
|
0b0492fc1e7cbde464a97119ddcd63308ea11bc3
|
[] |
no_license
|
samsoncr/CMSC-355-Team-S
|
https://github.com/samsoncr/CMSC-355-Team-S
|
9f0802a4ad6d3473800df3c1358948eb9d2340a7
|
8c04c0688675686aa043c66d311562b16814d809
|
refs/heads/master
| 2023-01-29T08:34:22.788000 | 2020-12-10T03:14:51 | 2020-12-10T03:14:51 | 291,781,996 | 0 | 1 | null | false | 2020-12-10T03:19:32 | 2020-08-31T17:35:16 | 2020-12-10T03:14:54 | 2020-12-10T03:19:31 | 39,844 | 0 | 1 | 2 |
Java
| false | false |
package com.cmsc355.teams;
public class EndZoneObject extends GameObject{
}
|
UTF-8
|
Java
| 77 |
java
|
EndZoneObject.java
|
Java
|
[] | null |
[] |
package com.cmsc355.teams;
public class EndZoneObject extends GameObject{
}
| 77 | 0.818182 | 0.779221 | 4 | 18.25 | 19.10988 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
3
|
e72f2bb1b76b13f7d335e6a1c21a94bb8caa7676
| 32,796,370,319,434 |
f7c62e6e7d11132c8cbe87e94b0b0ba0fcd1e88c
|
/src/seleniumrevision/com/Table_example.java
|
63e1e7faf628b35c0475f88bf06657d5e42c657e
|
[] |
no_license
|
JaminAnsari/Seleniumrevision
|
https://github.com/JaminAnsari/Seleniumrevision
|
e0e732767b76d307cf7a2f7b3f5ba1291b8f16e6
|
a8858c62b34c2f4024c0ecf6356caacaff14b608
|
refs/heads/main
| 2023-06-16T09:58:29.367000 | 2021-07-15T05:15:22 | 2021-07-15T05:15:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package seleniumrevision.com;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Table_example {
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ELCOT\\Desktop\\eclipse\\Selenium_pro\\Browsers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.leafground.com/pages/table.html");
List<WebElement> numberOfColumns = driver.findElements(By.tagName("th"));
int size = numberOfColumns.size();
System.out.println(size);
List<WebElement> numberOfRows = driver.findElements(By.tagName("tr"));
int size2 = numberOfRows.size();
System.out.println(size2);
WebElement learnInteract = driver.findElement(By.xpath("//*[text()='Learn to interact with Elements']//following::td[1]"));
String text = learnInteract.getText();
System.out.println(text);
List<WebElement> leastNumber = driver.findElements(By.xpath("//td[2]"));
ArrayList<Integer> covertstring = new ArrayList<>();
for (WebElement string : leastNumber) {
String remove = string.getText().replace("%", "");
covertstring.add(Integer.parseInt(remove));
}
System.out.println(covertstring);
Integer min = Collections.min(covertstring);
System.out.println(min+"%");
//String xpath = ""/""+min+"/"";
}
}
|
UTF-8
|
Java
| 1,653 |
java
|
Table_example.java
|
Java
|
[] | null |
[] |
package seleniumrevision.com;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Table_example {
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ELCOT\\Desktop\\eclipse\\Selenium_pro\\Browsers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.leafground.com/pages/table.html");
List<WebElement> numberOfColumns = driver.findElements(By.tagName("th"));
int size = numberOfColumns.size();
System.out.println(size);
List<WebElement> numberOfRows = driver.findElements(By.tagName("tr"));
int size2 = numberOfRows.size();
System.out.println(size2);
WebElement learnInteract = driver.findElement(By.xpath("//*[text()='Learn to interact with Elements']//following::td[1]"));
String text = learnInteract.getText();
System.out.println(text);
List<WebElement> leastNumber = driver.findElements(By.xpath("//td[2]"));
ArrayList<Integer> covertstring = new ArrayList<>();
for (WebElement string : leastNumber) {
String remove = string.getText().replace("%", "");
covertstring.add(Integer.parseInt(remove));
}
System.out.println(covertstring);
Integer min = Collections.min(covertstring);
System.out.println(min+"%");
//String xpath = ""/""+min+"/"";
}
}
| 1,653 | 0.678766 | 0.676346 | 71 | 22.281691 | 27.406273 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.140845 | false | false |
3
|
a7a99cb5bb260bba81277602c4db25b3837b852f
| 16,071,767,666,200 |
2b4a9981e87f869d66ebf88f51125d50f43a0da4
|
/app/src/main/java/viviant/cn/weeklyplan/okhttp/AbstractBaseOkHttp.java
|
2d4d10ff610439df2e5784fffd0b68b623fc6539
|
[] |
no_license
|
viviant1224/WeeklyPlan
|
https://github.com/viviant1224/WeeklyPlan
|
37866bfcbe67beda70078255af332cf852bf25e8
|
7dd17511b15cefffa1fb3e81bb19bf2f1b967c61
|
refs/heads/master
| 2021-01-21T04:59:26.977000 | 2016-06-14T14:43:29 | 2016-06-14T14:43:29 | 54,562,097 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package viviant.cn.weeklyplan.okhttp;
import android.content.Context;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import viviant.cn.weeklyplan.exception.e.ErrorMessageFactory;
import viviant.cn.weeklyplan.i.IOkHttpClient;
import viviant.cn.weeklyplan.i.IOkHttpPrintLog;
import viviant.cn.weeklyplan.log.PrintLogUtil;
import viviant.cn.weeklyplan.okhttp.cookies.PersistentCookieJar;
import viviant.cn.weeklyplan.okhttp.cookies.cache.SetCookieCache;
import viviant.cn.weeklyplan.okhttp.cookies.persistence.SharedPrefsCookiePersistor;
import viviant.cn.weeklyplan.util.ExternalStorageUtil;
import viviant.cn.weeklyplan.util.TimeUtils;
/**
* 类描述: 创建人:hww 创建时间:2016/05/03 14:03 修改人:Administrator
* 修改时间:2016/5/03 14:03 修改备注:
*/
public abstract class AbstractBaseOkHttp implements IOkHttpClient, IOkHttpPrintLog {
private static OkHttpClient.Builder okHttpClientBuilder;
/**
* get请求参数 Bundle key
*/
public static final String BUNDLE_GET_KEY = "BUNDLE_GET_KEY";
/**
* post/put 请求参数 Bundle key
*/
public static final String BUNDLE_POST_OR_PUT_KEY = "BUNDLE_POST_OR_PUT_KEY";
protected Context context;
protected Bundle bundle;
/**
* 网络请求 异常信息
*/
protected String errorMessage;
protected String requestTime;
protected String responseTime;
protected String requestJson;
int cacheSize = 10 * 1024 * 1024; // 10 MiB
/**
* 获取HttpClient
*
* @return
*/
@Override
public OkHttpClient getOkHttpClient() {
okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.connectTimeout(30, TimeUnit.SECONDS);
okHttpClientBuilder.cache(new Cache(new File(ExternalStorageUtil.getExternalDownloadPath() + File.separator + "cache.tmp"), cacheSize));
okHttpClientBuilder.cookieJar(new PersistentCookieJar(new SetCookieCache(),new SharedPrefsCookiePersistor(context)));
return okHttpClientBuilder.build();
}
/**
* 请求配置
*
* @return
*/
@Override
public Request.Builder getRequestBuilder() {
return new Request.Builder().addHeader(HttpConstant.CONTENT_TYPE_KEY, HttpConstant.CONTENT_TYPE).addHeader(HttpConstant.ACCEPT_KEY, HttpConstant.ACCEPT);
}
/**
* 处理接口返回
*
* @return
*/
@Override
public Callback getResponseCallBack() {
return new Callback() {
@Override
public void onFailure(Call call, IOException e) {
onFailed(e);
}
@Override
public void onResponse(Call call, Response response){
try {
if (response.isSuccessful()) {
responseTime = TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"));
onSuccess(response);
} else {
onFailed(new IOException("onFailed" + response));
}
} catch (IOException e) {
onFailed(e);
}
}
};
}
/**
* 如果子类需要处理失败信息 重写该方法
*
* @param exception
*/
@Override
public void onFailed(Exception exception) {
responseTime = TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"));
errorMessage = ErrorMessageFactory.createMessage(exception);
printLog();
// 通知前台更新 失败后返回子类对象 在Activity里注册子类的监听
// com.orhanobut.logger.Logger.e(errorMessage);
}
/**
* 启动网络请求
*/
@Override
public void execute() {
getOkHttpClient().newCall(getRequest()).enqueue(getResponseCallBack());
requestTime = TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"));
}
/**
* 打印日志
*/
@Override
public void printLog() {
PrintLogUtil.createPrintLogToSdCard(context, this);
}
public String getErrorMessage() {
return errorMessage;
}
public String getRequestTime() {
return requestTime;
}
public String getResponseTime() {
return responseTime;
}
public String getRequestJson() {
return requestJson;
}
public Bundle getBundle() {
return bundle;
}
public void setBundle(Bundle bundle) {
this.bundle = bundle;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
|
UTF-8
|
Java
| 5,007 |
java
|
AbstractBaseOkHttp.java
|
Java
|
[
{
"context": "t.cn.weeklyplan.util.TimeUtils;\n\n/**\n * 类描述: 创建人:hww 创建时间:2016/05/03 14:03 修改人:Administrator\n * 修改时间:2",
"end": 907,
"score": 0.9958139061927795,
"start": 904,
"tag": "USERNAME",
"value": "hww"
}
] | null |
[] |
package viviant.cn.weeklyplan.okhttp;
import android.content.Context;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import viviant.cn.weeklyplan.exception.e.ErrorMessageFactory;
import viviant.cn.weeklyplan.i.IOkHttpClient;
import viviant.cn.weeklyplan.i.IOkHttpPrintLog;
import viviant.cn.weeklyplan.log.PrintLogUtil;
import viviant.cn.weeklyplan.okhttp.cookies.PersistentCookieJar;
import viviant.cn.weeklyplan.okhttp.cookies.cache.SetCookieCache;
import viviant.cn.weeklyplan.okhttp.cookies.persistence.SharedPrefsCookiePersistor;
import viviant.cn.weeklyplan.util.ExternalStorageUtil;
import viviant.cn.weeklyplan.util.TimeUtils;
/**
* 类描述: 创建人:hww 创建时间:2016/05/03 14:03 修改人:Administrator
* 修改时间:2016/5/03 14:03 修改备注:
*/
public abstract class AbstractBaseOkHttp implements IOkHttpClient, IOkHttpPrintLog {
private static OkHttpClient.Builder okHttpClientBuilder;
/**
* get请求参数 Bundle key
*/
public static final String BUNDLE_GET_KEY = "BUNDLE_GET_KEY";
/**
* post/put 请求参数 Bundle key
*/
public static final String BUNDLE_POST_OR_PUT_KEY = "BUNDLE_POST_OR_PUT_KEY";
protected Context context;
protected Bundle bundle;
/**
* 网络请求 异常信息
*/
protected String errorMessage;
protected String requestTime;
protected String responseTime;
protected String requestJson;
int cacheSize = 10 * 1024 * 1024; // 10 MiB
/**
* 获取HttpClient
*
* @return
*/
@Override
public OkHttpClient getOkHttpClient() {
okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.connectTimeout(30, TimeUnit.SECONDS);
okHttpClientBuilder.cache(new Cache(new File(ExternalStorageUtil.getExternalDownloadPath() + File.separator + "cache.tmp"), cacheSize));
okHttpClientBuilder.cookieJar(new PersistentCookieJar(new SetCookieCache(),new SharedPrefsCookiePersistor(context)));
return okHttpClientBuilder.build();
}
/**
* 请求配置
*
* @return
*/
@Override
public Request.Builder getRequestBuilder() {
return new Request.Builder().addHeader(HttpConstant.CONTENT_TYPE_KEY, HttpConstant.CONTENT_TYPE).addHeader(HttpConstant.ACCEPT_KEY, HttpConstant.ACCEPT);
}
/**
* 处理接口返回
*
* @return
*/
@Override
public Callback getResponseCallBack() {
return new Callback() {
@Override
public void onFailure(Call call, IOException e) {
onFailed(e);
}
@Override
public void onResponse(Call call, Response response){
try {
if (response.isSuccessful()) {
responseTime = TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"));
onSuccess(response);
} else {
onFailed(new IOException("onFailed" + response));
}
} catch (IOException e) {
onFailed(e);
}
}
};
}
/**
* 如果子类需要处理失败信息 重写该方法
*
* @param exception
*/
@Override
public void onFailed(Exception exception) {
responseTime = TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"));
errorMessage = ErrorMessageFactory.createMessage(exception);
printLog();
// 通知前台更新 失败后返回子类对象 在Activity里注册子类的监听
// com.orhanobut.logger.Logger.e(errorMessage);
}
/**
* 启动网络请求
*/
@Override
public void execute() {
getOkHttpClient().newCall(getRequest()).enqueue(getResponseCallBack());
requestTime = TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒"));
}
/**
* 打印日志
*/
@Override
public void printLog() {
PrintLogUtil.createPrintLogToSdCard(context, this);
}
public String getErrorMessage() {
return errorMessage;
}
public String getRequestTime() {
return requestTime;
}
public String getResponseTime() {
return responseTime;
}
public String getRequestJson() {
return requestJson;
}
public Bundle getBundle() {
return bundle;
}
public void setBundle(Bundle bundle) {
this.bundle = bundle;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
| 5,007 | 0.649086 | 0.64005 | 173 | 26.508671 | 28.158022 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.393064 | false | false |
3
|
833764577a0ebe581b6bf7e66cb1543fd7585766
| 16,071,767,665,508 |
b6e72f8a6490a7e9b836f07f7af74c8f537b7ee3
|
/Metamodelar/src/Metamodelar/MCore/src/org/cvut/vrchlpet/MCore/core/Property.java
|
54baa7a7e782c343e6758708aeaf3a3339250bd1
|
[] |
no_license
|
vrchlpet/mmnp
|
https://github.com/vrchlpet/mmnp
|
c162a63688346265f00f8dddab4a9385b54ea0da
|
f0b0a8bd2edd15fcd2019dbb560e2a042be750fb
|
refs/heads/master
| 2021-01-18T11:20:05.983000 | 2011-05-22T21:33:20 | 2011-05-22T21:33:20 | 1,257,993 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.cvut.vrchlpet.MCore.core;
/**
*
* Trida reprezentuje vlastnost elementu
*
* @author Vrchlavsky Petr
* @version 1.0
*/
public class Property extends StructuralFeature{
public static final MData DEFAULT_TYEP = MData.STRING;
// datovy typ
private MData mData;
// data
private Object value;
public Property() {
this.mData = DEFAULT_TYEP;
this.value = mData.getDefault();
}
public Property(MData mData) {
this.mData = mData;
this.value = mData.getDefault();
}
/**
* @return the mData
*/
public MData getmData() {
return mData;
}
/**
* @param mData the mData to set
*/
public void setMData(MData mData) {
MData old = this.mData;
this.mData = mData;
firePropertyChange("mData", old, this.mData);
if ( !mData.getClass().isInstance(value))
setValue(mData.getDefault());
}
/**
* @return the defaultValue
*/
public Object getValue() {
return value;
}
/**
* @param defaultValue the defaultValue to set
*/
public void setValue(Object defaultValue) {
if ( !this.mData.getDataClass().isInstance(defaultValue))
throw new IllegalArgumentException(defaultValue + ": cannot be "
+ "assigned to this property. Incompatible types!");
Object old = this.value;
this.value = defaultValue;
firePropertyChange("defaultValue", old, this.value);
}
}
|
UTF-8
|
Java
| 1,571 |
java
|
Property.java
|
Java
|
[
{
"context": "rida reprezentuje vlastnost elementu\n *\n * @author Vrchlavsky Petr\n * @version 1.0\n */\npublic class Property extends",
"end": 117,
"score": 0.9998811483383179,
"start": 102,
"tag": "NAME",
"value": "Vrchlavsky Petr"
}
] | null |
[] |
package org.cvut.vrchlpet.MCore.core;
/**
*
* Trida reprezentuje vlastnost elementu
*
* @author <NAME>
* @version 1.0
*/
public class Property extends StructuralFeature{
public static final MData DEFAULT_TYEP = MData.STRING;
// datovy typ
private MData mData;
// data
private Object value;
public Property() {
this.mData = DEFAULT_TYEP;
this.value = mData.getDefault();
}
public Property(MData mData) {
this.mData = mData;
this.value = mData.getDefault();
}
/**
* @return the mData
*/
public MData getmData() {
return mData;
}
/**
* @param mData the mData to set
*/
public void setMData(MData mData) {
MData old = this.mData;
this.mData = mData;
firePropertyChange("mData", old, this.mData);
if ( !mData.getClass().isInstance(value))
setValue(mData.getDefault());
}
/**
* @return the defaultValue
*/
public Object getValue() {
return value;
}
/**
* @param defaultValue the defaultValue to set
*/
public void setValue(Object defaultValue) {
if ( !this.mData.getDataClass().isInstance(defaultValue))
throw new IllegalArgumentException(defaultValue + ": cannot be "
+ "assigned to this property. Incompatible types!");
Object old = this.value;
this.value = defaultValue;
firePropertyChange("defaultValue", old, this.value);
}
}
| 1,562 | 0.576066 | 0.574793 | 74 | 20.216217 | 20.033937 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.297297 | false | false |
3
|
fc527c5051044f59e93d1e502f56d896f77055b4
| 15,857,019,286,469 |
e0733dcd6cfd00de4fb2edbf403d2ef698a653cc
|
/app/src/main/java/com/yxnne/mysides/dao/MessageDao.java
|
79cebd902d0e129c5cd2e1bebce7564d4e5de44b
|
[] |
no_license
|
yxnne/MySideApp_Recoding
|
https://github.com/yxnne/MySideApp_Recoding
|
0294f86d2648feb8570514a1463f83b397a6ddd8
|
659ac0e4e6c65127c2b64b0bb4e67d3f8e5ab8c9
|
refs/heads/master
| 2021-05-04T04:53:10.759000 | 2016-11-06T15:58:58 | 2016-11-06T15:58:58 | 70,908,015 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yxnne.mysides.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.yxnne.mysides.util.chat.ChatCommenUtil;
import com.yxnne.mysides.util.log.LogGenerator;
import org.jivesoftware.smack.packet.Message;
import java.util.ArrayList;
/**
* about message
* Created by Administrator on 2016/11/2.
*/
public class MessageDAO {
public static final String INSERT_IMAGE_TYPE = "i_m_a_g_e";
public static final String INSERT_AUDIO_TYPE = "a_u_d_i_o";
public static final String INSERT_MAP_TYPE = "m_a_p";
Context context;
public MessageDAO(Context context) {
this.context = context;
DBHelper dbHelper = null;
SQLiteDatabase sqLiteDatabase = null;
try {
//建一个message表
String sql = "create table if not exists message"
+ "(_id integer primary key," + "messageFrom text,"
+ "messageTo text," + "messageType text,"
+ "messageBody text)";
dbHelper = new DBHelper(context);
sqLiteDatabase = dbHelper.getWritableDatabase();
sqLiteDatabase.execSQL(sql);
} catch (Exception e) {
LogGenerator.getInstance().printError(e);
} finally {
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
if (dbHelper != null) {
dbHelper.close();
}
}
}
public int insert(Message message) {
int id = -1;
DBHelper dbHelper = null;
SQLiteDatabase sqLiteDatabase = null;
try {
ContentValues values = new ContentValues();
values.put("messageFrom", message.getFrom());
values.put("messageTo", message.getTo());
values.put("messageType", message.getType().toString());
String msg = judgeMsg(message);
values.put("messageBody", msg);
dbHelper = new DBHelper(context);
sqLiteDatabase = dbHelper.getWritableDatabase();
sqLiteDatabase.insert("message", null, values);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
if (dbHelper != null) {
dbHelper.close();
}
}
return id;
}
/**
* 判断类型 不同类型插入数据库的方式不同
* @param message msg
* @return str to insert
*/
private String judgeMsg(Message message) {
String strMsg = message.getBody();
int type = ChatCommenUtil.getType(strMsg);
switch (type){
case ChatCommenUtil.TYPE_IMAGE:
strMsg = INSERT_IMAGE_TYPE;
break;
case ChatCommenUtil.TYPE_MAP:
strMsg = INSERT_MAP_TYPE;
break;
case ChatCommenUtil.TYPE_AUDIO:
strMsg = INSERT_AUDIO_TYPE;
break;
}
return strMsg;
}
public ArrayList<Message> query(String friendUser) {
ArrayList<Message> list = null;
DBHelper dbHelper = null;
SQLiteDatabase sqLiteDatabase = null;
Cursor cursor = null;
try {
dbHelper = new DBHelper(context);
sqLiteDatabase = dbHelper.getWritableDatabase();
String[] columns = { "messageFrom", "messageTo", "messageType",
"messageBody" };
String selection = "messageTo=? or messageFrom like ?";
String[] selectionArgs = { friendUser, friendUser+"%" };
cursor = sqLiteDatabase.query("message", columns, selection,
selectionArgs, null, null, "_id asc");
list = new ArrayList<Message>();
while (cursor.moveToNext()) {
String from = cursor.getString(cursor
.getColumnIndex("messageFrom"));
String to = cursor
.getString(cursor.getColumnIndex("messageTo"));
String type = cursor.getString(cursor
.getColumnIndex("messageType"));
String body = cursor.getString(cursor
.getColumnIndex("messageBody"));
Message message = new Message();
message.setFrom(from);
message.setTo(to);
message.setBody(body);
if ("chat".equals(type)) {
message.setType(Message.Type.chat);
}
list.add(message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
if (dbHelper != null) {
dbHelper.close();
}
}
return list;
}
}
|
UTF-8
|
Java
| 5,121 |
java
|
MessageDao.java
|
Java
|
[] | null |
[] |
package com.yxnne.mysides.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.yxnne.mysides.util.chat.ChatCommenUtil;
import com.yxnne.mysides.util.log.LogGenerator;
import org.jivesoftware.smack.packet.Message;
import java.util.ArrayList;
/**
* about message
* Created by Administrator on 2016/11/2.
*/
public class MessageDAO {
public static final String INSERT_IMAGE_TYPE = "i_m_a_g_e";
public static final String INSERT_AUDIO_TYPE = "a_u_d_i_o";
public static final String INSERT_MAP_TYPE = "m_a_p";
Context context;
public MessageDAO(Context context) {
this.context = context;
DBHelper dbHelper = null;
SQLiteDatabase sqLiteDatabase = null;
try {
//建一个message表
String sql = "create table if not exists message"
+ "(_id integer primary key," + "messageFrom text,"
+ "messageTo text," + "messageType text,"
+ "messageBody text)";
dbHelper = new DBHelper(context);
sqLiteDatabase = dbHelper.getWritableDatabase();
sqLiteDatabase.execSQL(sql);
} catch (Exception e) {
LogGenerator.getInstance().printError(e);
} finally {
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
if (dbHelper != null) {
dbHelper.close();
}
}
}
public int insert(Message message) {
int id = -1;
DBHelper dbHelper = null;
SQLiteDatabase sqLiteDatabase = null;
try {
ContentValues values = new ContentValues();
values.put("messageFrom", message.getFrom());
values.put("messageTo", message.getTo());
values.put("messageType", message.getType().toString());
String msg = judgeMsg(message);
values.put("messageBody", msg);
dbHelper = new DBHelper(context);
sqLiteDatabase = dbHelper.getWritableDatabase();
sqLiteDatabase.insert("message", null, values);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
if (dbHelper != null) {
dbHelper.close();
}
}
return id;
}
/**
* 判断类型 不同类型插入数据库的方式不同
* @param message msg
* @return str to insert
*/
private String judgeMsg(Message message) {
String strMsg = message.getBody();
int type = ChatCommenUtil.getType(strMsg);
switch (type){
case ChatCommenUtil.TYPE_IMAGE:
strMsg = INSERT_IMAGE_TYPE;
break;
case ChatCommenUtil.TYPE_MAP:
strMsg = INSERT_MAP_TYPE;
break;
case ChatCommenUtil.TYPE_AUDIO:
strMsg = INSERT_AUDIO_TYPE;
break;
}
return strMsg;
}
public ArrayList<Message> query(String friendUser) {
ArrayList<Message> list = null;
DBHelper dbHelper = null;
SQLiteDatabase sqLiteDatabase = null;
Cursor cursor = null;
try {
dbHelper = new DBHelper(context);
sqLiteDatabase = dbHelper.getWritableDatabase();
String[] columns = { "messageFrom", "messageTo", "messageType",
"messageBody" };
String selection = "messageTo=? or messageFrom like ?";
String[] selectionArgs = { friendUser, friendUser+"%" };
cursor = sqLiteDatabase.query("message", columns, selection,
selectionArgs, null, null, "_id asc");
list = new ArrayList<Message>();
while (cursor.moveToNext()) {
String from = cursor.getString(cursor
.getColumnIndex("messageFrom"));
String to = cursor
.getString(cursor.getColumnIndex("messageTo"));
String type = cursor.getString(cursor
.getColumnIndex("messageType"));
String body = cursor.getString(cursor
.getColumnIndex("messageBody"));
Message message = new Message();
message.setFrom(from);
message.setTo(to);
message.setBody(body);
if ("chat".equals(type)) {
message.setType(Message.Type.chat);
}
list.add(message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
if (sqLiteDatabase != null) {
sqLiteDatabase.close();
}
if (dbHelper != null) {
dbHelper.close();
}
}
return list;
}
}
| 5,121 | 0.533189 | 0.531613 | 153 | 32.183006 | 19.816952 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.614379 | false | false |
3
|
011d4298d0bdc9eb1a90008855096d14980fca26
| 7,894,149,930,975 |
1bdaa44193247aa6af88bfef94833e86fe1b94d0
|
/src/com/vms/servlets/AddDriverAttendance.java
|
1431b7808ac9ae8db225100e099a9c4da932f0ca
|
[] |
no_license
|
kishaningithub/VMS
|
https://github.com/kishaningithub/VMS
|
7beb7202094762daefcdd663421a011702eff23f
|
8eda48508d93434b521862fe85cf5f3b4414898b
|
refs/heads/master
| 2021-01-09T05:59:22.350000 | 2016-04-22T11:57:33 | 2016-04-22T11:57:33 | 4,703,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vms.servlets;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import com.vms.dao.DriverAttendanceDAO;
import com.vms.dto.DriverAttendanceDTO;
import com.vms.dto.DriverAttendanceDTO;
import com.vms.dto.DriverDetailsDTO;
import com.vms.dto.VehicleDetailsDTO;
import com.vms.util.VmsSessionFactory;
/**
* Servlet implementation class AddDriverAttendance
*/
public class AddDriverAttendance extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddDriverAttendance() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DriverAttendanceDTO driverAttendanceDetails = new DriverAttendanceDTO();
SessionFactory sessionFactory=VmsSessionFactory.getSessionFactory();
Session session=sessionFactory.openSession();
try {
DriverAttendanceDTO driverAtt=new DriverAttendanceDTO();
DateFormat dateFormater=new SimpleDateFormat("dd/MMM/yyyy");
session.beginTransaction();
driverAtt.getAttId().setDateOfAtt((dateFormater.parse(request.getParameter("dateOfAtt").trim())));
driverAtt.getAttId().setLicenceNo((DriverDetailsDTO)session.get(DriverDetailsDTO.class,request.getParameter("licenceNo").trim()));
driverAttendanceDetails.setVehicleNo((VehicleDetailsDTO)session.get(VehicleDetailsDTO.class,request.getParameter("vehicleNo").trim()));
if(driverAtt.getAttId().getLicenceNo()==null)
throw new IllegalArgumentException("The given License No. does not exist");
else if(driverAttendanceDetails.getVehicleNo()==null)
throw new IllegalArgumentException("The given vehicle No. does not exist");
driverAttendanceDetails.setPresent(new Boolean(request.getParameter("present").trim()));
driverAttendanceDetails.setOverTime(Integer.parseInt(request.getParameter("overTime").trim()));
driverAttendanceDetails.setRecordStatus(request.getParameter("recordStatus").trim());
new DriverAttendanceDAO().addDriverAttendance(driverAttendanceDetails);
}
catch (NumberFormatException e) {
response.setStatus(500);
response.getWriter().print("Please enter proper value in overtime");
}
catch (IllegalArgumentException e) {
response.setStatus(500);
response.getWriter().print(e.getMessage());
}
catch (ParseException e) {
response.setStatus(500);
response.getWriter().print("Please enter proper dates");
}
catch (ConstraintViolationException e) {
response.setStatus(500);
response.getWriter().print("Cannot put attendance for a person more than once");
}
catch (NullPointerException e) {
response.setStatus(403);
response.getWriter().print("Hacker Get Lost!");
}
finally{
session.close();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
UTF-8
|
Java
| 3,514 |
java
|
AddDriverAttendance.java
|
Java
|
[] | null |
[] |
package com.vms.servlets;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import com.vms.dao.DriverAttendanceDAO;
import com.vms.dto.DriverAttendanceDTO;
import com.vms.dto.DriverAttendanceDTO;
import com.vms.dto.DriverDetailsDTO;
import com.vms.dto.VehicleDetailsDTO;
import com.vms.util.VmsSessionFactory;
/**
* Servlet implementation class AddDriverAttendance
*/
public class AddDriverAttendance extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddDriverAttendance() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DriverAttendanceDTO driverAttendanceDetails = new DriverAttendanceDTO();
SessionFactory sessionFactory=VmsSessionFactory.getSessionFactory();
Session session=sessionFactory.openSession();
try {
DriverAttendanceDTO driverAtt=new DriverAttendanceDTO();
DateFormat dateFormater=new SimpleDateFormat("dd/MMM/yyyy");
session.beginTransaction();
driverAtt.getAttId().setDateOfAtt((dateFormater.parse(request.getParameter("dateOfAtt").trim())));
driverAtt.getAttId().setLicenceNo((DriverDetailsDTO)session.get(DriverDetailsDTO.class,request.getParameter("licenceNo").trim()));
driverAttendanceDetails.setVehicleNo((VehicleDetailsDTO)session.get(VehicleDetailsDTO.class,request.getParameter("vehicleNo").trim()));
if(driverAtt.getAttId().getLicenceNo()==null)
throw new IllegalArgumentException("The given License No. does not exist");
else if(driverAttendanceDetails.getVehicleNo()==null)
throw new IllegalArgumentException("The given vehicle No. does not exist");
driverAttendanceDetails.setPresent(new Boolean(request.getParameter("present").trim()));
driverAttendanceDetails.setOverTime(Integer.parseInt(request.getParameter("overTime").trim()));
driverAttendanceDetails.setRecordStatus(request.getParameter("recordStatus").trim());
new DriverAttendanceDAO().addDriverAttendance(driverAttendanceDetails);
}
catch (NumberFormatException e) {
response.setStatus(500);
response.getWriter().print("Please enter proper value in overtime");
}
catch (IllegalArgumentException e) {
response.setStatus(500);
response.getWriter().print(e.getMessage());
}
catch (ParseException e) {
response.setStatus(500);
response.getWriter().print("Please enter proper dates");
}
catch (ConstraintViolationException e) {
response.setStatus(500);
response.getWriter().print("Cannot put attendance for a person more than once");
}
catch (NullPointerException e) {
response.setStatus(403);
response.getWriter().print("Hacker Get Lost!");
}
finally{
session.close();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
| 3,514 | 0.782869 | 0.778315 | 93 | 36.784946 | 33.284969 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.010753 | false | false |
3
|
17bf874c0fd57e7a0fb84ce14b0cfdc7ab08abba
| 11,312,943,881,407 |
37250201c60c1b49004d90f8899475a69b35840f
|
/e3-content/e3-content-service/src/main/java/cn/e3mall/content/service/impl/ContentCarServiceImpl.java
|
54abcf4075f1d91047f10cad2d103a320e693e1b
|
[] |
no_license
|
1994xiaoquan/second
|
https://github.com/1994xiaoquan/second
|
c1032b0f64338dc5e87d7cc48705a35571a55227
|
648cdf2ca62db32dbd2b4c1a31a53c00b61436c2
|
refs/heads/master
| 2021-08-08T14:26:54.332000 | 2017-11-10T14:31:37 | 2017-11-10T14:31:37 | 109,706,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.e3mall.content.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.e3mall.content.service.ContentCarService;
import cn.e3mall.mapper.TbContentCategoryMapper;
import cn.e3mall.pojo.TbContentCategory;
import cn.e3mall.pojo.TbContentCategoryExample;
import cn.e3mall.pojo.TbContentCategoryExample.Criteria;
import cn.e3mall.pojo.TbContentExample;
import cn.e3mall.utils.E3mallResult;
import cn.e3mall.utils.TreeNode;
@Service
public class ContentCarServiceImpl implements ContentCarService{
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
/**
* 参数: 查询的父id
* 返回值: pageresult
* 需要订阅服务
*/
@Override
public List<TreeNode> findCatTreeNode(Long id) {
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(id);
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
List<TreeNode> treenodelist= new ArrayList<TreeNode>();
for (TbContentCategory tbContentCategory : list) {
TreeNode treeNode = new TreeNode();
treeNode.setId(tbContentCategory.getId());
treeNode.setState(tbContentCategory.getIsParent()?"closed":"open");
treeNode.setText(tbContentCategory.getName());
treenodelist.add(treeNode);
}
return treenodelist;
}
/**
* 新增节点
* 路径:/content/category/create
* 参数: parentId:node.parentId,name:node.text
* 返回值: E3mallresult
*/
@Override
public E3mallResult insertCat(Long parentId, String name) {
TbContentCategory contentCategory = new TbContentCategory();
contentCategory.setParentId(parentId);
contentCategory.setName(name);
//设置搜索顺序
contentCategory.setSortOrder(1);
//设置状态
contentCategory.setStatus(1);
//设置isparent
contentCategory.setIsParent(false);
//设置时间
Date data = new Date();
contentCategory.setCreated(data);
contentCategory.setUpdated(data);
//增加
contentCategoryMapper.insert(contentCategory);
//判断是否其父类是子节点
TbContentCategory parent = contentCategoryMapper.selectByPrimaryKey(parentId);
if(!parent.getIsParent()){
//改变父的isparent
parent.setIsParent(true);
contentCategoryMapper.updateByPrimaryKey(parent);
}
return E3mallResult.ok(contentCategory);
}
}
|
UTF-8
|
Java
| 2,574 |
java
|
ContentCarServiceImpl.java
|
Java
|
[] | null |
[] |
package cn.e3mall.content.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.e3mall.content.service.ContentCarService;
import cn.e3mall.mapper.TbContentCategoryMapper;
import cn.e3mall.pojo.TbContentCategory;
import cn.e3mall.pojo.TbContentCategoryExample;
import cn.e3mall.pojo.TbContentCategoryExample.Criteria;
import cn.e3mall.pojo.TbContentExample;
import cn.e3mall.utils.E3mallResult;
import cn.e3mall.utils.TreeNode;
@Service
public class ContentCarServiceImpl implements ContentCarService{
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
/**
* 参数: 查询的父id
* 返回值: pageresult
* 需要订阅服务
*/
@Override
public List<TreeNode> findCatTreeNode(Long id) {
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(id);
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
List<TreeNode> treenodelist= new ArrayList<TreeNode>();
for (TbContentCategory tbContentCategory : list) {
TreeNode treeNode = new TreeNode();
treeNode.setId(tbContentCategory.getId());
treeNode.setState(tbContentCategory.getIsParent()?"closed":"open");
treeNode.setText(tbContentCategory.getName());
treenodelist.add(treeNode);
}
return treenodelist;
}
/**
* 新增节点
* 路径:/content/category/create
* 参数: parentId:node.parentId,name:node.text
* 返回值: E3mallresult
*/
@Override
public E3mallResult insertCat(Long parentId, String name) {
TbContentCategory contentCategory = new TbContentCategory();
contentCategory.setParentId(parentId);
contentCategory.setName(name);
//设置搜索顺序
contentCategory.setSortOrder(1);
//设置状态
contentCategory.setStatus(1);
//设置isparent
contentCategory.setIsParent(false);
//设置时间
Date data = new Date();
contentCategory.setCreated(data);
contentCategory.setUpdated(data);
//增加
contentCategoryMapper.insert(contentCategory);
//判断是否其父类是子节点
TbContentCategory parent = contentCategoryMapper.selectByPrimaryKey(parentId);
if(!parent.getIsParent()){
//改变父的isparent
parent.setIsParent(true);
contentCategoryMapper.updateByPrimaryKey(parent);
}
return E3mallResult.ok(contentCategory);
}
}
| 2,574 | 0.753257 | 0.74715 | 81 | 28.320988 | 21.940338 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.802469 | false | false |
3
|
8dd0c8088ef7fd1a1e4ea415d9dc28e956d04e48
| 3,805,341,092,259 |
717956c98e5d3ca5a86a6421368f5bc5d9dd6a09
|
/PetStore/src/basics/MilkShelf.java
|
8f662afbad197f1b3b9940ac98963a1371982369
|
[
"MIT"
] |
permissive
|
sosostris/javapetmarket
|
https://github.com/sosostris/javapetmarket
|
a96dd373e6b264d5e0df7ec1449d9a6b812ff042
|
a6f04c9263167b53b4303b226fe6eb16dd18c28c
|
refs/heads/master
| 2021-01-10T19:09:01.006000 | 2015-01-15T02:13:57 | 2015-01-15T02:13:57 | 28,607,481 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package basics;
import java.util.Scanner;
public class MilkShelf {
public static void main(String args[]) {
String milkBrands[] = { "Guangming", "Shuangxi", "Mengniu", "Yili",
"Weiquan" };
String milkTypes[] = { "bottled milk", "yogurt" };
double[][] price = new double[5][2];
price[0][0] = 15.50;
price[0][1] = 4.00;
price[1][0] = 17.50;
price[1][1] = 5.00;
price[2][0] = 14.50;
price[2][1] = 4.00;
price[3][0] = 14.00;
price[3][1] = 4.50;
price[4][0] = 18.00;
price[4][1] = 5.50;
boolean userAnswer = true;
while (userAnswer) {
String userInputBrand = getUserInputBrand();
int brandIndex = findIndex(userInputBrand, milkBrands);
if (brandIndex == -1) {
System.out.println("Brand not found! Try again!");
continue;
}
int typeIndex;
String userInputType;
do {
userInputType = getUserInputType();
typeIndex = findIndex(userInputType, milkTypes);
if (typeIndex == -1) {
System.out.println("Type not found! Try again!");
}
} while (typeIndex == -1);
print(userInputBrand + " " + userInputType + " is "
+ price[brandIndex][typeIndex] + ".");
String userDecision = getUserDecision();
if (userDecision.equals("yes")) {
continue;
} else {
break;
}
}
}
static void print(String line) {
System.out.println(line);
}
static String getUserInputBrand() {
return getUserInput("Enter brand:");
}
static String getUserInputType() {
return getUserInput("Enter type:");
}
static String getUserMembership() {
return getUserInput("Enter your membership number:");
}
static String getUserDecision() {
return getUserInput("Query again? Enter yes to continue!");
}
static String getUserInput(String hint) {
Scanner reader = new Scanner(System.in);
System.out.println(hint);
String input = reader.nextLine();
return input;
}
static int findIndex(String value, String[] values) {
for (int i = 0; i < values.length; i++) {
if (value.equals(values[i])) {
return i;
}
}
return -1;
}
}
|
UTF-8
|
Java
| 2,033 |
java
|
MilkShelf.java
|
Java
|
[] | null |
[] |
package basics;
import java.util.Scanner;
public class MilkShelf {
public static void main(String args[]) {
String milkBrands[] = { "Guangming", "Shuangxi", "Mengniu", "Yili",
"Weiquan" };
String milkTypes[] = { "bottled milk", "yogurt" };
double[][] price = new double[5][2];
price[0][0] = 15.50;
price[0][1] = 4.00;
price[1][0] = 17.50;
price[1][1] = 5.00;
price[2][0] = 14.50;
price[2][1] = 4.00;
price[3][0] = 14.00;
price[3][1] = 4.50;
price[4][0] = 18.00;
price[4][1] = 5.50;
boolean userAnswer = true;
while (userAnswer) {
String userInputBrand = getUserInputBrand();
int brandIndex = findIndex(userInputBrand, milkBrands);
if (brandIndex == -1) {
System.out.println("Brand not found! Try again!");
continue;
}
int typeIndex;
String userInputType;
do {
userInputType = getUserInputType();
typeIndex = findIndex(userInputType, milkTypes);
if (typeIndex == -1) {
System.out.println("Type not found! Try again!");
}
} while (typeIndex == -1);
print(userInputBrand + " " + userInputType + " is "
+ price[brandIndex][typeIndex] + ".");
String userDecision = getUserDecision();
if (userDecision.equals("yes")) {
continue;
} else {
break;
}
}
}
static void print(String line) {
System.out.println(line);
}
static String getUserInputBrand() {
return getUserInput("Enter brand:");
}
static String getUserInputType() {
return getUserInput("Enter type:");
}
static String getUserMembership() {
return getUserInput("Enter your membership number:");
}
static String getUserDecision() {
return getUserInput("Query again? Enter yes to continue!");
}
static String getUserInput(String hint) {
Scanner reader = new Scanner(System.in);
System.out.println(hint);
String input = reader.nextLine();
return input;
}
static int findIndex(String value, String[] values) {
for (int i = 0; i < values.length; i++) {
if (value.equals(values[i])) {
return i;
}
}
return -1;
}
}
| 2,033 | 0.633055 | 0.602558 | 84 | 23.202381 | 18.418921 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.595238 | false | false |
3
|
221e8e3f102a5bf12414ac2b7d8f64a76ce0ee0d
| 5,978,594,534,604 |
8e5c4206ac814b0066becf35b8a9bbd8efd155bf
|
/src/edu/cs472/lab1/SearchNode.java
|
1fa67e690e0dbc53187513e78bba3dc981f6969d
|
[] |
no_license
|
roblourens/AI_Lab1
|
https://github.com/roblourens/AI_Lab1
|
ebc0e42b75ba2d3bd1d799ec65268c39f4c72dc6
|
b0525d194c2d8fe627ad6af40bba68ade4ab5107
|
refs/heads/master
| 2021-01-01T17:15:59.377000 | 2011-09-30T05:33:15 | 2011-09-30T05:33:15 | 2,484,580 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.cs472.lab1;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an action- not just a page, but the hyperlink leading to that page
*
* @author rob
*
*/
public class SearchNode
{
/**
* The URL that this node represents (entire path including file name)
*/
private final String nodeURL;
/**
* The file name of the node
*/
private final String nodeName;
/**
* The text associated with the link
*/
private final String hypertext;
/**
* The node from which this node was reached
*/
private final SearchNode parent;
/**
* The depth of this node in the search tree
*/
private final int depth;
/**
* The HTML contents of the file represented by this node
*/
private String contents;
/**
* The non-HTML text of the file
*/
private String textContents;
/**
* The child nodes of this SearchNode
*/
private List<SearchNode> children;
public SearchNode(String nodeName)
{
this(nodeName, null, null);
}
public SearchNode(String nodeURL, String hypertext, SearchNode parent)
{
this.nodeURL = nodeURL;
this.nodeName = new File(nodeURL).getName();
this.hypertext = Utilities.normalizeSearchString(hypertext);
this.parent = parent;
this.depth = parent == null ? 0 : parent.getDepth() + 1;
}
/**
* Prints the path from this node to the start node
*/
public void reportSolutionPath()
{
System.out.print(nodeName);
if (parent != null) {
System.out.print(" <- ");
parent.reportSolutionPath();
} else
System.out.println();
}
/**
* Returns true if this node matches the given goal pattern
*
* @throws Exception
* if called before expandNode
*/
public boolean isGoalForPattern(String goalPattern)
{
if (contents == null)
throw new RuntimeException("SearchNode " + nodeURL
+ ": isGoalForPattern cannot be called before expandNode");
return contents.indexOf(goalPattern) >= 0;
}
/**
* Loads the node's URL, discovers children
*
* @return new children
*/
private void expandNode()
{
if (contents == null) {
contents = Utilities.getFileContents(nodeURL);
List<SearchNode> children = new ArrayList<SearchNode>();
StringBuilder textContents = new StringBuilder();
for (String[] data : Utilities.getHyperlinksFromHTML(getContents(),
textContents)) {
String hyperlink = data[0];
String hypertext = data[1];
String parentPath = new File(nodeURL).getParent();
String newNodeURL = new File(parentPath, hyperlink).getPath();
children.add(new SearchNode(newNodeURL, hypertext, this));
}
this.children = children;
this.textContents = Utilities.normalizeSearchString(textContents
.toString());
}
}
public String getNodeURL()
{
return nodeURL;
}
public SearchNode getParent()
{
return parent;
}
public int getDepth()
{
return depth;
}
@Override
public String toString()
{
return nodeURL;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((nodeURL == null) ? 0 : nodeURL.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SearchNode other = (SearchNode) obj;
if (nodeURL == null) {
if (other.nodeURL != null)
return false;
} else if (!nodeURL.equals(other.nodeURL))
return false;
return true;
}
public String getHypertext()
{
return hypertext;
}
public String getNodeName()
{
return nodeName;
}
public String getContents()
{
expandNode();
return contents;
}
public String getTextContents()
{
expandNode();
return textContents;
}
public List<SearchNode> getChildren()
{
expandNode();
return children;
}
}
|
UTF-8
|
Java
| 4,597 |
java
|
SearchNode.java
|
Java
|
[
{
"context": " the hyperlink leading to that page\n * \n * @author rob\n * \n */\npublic class SearchNode\n{\n /**\n * ",
"end": 201,
"score": 0.9928887486457825,
"start": 198,
"tag": "USERNAME",
"value": "rob"
}
] | null |
[] |
package edu.cs472.lab1;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an action- not just a page, but the hyperlink leading to that page
*
* @author rob
*
*/
public class SearchNode
{
/**
* The URL that this node represents (entire path including file name)
*/
private final String nodeURL;
/**
* The file name of the node
*/
private final String nodeName;
/**
* The text associated with the link
*/
private final String hypertext;
/**
* The node from which this node was reached
*/
private final SearchNode parent;
/**
* The depth of this node in the search tree
*/
private final int depth;
/**
* The HTML contents of the file represented by this node
*/
private String contents;
/**
* The non-HTML text of the file
*/
private String textContents;
/**
* The child nodes of this SearchNode
*/
private List<SearchNode> children;
public SearchNode(String nodeName)
{
this(nodeName, null, null);
}
public SearchNode(String nodeURL, String hypertext, SearchNode parent)
{
this.nodeURL = nodeURL;
this.nodeName = new File(nodeURL).getName();
this.hypertext = Utilities.normalizeSearchString(hypertext);
this.parent = parent;
this.depth = parent == null ? 0 : parent.getDepth() + 1;
}
/**
* Prints the path from this node to the start node
*/
public void reportSolutionPath()
{
System.out.print(nodeName);
if (parent != null) {
System.out.print(" <- ");
parent.reportSolutionPath();
} else
System.out.println();
}
/**
* Returns true if this node matches the given goal pattern
*
* @throws Exception
* if called before expandNode
*/
public boolean isGoalForPattern(String goalPattern)
{
if (contents == null)
throw new RuntimeException("SearchNode " + nodeURL
+ ": isGoalForPattern cannot be called before expandNode");
return contents.indexOf(goalPattern) >= 0;
}
/**
* Loads the node's URL, discovers children
*
* @return new children
*/
private void expandNode()
{
if (contents == null) {
contents = Utilities.getFileContents(nodeURL);
List<SearchNode> children = new ArrayList<SearchNode>();
StringBuilder textContents = new StringBuilder();
for (String[] data : Utilities.getHyperlinksFromHTML(getContents(),
textContents)) {
String hyperlink = data[0];
String hypertext = data[1];
String parentPath = new File(nodeURL).getParent();
String newNodeURL = new File(parentPath, hyperlink).getPath();
children.add(new SearchNode(newNodeURL, hypertext, this));
}
this.children = children;
this.textContents = Utilities.normalizeSearchString(textContents
.toString());
}
}
public String getNodeURL()
{
return nodeURL;
}
public SearchNode getParent()
{
return parent;
}
public int getDepth()
{
return depth;
}
@Override
public String toString()
{
return nodeURL;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((nodeURL == null) ? 0 : nodeURL.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SearchNode other = (SearchNode) obj;
if (nodeURL == null) {
if (other.nodeURL != null)
return false;
} else if (!nodeURL.equals(other.nodeURL))
return false;
return true;
}
public String getHypertext()
{
return hypertext;
}
public String getNodeName()
{
return nodeName;
}
public String getContents()
{
expandNode();
return contents;
}
public String getTextContents()
{
expandNode();
return textContents;
}
public List<SearchNode> getChildren()
{
expandNode();
return children;
}
}
| 4,597 | 0.55906 | 0.556232 | 201 | 21.875622 | 21.172579 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
3
|
83adf345054c29ae7e67d5d06f168213d39f41c9
| 22,247,930,660,098 |
3c7abce07f48985e74c6256264141f1660e31ea2
|
/src/main/java/com/example/todoapp/dto/response/TodoDto.java
|
42857e88d41319a7724da4f725cb4619845f6382
|
[] |
no_license
|
hsyndg98/todo-app
|
https://github.com/hsyndg98/todo-app
|
fff1a2e93a7115d1d54a2ca81125e22a74acca68
|
7b8a621192fe110239333bddd20de29a029709d0
|
refs/heads/master
| 2023-08-23T06:36:47.535000 | 2021-10-18T17:53:31 | 2021-10-18T17:53:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.todoapp.dto.response;
import lombok.*;
import java.util.Date;
import java.util.UUID;
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TodoDto {
private UUID id;
private String title;
private String description;
private String username;
private Date updatedAt;
private Date createdAt;
}
|
UTF-8
|
Java
| 363 |
java
|
TodoDto.java
|
Java
|
[] | null |
[] |
package com.example.todoapp.dto.response;
import lombok.*;
import java.util.Date;
import java.util.UUID;
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TodoDto {
private UUID id;
private String title;
private String description;
private String username;
private Date updatedAt;
private Date createdAt;
}
| 363 | 0.746556 | 0.746556 | 22 | 15.5 | 12.021761 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
3
|
da813c3466f4c0744343f5ebde3b3405962397f6
| 15,126,874,843,855 |
69b127cae0bb30712c2a8169c2cdc95968dbc074
|
/src/main/java/org/leanpoker/cards/Suit.java
|
139330472f07785da651686f9d0d0a93e60f9784
|
[] |
no_license
|
empyty/poker-player-cashino
|
https://github.com/empyty/poker-player-cashino
|
9c811368e1be7947c462d0f828e6e939d643fe13
|
b7e9d3b17817dd8f7574ea0dc70d00c394ee4fe0
|
refs/heads/master
| 2020-03-23T19:29:52.471000 | 2018-07-23T14:57:35 | 2018-07-23T14:57:35 | 141,982,484 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.leanpoker.cards;
public enum Suit {
SPADES(1, "spades", Color.BLACK),
HEARTS(2, "hearts", Color.RED),
DIAMONDS(3, "diamonds", Color.RED),
CLUBS(4, "clubs", Color.BLACK);
private final int value;
private final String name;
private final Color color;
Suit(int value, String name, Color color) {
this.value = value;
this.name = name;
this.color = color;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
@Override
public String toString() {
return String.valueOf(this.name);
}
public enum Color {
BLACK,
RED
}
}
|
UTF-8
|
Java
| 757 |
java
|
Suit.java
|
Java
|
[] | null |
[] |
package org.leanpoker.cards;
public enum Suit {
SPADES(1, "spades", Color.BLACK),
HEARTS(2, "hearts", Color.RED),
DIAMONDS(3, "diamonds", Color.RED),
CLUBS(4, "clubs", Color.BLACK);
private final int value;
private final String name;
private final Color color;
Suit(int value, String name, Color color) {
this.value = value;
this.name = name;
this.color = color;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
@Override
public String toString() {
return String.valueOf(this.name);
}
public enum Color {
BLACK,
RED
}
}
| 757 | 0.566711 | 0.561427 | 40 | 17.9 | 14.095744 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false |
3
|
3d8b7c45c6ccb114d1a642638e0feb6b62bd2734
| 4,870,492,971,127 |
d4e4bb2ee028a104aa678d20d87ebd71958a319e
|
/spring-boot-13-canal/src/main/java/com/example/sys/controller/UserController.java
|
a68451cf15fcffa51c6d083989f9eb2e81e1c042
|
[
"Apache-2.0"
] |
permissive
|
QiPengBian/spring-boot-example
|
https://github.com/QiPengBian/spring-boot-example
|
02c6ed0fe9bb0eda3754fce1ccebfd6350f95439
|
c4a48850408c8424f838a3cbf6040ba80d6e5c1a
|
refs/heads/main
| 2023-07-24T06:36:47.135000 | 2023-07-11T14:47:39 | 2023-07-11T14:47:39 | 267,216,436 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.sys.controller;
import com.example.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
/**
* 用户信息表
*
* @author QiPeng
* @email 276109002@qq.com
* @date 2021-07-07 14:21:17
*/
@RestController("sys/user")
public class UserController {
@Autowired
private UserService userService;
}
|
UTF-8
|
Java
| 426 |
java
|
UserController.java
|
Java
|
[
{
"context": "tation.RestController;\n\n/**\n * 用户信息表\n *\n * @author QiPeng\n * @email 276109002@qq.com\n * @date 2021-07-07 14",
"end": 241,
"score": 0.9973604083061218,
"start": 235,
"tag": "NAME",
"value": "QiPeng"
},
{
"context": "ler;\n\n/**\n * 用户信息表\n *\n * @author QiPeng\n * @email 276109002@qq.com\n * @date 2021-07-07 14:21:17\n */\n@RestController(",
"end": 268,
"score": 0.9996781945228577,
"start": 252,
"tag": "EMAIL",
"value": "276109002@qq.com"
}
] | null |
[] |
package com.example.sys.controller;
import com.example.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
/**
* 用户信息表
*
* @author QiPeng
* @email <EMAIL>
* @date 2021-07-07 14:21:17
*/
@RestController("sys/user")
public class UserController {
@Autowired
private UserService userService;
}
| 417 | 0.757212 | 0.701923 | 20 | 19.799999 | 19.772709 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
3
|
3a96651c8b2c8ecd81ea42e9b8e3ed6fbb34ceb6
| 25,598,005,152,135 |
5e26ae6f1550a4aeaef8b00cc334b31dfa774e5d
|
/PepCodes/BT/avl.java
|
516783c7fdc2cf07d8a69fe3eb9254f90e245b8f
|
[] |
no_license
|
kman1sh/pep-DS-Algo
|
https://github.com/kman1sh/pep-DS-Algo
|
b490f1988d98b98783dfa9c5477d8d29145d48f0
|
00d6b3eb10f247bb5d02d6a8370e86860bdc3c7c
|
refs/heads/master
| 2022-12-01T09:41:42.886000 | 2020-08-15T08:34:57 | 2020-08-15T08:34:57 | 287,708,678 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* avl
*/
public class avl {
static class Node {
int data = 0;
Node left = null;
Node right = null;
int height = -1;
int bf = 0;
Node(int data) {
this.data = data;
}
}
public static void main(String[] args) {
Node node = null;
for (int i = 1; i <= 7; i++) {
int num = (int) (100 * Math.random());
node = addData(node, num);
}
display(node);
}
public static void display(Node node) {
if (node == null)
return;
String ans = "";
ans += (node.left == null) ? "." : node.left.data;
ans += "-> " + node.data + " <-";
ans += (node.right == null) ? "." : node.right.data;
System.out.println(ans);
display(node.left);
display(node.right);
}
public static Node addData(Node node, int data) {
if (node == null)
return new Node(data);
if (node.data > data) {
node.left = addData(node.left, data);
} else {
node.right = addData(node.right, data);
}
// node = updateHeightBalance(node);
return node;
}
public static Node removeData(Node node, int data) {
if (node == null)
return;
if (node.data > data) {
node.left = addData(node.left, data);
} else if(node.data < data) {
node.right = addData(node.right, data);
} else { //data mil gya
if(node.left == null || node.right == null)
return
}
}
}
|
UTF-8
|
Java
| 1,627 |
java
|
avl.java
|
Java
|
[] | null |
[] |
/**
* avl
*/
public class avl {
static class Node {
int data = 0;
Node left = null;
Node right = null;
int height = -1;
int bf = 0;
Node(int data) {
this.data = data;
}
}
public static void main(String[] args) {
Node node = null;
for (int i = 1; i <= 7; i++) {
int num = (int) (100 * Math.random());
node = addData(node, num);
}
display(node);
}
public static void display(Node node) {
if (node == null)
return;
String ans = "";
ans += (node.left == null) ? "." : node.left.data;
ans += "-> " + node.data + " <-";
ans += (node.right == null) ? "." : node.right.data;
System.out.println(ans);
display(node.left);
display(node.right);
}
public static Node addData(Node node, int data) {
if (node == null)
return new Node(data);
if (node.data > data) {
node.left = addData(node.left, data);
} else {
node.right = addData(node.right, data);
}
// node = updateHeightBalance(node);
return node;
}
public static Node removeData(Node node, int data) {
if (node == null)
return;
if (node.data > data) {
node.left = addData(node.left, data);
} else if(node.data < data) {
node.right = addData(node.right, data);
} else { //data mil gya
if(node.left == null || node.right == null)
return
}
}
}
| 1,627 | 0.460356 | 0.455439 | 75 | 20.693333 | 18.356451 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.493333 | false | false |
3
|
a610921be2d32feeb961e135941e7495194fca84
| 9,053,791,096,025 |
76f052777e474308e504bb51f89cda17a82c10d4
|
/src/com/tavant/mobilecoe/bubblegame/renderer/GridViewAdapter.java
|
09b7781460abd61683f0dd5c02bad5341a760b68
|
[] |
no_license
|
nasif/BubbleGame
|
https://github.com/nasif/BubbleGame
|
c7ea200e8dcc41b288c5b11a95c2409cc57ab9d7
|
c03eeca6c6f120a1e17717a4be9009379a7d2524
|
refs/heads/master
| 2020-06-09T05:10:31.302000 | 2014-01-20T06:50:07 | 2014-01-20T06:50:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tavant.mobilecoe.bubblegame.renderer;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.tavant.mobilecoe.bubblegame.R;
import com.tavant.mobilecoe.bubblegame.gameobject.Grid;
public class GridViewAdapter extends BaseAdapter{
Context context;
int layoutResourceId;
ArrayList<Grid> data = new ArrayList<Grid>();
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList<Grid> data) {
super();
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
// public View getGridRow(int position, View convertView, ViewGroup parent) {
// View row = convertView;
// RecordHolder holder = null;
//
// if (row == null) {
// LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// row = inflater.inflate(layoutResourceId, parent, false);
//
// holder = new RecordHolder();
// holder.txtTitle = (TextView) row.findViewById(R.id.grid_text);
// holder.imageItem = (ImageView) row.findViewById(R.id.grid_image);
// row.setTag(holder);
// } else {
// holder = (RecordHolder) row.getTag();
// }
//
// Grid grid = data.get(position);
// holder.txtTitle.setText(grid.getTitle());
// holder.imageItem.setImageBitmap(grid.getImage());
// return row;
//
// }
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
RecordHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.grid_text);
holder.imageItem = (ImageView) row.findViewById(R.id.grid_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
Grid grid = data.get(position);
holder.txtTitle.setText(grid.getTitle());
holder.imageItem.setImageBitmap(grid.getImage());
return row;
}
}
|
UTF-8
|
Java
| 2,748 |
java
|
GridViewAdapter.java
|
Java
|
[] | null |
[] |
package com.tavant.mobilecoe.bubblegame.renderer;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.tavant.mobilecoe.bubblegame.R;
import com.tavant.mobilecoe.bubblegame.gameobject.Grid;
public class GridViewAdapter extends BaseAdapter{
Context context;
int layoutResourceId;
ArrayList<Grid> data = new ArrayList<Grid>();
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList<Grid> data) {
super();
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
// public View getGridRow(int position, View convertView, ViewGroup parent) {
// View row = convertView;
// RecordHolder holder = null;
//
// if (row == null) {
// LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// row = inflater.inflate(layoutResourceId, parent, false);
//
// holder = new RecordHolder();
// holder.txtTitle = (TextView) row.findViewById(R.id.grid_text);
// holder.imageItem = (ImageView) row.findViewById(R.id.grid_image);
// row.setTag(holder);
// } else {
// holder = (RecordHolder) row.getTag();
// }
//
// Grid grid = data.get(position);
// holder.txtTitle.setText(grid.getTitle());
// holder.imageItem.setImageBitmap(grid.getImage());
// return row;
//
// }
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
RecordHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.grid_text);
holder.imageItem = (ImageView) row.findViewById(R.id.grid_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
Grid grid = data.get(position);
holder.txtTitle.setText(grid.getTitle());
holder.imageItem.setImageBitmap(grid.getImage());
return row;
}
}
| 2,748 | 0.695051 | 0.694687 | 101 | 25.20792 | 21.392752 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.910891 | false | false |
3
|
55850d593cd23432a113d46f1454ea0570335fcc
| 30,588,757,085,169 |
eba77a11fd0e41fef7f63c12df1119b8d4518928
|
/app/build/generated/source/apt/debug/com/geekhive/foodey/Food/login/LoginActivity_ViewBinding.java
|
f71657c6dc6bc455e8c130f483059981a98f04fd
|
[] |
no_license
|
dprasad554/FoodeyResurant
|
https://github.com/dprasad554/FoodeyResurant
|
0a64f014c504c945aadf7c1fa8cfc465a6b836de
|
40fa1753567ec15f4d47f71f45b917b18b314fcb
|
refs/heads/master
| 2023-04-03T15:41:55.851000 | 2021-05-03T08:39:01 | 2021-05-03T08:39:01 | 363,862,272 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// Generated code from Butter Knife. Do not modify!
package com.geekhive.foodey.Food.login;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.CallSuper;
import androidx.annotation.UiThread;
import butterknife.Unbinder;
import butterknife.internal.Utils;
import com.geekhive.foodey.R;
import java.lang.IllegalStateException;
import java.lang.Override;
public class LoginActivity_ViewBinding implements Unbinder {
private LoginActivity target;
@UiThread
public LoginActivity_ViewBinding(LoginActivity target) {
this(target, target.getWindow().getDecorView());
}
@UiThread
public LoginActivity_ViewBinding(LoginActivity target, View source) {
this.target = target;
target.vIAlBack = Utils.findRequiredViewAsType(source, R.id.vI_al_back, "field 'vIAlBack'", ImageView.class);
target.vTAlApp = Utils.findRequiredViewAsType(source, R.id.vT_al_app, "field 'vTAlApp'", TextView.class);
target.vTAlInstant = Utils.findRequiredViewAsType(source, R.id.vT_al_instant, "field 'vTAlInstant'", TextView.class);
target.vTAlLogin = Utils.findRequiredViewAsType(source, R.id.vT_al_login, "field 'vTAlLogin'", TextView.class);
target.vEAlMobile = Utils.findRequiredViewAsType(source, R.id.vE_al_Mobile, "field 'vEAlMobile'", EditText.class);
target.vIAlPass = Utils.findRequiredViewAsType(source, R.id.vI_al_pass, "field 'vIAlPass'", ImageView.class);
target.vEAlPass = Utils.findRequiredViewAsType(source, R.id.vE_al_pass, "field 'vEAlPass'", EditText.class);
target.vTAlForgot = Utils.findRequiredViewAsType(source, R.id.vT_al_forgot, "field 'vTAlForgot'", TextView.class);
target.vTAlLogina = Utils.findRequiredViewAsType(source, R.id.vT_al_logina, "field 'vTAlLogina'", TextView.class);
target.vTAlNewUser = Utils.findRequiredViewAsType(source, R.id.vT_al_new_user, "field 'vTAlNewUser'", TextView.class);
target.vTAlSignup = Utils.findRequiredViewAsType(source, R.id.vT_al_signup, "field 'vTAlSignup'", TextView.class);
target.vLAlSignup = Utils.findRequiredViewAsType(source, R.id.vL_al_signup, "field 'vLAlSignup'", LinearLayout.class);
target.vTAlFb = Utils.findRequiredViewAsType(source, R.id.vT_al_fb, "field 'vTAlFb'", TextView.class);
target.vLAlFb = Utils.findRequiredViewAsType(source, R.id.vL_al_fb, "field 'vLAlFb'", LinearLayout.class);
}
@Override
@CallSuper
public void unbind() {
LoginActivity target = this.target;
if (target == null) throw new IllegalStateException("Bindings already cleared.");
this.target = null;
target.vIAlBack = null;
target.vTAlApp = null;
target.vTAlInstant = null;
target.vTAlLogin = null;
target.vEAlMobile = null;
target.vIAlPass = null;
target.vEAlPass = null;
target.vTAlForgot = null;
target.vTAlLogina = null;
target.vTAlNewUser = null;
target.vTAlSignup = null;
target.vLAlSignup = null;
target.vTAlFb = null;
target.vLAlFb = null;
}
}
|
UTF-8
|
Java
| 3,068 |
java
|
LoginActivity_ViewBinding.java
|
Java
|
[] | null |
[] |
// Generated code from Butter Knife. Do not modify!
package com.geekhive.foodey.Food.login;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.CallSuper;
import androidx.annotation.UiThread;
import butterknife.Unbinder;
import butterknife.internal.Utils;
import com.geekhive.foodey.R;
import java.lang.IllegalStateException;
import java.lang.Override;
public class LoginActivity_ViewBinding implements Unbinder {
private LoginActivity target;
@UiThread
public LoginActivity_ViewBinding(LoginActivity target) {
this(target, target.getWindow().getDecorView());
}
@UiThread
public LoginActivity_ViewBinding(LoginActivity target, View source) {
this.target = target;
target.vIAlBack = Utils.findRequiredViewAsType(source, R.id.vI_al_back, "field 'vIAlBack'", ImageView.class);
target.vTAlApp = Utils.findRequiredViewAsType(source, R.id.vT_al_app, "field 'vTAlApp'", TextView.class);
target.vTAlInstant = Utils.findRequiredViewAsType(source, R.id.vT_al_instant, "field 'vTAlInstant'", TextView.class);
target.vTAlLogin = Utils.findRequiredViewAsType(source, R.id.vT_al_login, "field 'vTAlLogin'", TextView.class);
target.vEAlMobile = Utils.findRequiredViewAsType(source, R.id.vE_al_Mobile, "field 'vEAlMobile'", EditText.class);
target.vIAlPass = Utils.findRequiredViewAsType(source, R.id.vI_al_pass, "field 'vIAlPass'", ImageView.class);
target.vEAlPass = Utils.findRequiredViewAsType(source, R.id.vE_al_pass, "field 'vEAlPass'", EditText.class);
target.vTAlForgot = Utils.findRequiredViewAsType(source, R.id.vT_al_forgot, "field 'vTAlForgot'", TextView.class);
target.vTAlLogina = Utils.findRequiredViewAsType(source, R.id.vT_al_logina, "field 'vTAlLogina'", TextView.class);
target.vTAlNewUser = Utils.findRequiredViewAsType(source, R.id.vT_al_new_user, "field 'vTAlNewUser'", TextView.class);
target.vTAlSignup = Utils.findRequiredViewAsType(source, R.id.vT_al_signup, "field 'vTAlSignup'", TextView.class);
target.vLAlSignup = Utils.findRequiredViewAsType(source, R.id.vL_al_signup, "field 'vLAlSignup'", LinearLayout.class);
target.vTAlFb = Utils.findRequiredViewAsType(source, R.id.vT_al_fb, "field 'vTAlFb'", TextView.class);
target.vLAlFb = Utils.findRequiredViewAsType(source, R.id.vL_al_fb, "field 'vLAlFb'", LinearLayout.class);
}
@Override
@CallSuper
public void unbind() {
LoginActivity target = this.target;
if (target == null) throw new IllegalStateException("Bindings already cleared.");
this.target = null;
target.vIAlBack = null;
target.vTAlApp = null;
target.vTAlInstant = null;
target.vTAlLogin = null;
target.vEAlMobile = null;
target.vIAlPass = null;
target.vEAlPass = null;
target.vTAlForgot = null;
target.vTAlLogina = null;
target.vTAlNewUser = null;
target.vTAlSignup = null;
target.vLAlSignup = null;
target.vTAlFb = null;
target.vLAlFb = null;
}
}
| 3,068 | 0.745763 | 0.745763 | 67 | 44.791046 | 39.842052 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.358209 | false | false |
3
|
bdc81c16a6d0e08ef874b34835f5863408188d50
| 7,155,415,577,024 |
ce60e237f9491d4bb7143ce6532316b2f754cbad
|
/src/main/java/reco/configuration/JpaConfiguration.java
|
352d86172851cf2c958c7db162737f73ba4d0919
|
[] |
no_license
|
Debadarsini/recomendation
|
https://github.com/Debadarsini/recomendation
|
2d1a45455054e884e502c2e0f8d5c704e0af15c8
|
20b3601908178ba87a1daa1c7a66d65b7ddbb6cc
|
refs/heads/master
| 2021-01-02T08:13:29.185000 | 2017-08-02T04:22:45 | 2017-08-02T04:22:45 | 98,965,752 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package reco.configuration;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariDataSource;
@Configuration
@EnableJpaRepositories(basePackages="reco.repositories",
entityManagerFactoryRef="entityManagerFactory",transactionManagerRef="transactionManager")
@EnableTransactionManagement
public class JpaConfiguration {
@Autowired
private Environment environment;
@Value("${datasource.reco.maxPoolSize:10}")
private int maxPoolSize;
@Bean
@Primary
@ConfigurationProperties(prefix="datasource.reco")
public DataSourceProperties dataSourceProperties(){
return new DataSourceProperties();
}
@Bean
public DataSource dataSource(){
DataSourceProperties dsprop = dataSourceProperties();
HikariDataSource dataSource = (HikariDataSource)DataSourceBuilder
.create(dsprop.getClassLoader())
.driverClassName(dsprop.getDriverClassName())
.url(dsprop.getUrl())
.username(dsprop.getDataUsername())
.password(dsprop.getDataPassword())
.type(HikariDataSource.class)
.build();
dataSource.setMaximumPoolSize(maxPoolSize);
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("reco.model");
factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
factoryBean.setJpaProperties(jpaProperties());
return factoryBean;
}
private Properties jpaProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("datasource.reco.hibernate.dialect"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("datasource.reco.hibernate.hbm2ddl.method"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("datasource.reco.hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("datasource.reco.hibernate.format_sql"));
if(null != environment.getRequiredProperty("datasource.reco.defaultSchema") ||
!"".equals(environment.getRequiredProperty("datasource.reco.defaultSchema"))){
properties.put("hibernate.default_schema", environment.getRequiredProperty("datasource.reco.defaultSchema"));
}
return properties;
}
public JpaVendorAdapter jpaVendorAdapter(){
HibernateJpaVendorAdapter provider = new HibernateJpaVendorAdapter();
return provider;
}
@Bean
@Autowired
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
}
|
UTF-8
|
Java
| 4,289 |
java
|
JpaConfiguration.java
|
Java
|
[
{
"context": "Username())\n .password(dsprop.getDataPassword())\n ",
"end": 2254,
"score": 0.6323537826538086,
"start": 2251,
"tag": "PASSWORD",
"value": "dsp"
}
] | null |
[] |
package reco.configuration;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariDataSource;
@Configuration
@EnableJpaRepositories(basePackages="reco.repositories",
entityManagerFactoryRef="entityManagerFactory",transactionManagerRef="transactionManager")
@EnableTransactionManagement
public class JpaConfiguration {
@Autowired
private Environment environment;
@Value("${datasource.reco.maxPoolSize:10}")
private int maxPoolSize;
@Bean
@Primary
@ConfigurationProperties(prefix="datasource.reco")
public DataSourceProperties dataSourceProperties(){
return new DataSourceProperties();
}
@Bean
public DataSource dataSource(){
DataSourceProperties dsprop = dataSourceProperties();
HikariDataSource dataSource = (HikariDataSource)DataSourceBuilder
.create(dsprop.getClassLoader())
.driverClassName(dsprop.getDriverClassName())
.url(dsprop.getUrl())
.username(dsprop.getDataUsername())
.password(dsprop.getDataPassword())
.type(HikariDataSource.class)
.build();
dataSource.setMaximumPoolSize(maxPoolSize);
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("reco.model");
factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
factoryBean.setJpaProperties(jpaProperties());
return factoryBean;
}
private Properties jpaProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("datasource.reco.hibernate.dialect"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("datasource.reco.hibernate.hbm2ddl.method"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("datasource.reco.hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("datasource.reco.hibernate.format_sql"));
if(null != environment.getRequiredProperty("datasource.reco.defaultSchema") ||
!"".equals(environment.getRequiredProperty("datasource.reco.defaultSchema"))){
properties.put("hibernate.default_schema", environment.getRequiredProperty("datasource.reco.defaultSchema"));
}
return properties;
}
public JpaVendorAdapter jpaVendorAdapter(){
HibernateJpaVendorAdapter provider = new HibernateJpaVendorAdapter();
return provider;
}
@Bean
@Autowired
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(emf);
return txManager;
}
}
| 4,289 | 0.733504 | 0.732572 | 103 | 40.640778 | 32.657341 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533981 | false | false |
3
|
b8165bdf20666b3b873756b464e1ff75dce4becb
| 36,292,473,698,590 |
7999d910736149ee66788c9efe6dc6c801ca5d2d
|
/app/src/main/java/com/example/hsc/irunning/main/bean/UserInfo.java
|
faa83df6891d39bd73c0dc5148f32ac221959301
|
[] |
no_license
|
githushiche/irunning_pc
|
https://github.com/githushiche/irunning_pc
|
f6f562fc9a025ba13cb00b0d88d15d97d50fd86d
|
433342698ad31b238eef6f404acfaea6e1fa349d
|
refs/heads/master
| 2020-07-10T10:41:37.555000 | 2019-08-25T04:16:47 | 2019-08-25T04:16:47 | 204,243,964 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.hsc.irunning.main.bean;
import org.litepal.crud.LitePalSupport;
import java.io.Serializable;
/**
* 用户基本信息
*
* @author Diviner
*/
public class UserInfo extends LitePalSupport implements Serializable {
private int uId;
private int uSex;// 性别 0男1女
private int uAge;// 年龄
private String uCity;// 城市
private String uEmail;// 邮箱用于认证
private String uPhone;// 联系电话
private String uAddress;// 详细地址
private String uIntroduce;// 个人简介
private int uHeight;// 身高
private int uWeight;// 体重
private float uFat;// 体脂
private double uLongitude;// 记录用户经度
private double uLatitude;// 记录用户纬度
public UserInfo() {
}
public UserInfo(int uId, int uSex, int uAge, String uCity, String uEmail, String uPhone, String uAddress,
String uIntroduce, int uHeight, int uWeight, float uFat, double uLongitude, double uLatitude) {
super();
this.uId = uId;
this.uSex = uSex;
this.uAge = uAge;
this.uCity = uCity;
this.uEmail = uEmail;
this.uPhone = uPhone;
this.uAddress = uAddress;
this.uIntroduce = uIntroduce;
this.uHeight = uHeight;
this.uWeight = uWeight;
this.uFat = uFat;
this.uLongitude = uLongitude;
this.uLatitude = uLatitude;
}
public int getuId() {
return uId;
}
public void setuId(int uId) {
this.uId = uId;
}
public int getuSex() {
return uSex;
}
public void setuSex(int uSex) {
this.uSex = uSex;
}
public int getuAge() {
return uAge;
}
public void setuAge(int uAge) {
this.uAge = uAge;
}
public String getuCity() {
return uCity;
}
public void setuCity(String uCity) {
this.uCity = uCity;
}
public String getuEmail() {
return uEmail;
}
public void setuEmail(String uEmail) {
this.uEmail = uEmail;
}
public String getuPhone() {
return uPhone;
}
public void setuPhone(String uPhone) {
this.uPhone = uPhone;
}
public String getuAddress() {
return uAddress;
}
public void setuAddress(String uAddress) {
this.uAddress = uAddress;
}
public String getuIntroduce() {
return uIntroduce;
}
public void setuIntroduce(String uIntroduce) {
this.uIntroduce = uIntroduce;
}
public int getuHeight() {
return uHeight;
}
public void setuHeight(int uHeight) {
this.uHeight = uHeight;
}
public int getuWeight() {
return uWeight;
}
public void setuWeight(int uWeight) {
this.uWeight = uWeight;
}
public float getuFat() {
return uFat;
}
public void setuFat(float uFat) {
this.uFat = uFat;
}
public double getuLongitude() {
return uLongitude;
}
public void setuLongitude(double uLongitude) {
this.uLongitude = uLongitude;
}
public double getuLatitude() {
return uLatitude;
}
public void setuLatitude(double uLatitude) {
this.uLatitude = uLatitude;
}
@Override
public String toString() {
return "UserInfo{" +
"uId=" + uId +
", uSex=" + uSex +
", uAge=" + uAge +
", uCity='" + uCity + '\'' +
", uEmail='" + uEmail + '\'' +
", uPhone='" + uPhone + '\'' +
", uAddress='" + uAddress + '\'' +
", uIntroduce='" + uIntroduce + '\'' +
", uHeight=" + uHeight +
", uWeight=" + uWeight +
", uFat=" + uFat +
", uLongitude=" + uLongitude +
", uLatitude=" + uLatitude +
'}';
}
}
|
UTF-8
|
Java
| 3,934 |
java
|
UserInfo.java
|
Java
|
[
{
"context": "java.io.Serializable;\n\n/**\n * 用户基本信息\n *\n * @author Diviner\n */\npublic class UserInfo extends LitePalSupport ",
"end": 151,
"score": 0.944007396697998,
"start": 144,
"tag": "USERNAME",
"value": "Diviner"
}
] | null |
[] |
package com.example.hsc.irunning.main.bean;
import org.litepal.crud.LitePalSupport;
import java.io.Serializable;
/**
* 用户基本信息
*
* @author Diviner
*/
public class UserInfo extends LitePalSupport implements Serializable {
private int uId;
private int uSex;// 性别 0男1女
private int uAge;// 年龄
private String uCity;// 城市
private String uEmail;// 邮箱用于认证
private String uPhone;// 联系电话
private String uAddress;// 详细地址
private String uIntroduce;// 个人简介
private int uHeight;// 身高
private int uWeight;// 体重
private float uFat;// 体脂
private double uLongitude;// 记录用户经度
private double uLatitude;// 记录用户纬度
public UserInfo() {
}
public UserInfo(int uId, int uSex, int uAge, String uCity, String uEmail, String uPhone, String uAddress,
String uIntroduce, int uHeight, int uWeight, float uFat, double uLongitude, double uLatitude) {
super();
this.uId = uId;
this.uSex = uSex;
this.uAge = uAge;
this.uCity = uCity;
this.uEmail = uEmail;
this.uPhone = uPhone;
this.uAddress = uAddress;
this.uIntroduce = uIntroduce;
this.uHeight = uHeight;
this.uWeight = uWeight;
this.uFat = uFat;
this.uLongitude = uLongitude;
this.uLatitude = uLatitude;
}
public int getuId() {
return uId;
}
public void setuId(int uId) {
this.uId = uId;
}
public int getuSex() {
return uSex;
}
public void setuSex(int uSex) {
this.uSex = uSex;
}
public int getuAge() {
return uAge;
}
public void setuAge(int uAge) {
this.uAge = uAge;
}
public String getuCity() {
return uCity;
}
public void setuCity(String uCity) {
this.uCity = uCity;
}
public String getuEmail() {
return uEmail;
}
public void setuEmail(String uEmail) {
this.uEmail = uEmail;
}
public String getuPhone() {
return uPhone;
}
public void setuPhone(String uPhone) {
this.uPhone = uPhone;
}
public String getuAddress() {
return uAddress;
}
public void setuAddress(String uAddress) {
this.uAddress = uAddress;
}
public String getuIntroduce() {
return uIntroduce;
}
public void setuIntroduce(String uIntroduce) {
this.uIntroduce = uIntroduce;
}
public int getuHeight() {
return uHeight;
}
public void setuHeight(int uHeight) {
this.uHeight = uHeight;
}
public int getuWeight() {
return uWeight;
}
public void setuWeight(int uWeight) {
this.uWeight = uWeight;
}
public float getuFat() {
return uFat;
}
public void setuFat(float uFat) {
this.uFat = uFat;
}
public double getuLongitude() {
return uLongitude;
}
public void setuLongitude(double uLongitude) {
this.uLongitude = uLongitude;
}
public double getuLatitude() {
return uLatitude;
}
public void setuLatitude(double uLatitude) {
this.uLatitude = uLatitude;
}
@Override
public String toString() {
return "UserInfo{" +
"uId=" + uId +
", uSex=" + uSex +
", uAge=" + uAge +
", uCity='" + uCity + '\'' +
", uEmail='" + uEmail + '\'' +
", uPhone='" + uPhone + '\'' +
", uAddress='" + uAddress + '\'' +
", uIntroduce='" + uIntroduce + '\'' +
", uHeight=" + uHeight +
", uWeight=" + uWeight +
", uFat=" + uFat +
", uLongitude=" + uLongitude +
", uLatitude=" + uLatitude +
'}';
}
}
| 3,934 | 0.54747 | 0.546948 | 170 | 21.55294 | 18.911251 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.476471 | false | false |
3
|
fdfc2b657fbf430f0c702b12e970e8e6d0eb2d7d
| 36,292,473,699,862 |
1e681b81e7b8c030be7e9fee9b6cfa0484c6edb7
|
/app/src/main/java/com/example/test1/GameActivity.java
|
877964b269ccd4f30eebf9d7eca09789597fe179
|
[] |
no_license
|
MaxyLee/musical-waffle
|
https://github.com/MaxyLee/musical-waffle
|
4f04bb811b885465ecee9e808dcb8e9d0433b424
|
e0f8b2a81f6d769185093d18eca28861d907b6ed
|
refs/heads/master
| 2020-06-18T05:44:01.496000 | 2019-07-10T10:42:12 | 2019-07-10T10:42:12 | 196,184,260 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.test1;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class GameActivity extends AppCompatActivity {
View mView;
//draw notes
private Paint notePaint;
//draw checkCircle
private Paint nPaint;
private Paint lPaint;
LinearLayout gameLayout;
Music music;
//count notes that have appeared
public int cnt;
//notes fall
public Thread mThread;
public Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
initData();
initView();
gameStart();
}
@SuppressLint("HandlerLeak")
public void initData(){
//init count
cnt = 0;
//init Paints
notePaint = new Paint();
notePaint.setColor(0xff666666);
notePaint.setAntiAlias(true);
nPaint = new Paint();
nPaint.setARGB(100,246,198,123);
nPaint.setAntiAlias(true);
nPaint.setStyle(Paint.Style.STROKE);
nPaint.setStrokeWidth(5);
lPaint = new Paint();
lPaint.setARGB(100,246,198,123);
lPaint.setAntiAlias(true);
lPaint.setStrokeWidth(5);
//init music
music = new Music();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String musicName = bundle.getString("musicName","");
try{
InputStream is = GameActivity.this.getClass().getClassLoader().getResourceAsStream("assets/"+"sheet.json");
BufferedReader bufr = new BufferedReader((new InputStreamReader(is)));
String line;
StringBuilder builder = new StringBuilder();
while((line = bufr.readLine())!=null){
builder.append(line);
}
is.close();
bufr.close();
try{
JSONObject json = new JSONObject(builder.toString());
JSONArray notes = json.getJSONArray(musicName);
music.appearTime = new int[notes.length()];
music.state = new int[notes.length()];
for(int i=0;i<notes.length();i++)
music.appearTime[i] = (int) notes.get(i);
} catch (JSONException e){
e.printStackTrace();
}
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler = new Handler(){
public void handleMessage(android.os.Message msg){
mView.invalidate();
};
};
}
public void initView(){
gameLayout = findViewById(R.id.gameLayout);
mView = new View(this){
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(mView.getWidth()/2,mView.getHeight()-100,60,nPaint);
canvas.drawCircle(mView.getWidth()/2,mView.getHeight()-100,50,lPaint);
for(int i=0;i<music.appearTime.length;i++){
if(music.state[i]==1){
canvas.drawOval(mView.getWidth()/2-50,music.position[i],mView.getWidth()/2+50,music.position[i]+100,notePaint);
}
}
}
};
mView.setBackgroundColor(0xff000000);
gameLayout.addView(mView);
gameLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(cnt<music.state.length&&music.state[cnt]==1){
if(music.position[cnt]>mView.getHeight()-210&&music.position[cnt]<mView.getHeight()-40){
music.state[cnt] = 2;
cnt++;
}
}
}
});
}
public void gameStart(){
if(mThread==null){
mThread = new Thread(){
@Override
public void run() {
super.run();
long startTime = System.currentTimeMillis();
long time;
while(true){
try{
sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
}
time = System.currentTimeMillis();
for(int i=cnt;i<music.appearTime.length;i++){
if(music.state[i]!=2&&(time-startTime)>=music.appearTime[i]&&(time-startTime)<(music.appearTime[i]+mView.getHeight()/music.velocity)*4){
music.state[i] = 1;
music.position[i] = (time-startTime-music.appearTime[i])*music.velocity/4;
}
else if(music.state[i]==2||(time-startTime)>(music.appearTime[i]+mView.getHeight()/music.velocity)*4){
music.state[i] = 2;
if(cnt<i+1)
cnt=i+1;
}
}
handler.sendEmptyMessage(0);
}
}
};
mThread.start();
}
}
}
|
UTF-8
|
Java
| 6,052 |
java
|
GameActivity.java
|
Java
|
[] | null |
[] |
package com.example.test1;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class GameActivity extends AppCompatActivity {
View mView;
//draw notes
private Paint notePaint;
//draw checkCircle
private Paint nPaint;
private Paint lPaint;
LinearLayout gameLayout;
Music music;
//count notes that have appeared
public int cnt;
//notes fall
public Thread mThread;
public Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
initData();
initView();
gameStart();
}
@SuppressLint("HandlerLeak")
public void initData(){
//init count
cnt = 0;
//init Paints
notePaint = new Paint();
notePaint.setColor(0xff666666);
notePaint.setAntiAlias(true);
nPaint = new Paint();
nPaint.setARGB(100,246,198,123);
nPaint.setAntiAlias(true);
nPaint.setStyle(Paint.Style.STROKE);
nPaint.setStrokeWidth(5);
lPaint = new Paint();
lPaint.setARGB(100,246,198,123);
lPaint.setAntiAlias(true);
lPaint.setStrokeWidth(5);
//init music
music = new Music();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String musicName = bundle.getString("musicName","");
try{
InputStream is = GameActivity.this.getClass().getClassLoader().getResourceAsStream("assets/"+"sheet.json");
BufferedReader bufr = new BufferedReader((new InputStreamReader(is)));
String line;
StringBuilder builder = new StringBuilder();
while((line = bufr.readLine())!=null){
builder.append(line);
}
is.close();
bufr.close();
try{
JSONObject json = new JSONObject(builder.toString());
JSONArray notes = json.getJSONArray(musicName);
music.appearTime = new int[notes.length()];
music.state = new int[notes.length()];
for(int i=0;i<notes.length();i++)
music.appearTime[i] = (int) notes.get(i);
} catch (JSONException e){
e.printStackTrace();
}
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler = new Handler(){
public void handleMessage(android.os.Message msg){
mView.invalidate();
};
};
}
public void initView(){
gameLayout = findViewById(R.id.gameLayout);
mView = new View(this){
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(mView.getWidth()/2,mView.getHeight()-100,60,nPaint);
canvas.drawCircle(mView.getWidth()/2,mView.getHeight()-100,50,lPaint);
for(int i=0;i<music.appearTime.length;i++){
if(music.state[i]==1){
canvas.drawOval(mView.getWidth()/2-50,music.position[i],mView.getWidth()/2+50,music.position[i]+100,notePaint);
}
}
}
};
mView.setBackgroundColor(0xff000000);
gameLayout.addView(mView);
gameLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(cnt<music.state.length&&music.state[cnt]==1){
if(music.position[cnt]>mView.getHeight()-210&&music.position[cnt]<mView.getHeight()-40){
music.state[cnt] = 2;
cnt++;
}
}
}
});
}
public void gameStart(){
if(mThread==null){
mThread = new Thread(){
@Override
public void run() {
super.run();
long startTime = System.currentTimeMillis();
long time;
while(true){
try{
sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
}
time = System.currentTimeMillis();
for(int i=cnt;i<music.appearTime.length;i++){
if(music.state[i]!=2&&(time-startTime)>=music.appearTime[i]&&(time-startTime)<(music.appearTime[i]+mView.getHeight()/music.velocity)*4){
music.state[i] = 1;
music.position[i] = (time-startTime-music.appearTime[i])*music.velocity/4;
}
else if(music.state[i]==2||(time-startTime)>(music.appearTime[i]+mView.getHeight()/music.velocity)*4){
music.state[i] = 2;
if(cnt<i+1)
cnt=i+1;
}
}
handler.sendEmptyMessage(0);
}
}
};
mThread.start();
}
}
}
| 6,052 | 0.534534 | 0.520489 | 173 | 33.982658 | 25.471161 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.687861 | false | false |
3
|
f5f2a7becce78d2a30b4140c4a59a106d0df0d6e
| 28,406,913,738,741 |
30efc5b559a848049295c07d84502c464d3adcef
|
/app/synappease movil/DataService/src/com/System/WebServices/wsManager.java
|
f6ab88821b5d5c180e10fa27575cbd0897e57880
|
[] |
no_license
|
WizelineHackathon2018/synapps-ease
|
https://github.com/WizelineHackathon2018/synapps-ease
|
651d6e19a2ff52dbf664daeba1a2e7ffe4406023
|
c979e754aca490d4e42ed0e4c9845f57f5dafddc
|
refs/heads/master
| 2020-03-19T05:19:21.447000 | 2018-06-03T16:31:10 | 2018-06-03T16:31:10 | 135,920,538 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.System.WebServices;
import java.util.*;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.System.Utils.Logg;
public class wsManager
{
//Variables de la clase
public String Error;
public String wsNamesPace;//Nombre del namespace pe: http://tempuri.org/
public String wsUrl; //Url del asmx pe: http://intersad.no-ip.org/service/service.asmx
public String WebMethod; //Nombre del web method pe: DarDatosEncabezado
private Hashtable listaParametros = new Hashtable();//Lista de parametros
//Variables de la clase
//Constructor de la clase
public wsManager()
{
}
//hace un clear a la lista de prametros
public void ClearParametros()
{
listaParametros.clear();
}
//agrega un parametro al web services
public void AgregarParametro(String NombreParametro, String Valor)
{
listaParametros.put(NombreParametro, Valor);
}
//Manda a llamar un WebServices con parametros y demas y regresa verdadero si se ejecuto bien y falso su fallo algo
public boolean EjecutarWS()
{
Error = "";
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject soapObject = new SoapObject(wsNamesPace, WebMethod);
//Aca se agregan los parametros al Web Services
Enumeration enumeracion = listaParametros.keys();
while(enumeracion.hasMoreElements())
{
String key = (String)(enumeracion.nextElement());
String value = (String)listaParametros.get(key);
soapObject.addProperty(key, value);
}
//Aca se agregan los parametros al Web Services
soapEnvelope.setOutputSoapObject(soapObject);
soapEnvelope.bodyOut = soapObject;
soapEnvelope.dotNet = true;
soapEnvelope.encodingStyle = SoapSerializationEnvelope.XSD;
HttpTransportSE transport = new HttpTransportSE(wsUrl);
try
{
//Aca se llama al WebService
transport.debug = true;
transport.call(wsNamesPace + WebMethod, soapEnvelope);
this.Error = "";
Logg.error("WS " + WebMethod);
}
catch (Exception e)
{
this.Error = WebMethod + " - " + e.getMessage() + " - " + Arrays.toString(e.getStackTrace());
Logg.error("ErrorWS " + this.Error);
Logg.error("transport.requestDump " + transport.requestDump);
Logg.error("transport.responseDump " + transport.responseDump);
soapEnvelope = null;
transport = null;
return false;
}
soapEnvelope = null;
transport = null;
return true;
}
//Aca se ejecuta un Web Services y regresa una coleccion de respuesta
public SoapObject ConsultarWS()
{
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject soapObject = new SoapObject(wsNamesPace, WebMethod);
//Aca se agregan los parametros al Web Services
Enumeration enumeracion = listaParametros.keys();
while(enumeracion.hasMoreElements())
{
String key = (String)(enumeracion.nextElement());
String value = (String)listaParametros.get(key);
soapObject.addProperty(key, value);
}
//Aca se agregan los parametros al Web Services
soapEnvelope.setOutputSoapObject(soapObject);
soapEnvelope.bodyOut = soapObject;
soapEnvelope.dotNet = true;
soapEnvelope.encodingStyle = SoapSerializationEnvelope.XSD;
SoapObject responseObject;
HttpTransportSE transport = new HttpTransportSE(wsUrl);
try
{
//Aca se llama al WebService
transport.debug = true;
transport.call(wsNamesPace + WebMethod, soapEnvelope);
responseObject = (SoapObject)soapEnvelope.getResponse();
int size = responseObject.getPropertyCount();
Logg.error("WS " + WebMethod);
this.Error = "";
}
catch (Exception e)
{
this.Error = WebMethod + " - " + e.getMessage() + " - " + Arrays.toString(e.getStackTrace());
Logg.error("ErrorWS " + this.Error);
Logg.error("transport.requestDump " + transport.requestDump);
Logg.error("transport.responseDump " + transport.responseDump);
responseObject = null;
}
soapEnvelope = null;
transport = null;
return responseObject;
}
public void Dispose()
{
listaParametros = null;
}
}
|
UTF-8
|
Java
| 4,843 |
java
|
wsManager.java
|
Java
|
[] | null |
[] |
package com.System.WebServices;
import java.util.*;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.System.Utils.Logg;
public class wsManager
{
//Variables de la clase
public String Error;
public String wsNamesPace;//Nombre del namespace pe: http://tempuri.org/
public String wsUrl; //Url del asmx pe: http://intersad.no-ip.org/service/service.asmx
public String WebMethod; //Nombre del web method pe: DarDatosEncabezado
private Hashtable listaParametros = new Hashtable();//Lista de parametros
//Variables de la clase
//Constructor de la clase
public wsManager()
{
}
//hace un clear a la lista de prametros
public void ClearParametros()
{
listaParametros.clear();
}
//agrega un parametro al web services
public void AgregarParametro(String NombreParametro, String Valor)
{
listaParametros.put(NombreParametro, Valor);
}
//Manda a llamar un WebServices con parametros y demas y regresa verdadero si se ejecuto bien y falso su fallo algo
public boolean EjecutarWS()
{
Error = "";
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject soapObject = new SoapObject(wsNamesPace, WebMethod);
//Aca se agregan los parametros al Web Services
Enumeration enumeracion = listaParametros.keys();
while(enumeracion.hasMoreElements())
{
String key = (String)(enumeracion.nextElement());
String value = (String)listaParametros.get(key);
soapObject.addProperty(key, value);
}
//Aca se agregan los parametros al Web Services
soapEnvelope.setOutputSoapObject(soapObject);
soapEnvelope.bodyOut = soapObject;
soapEnvelope.dotNet = true;
soapEnvelope.encodingStyle = SoapSerializationEnvelope.XSD;
HttpTransportSE transport = new HttpTransportSE(wsUrl);
try
{
//Aca se llama al WebService
transport.debug = true;
transport.call(wsNamesPace + WebMethod, soapEnvelope);
this.Error = "";
Logg.error("WS " + WebMethod);
}
catch (Exception e)
{
this.Error = WebMethod + " - " + e.getMessage() + " - " + Arrays.toString(e.getStackTrace());
Logg.error("ErrorWS " + this.Error);
Logg.error("transport.requestDump " + transport.requestDump);
Logg.error("transport.responseDump " + transport.responseDump);
soapEnvelope = null;
transport = null;
return false;
}
soapEnvelope = null;
transport = null;
return true;
}
//Aca se ejecuta un Web Services y regresa una coleccion de respuesta
public SoapObject ConsultarWS()
{
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
SoapObject soapObject = new SoapObject(wsNamesPace, WebMethod);
//Aca se agregan los parametros al Web Services
Enumeration enumeracion = listaParametros.keys();
while(enumeracion.hasMoreElements())
{
String key = (String)(enumeracion.nextElement());
String value = (String)listaParametros.get(key);
soapObject.addProperty(key, value);
}
//Aca se agregan los parametros al Web Services
soapEnvelope.setOutputSoapObject(soapObject);
soapEnvelope.bodyOut = soapObject;
soapEnvelope.dotNet = true;
soapEnvelope.encodingStyle = SoapSerializationEnvelope.XSD;
SoapObject responseObject;
HttpTransportSE transport = new HttpTransportSE(wsUrl);
try
{
//Aca se llama al WebService
transport.debug = true;
transport.call(wsNamesPace + WebMethod, soapEnvelope);
responseObject = (SoapObject)soapEnvelope.getResponse();
int size = responseObject.getPropertyCount();
Logg.error("WS " + WebMethod);
this.Error = "";
}
catch (Exception e)
{
this.Error = WebMethod + " - " + e.getMessage() + " - " + Arrays.toString(e.getStackTrace());
Logg.error("ErrorWS " + this.Error);
Logg.error("transport.requestDump " + transport.requestDump);
Logg.error("transport.responseDump " + transport.responseDump);
responseObject = null;
}
soapEnvelope = null;
transport = null;
return responseObject;
}
public void Dispose()
{
listaParametros = null;
}
}
| 4,843 | 0.630394 | 0.628743 | 136 | 34.60294 | 27.459671 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558824 | false | false |
3
|
b71d62975c3a9ced8ca04d5a71afce0d40685c27
| 2,362,232,037,065 |
a4c8a295165ccaee0a80fbb502dd7858b72593e1
|
/src/main/java/fun/hellofun/command/topic/VideoTopic.java
|
319519feb70f0da517207de4d15eed3507b1bff4
|
[
"MIT"
] |
permissive
|
he110fun/capi
|
https://github.com/he110fun/capi
|
8f6ffa6824d66bb9915656b1850df99954eeb26c
|
66acbd2a4c46097d862e75c1f27e0709314865fb
|
refs/heads/master
| 2021-03-26T05:12:04.845000 | 2020-03-24T01:23:10 | 2020-03-24T01:23:10 | 247,674,928 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fun.hellofun.command.topic;
/**
* 该类由 <b>张东冬</b> 于 2020年3月18日 星期三 18时42分17秒 创建;<br>
* 作用是:<b>视频主题</b>;<br>
*
* @author zdd
*/
public enum VideoTopic implements Topic {
/**
* 音乐视频
*/
MUSIC("music"),
/**
* 抖音上的视频
*/
TIKTOK("tiktok");
private String mark;
VideoTopic(String mark) {
this.mark = mark;
}
@Override
public String getMark() {
return mark;
}
}
|
UTF-8
|
Java
| 521 |
java
|
VideoTopic.java
|
Java
|
[
{
"context": "ackage fun.hellofun.command.topic;\n\n/**\n * 该类由 <b>张东冬</b> 于 2020年3月18日 星期三 18时42分17秒 创建;<br>\n * 作用是:<b>",
"end": 54,
"score": 0.9953418970108032,
"start": 51,
"tag": "NAME",
"value": "张东冬"
},
{
"context": "分17秒 创建;<br>\n * 作用是:<b>视频主题</b>;<br>\n *\n * @author zdd\n */\npublic enum VideoTopic implements Topic {\n ",
"end": 135,
"score": 0.9996753334999084,
"start": 132,
"tag": "USERNAME",
"value": "zdd"
}
] | null |
[] |
package fun.hellofun.command.topic;
/**
* 该类由 <b>张东冬</b> 于 2020年3月18日 星期三 18时42分17秒 创建;<br>
* 作用是:<b>视频主题</b>;<br>
*
* @author zdd
*/
public enum VideoTopic implements Topic {
/**
* 音乐视频
*/
MUSIC("music"),
/**
* 抖音上的视频
*/
TIKTOK("tiktok");
private String mark;
VideoTopic(String mark) {
this.mark = mark;
}
@Override
public String getMark() {
return mark;
}
}
| 521 | 0.534831 | 0.505618 | 29 | 14.344828 | 13.365617 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.206897 | false | false |
3
|
e116ad0d7383400212fe18665393cfd47a8c1a58
| 23,132,693,893,000 |
c75edf456802c939a58d1c477c48dcd50a9c63f0
|
/src/test/java/Chunghee/Level2/RightBracketTest.java
|
59c206ef73c555d2eccf1840929fa385f562f483
|
[] |
no_license
|
AlgorithmWarriors/5dae700
|
https://github.com/AlgorithmWarriors/5dae700
|
319eacb6a994f5d780878254049d4de4ac8ebad0
|
88db6c566a92e871620dd99433d78d6d0af301cb
|
refs/heads/master
| 2022-12-27T13:04:38.715000 | 2020-08-30T20:50:21 | 2020-08-30T20:50:21 | 271,702,105 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Chunghee.Level2;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class RightBracketTest {
@Test
public void 올바른괄호테스트(){
RightBracket rightBracket =new RightBracket();
String[] strings = {"()()","(())()",")()(","(()("};
Boolean[] result ={true,true,false,false};
for(int i=0;i<4;i++) {
assertThat(rightBracket.solution(strings[i]), is(result[i]));
}
}
}
|
UTF-8
|
Java
| 496 |
java
|
RightBracketTest.java
|
Java
|
[] | null |
[] |
package Chunghee.Level2;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class RightBracketTest {
@Test
public void 올바른괄호테스트(){
RightBracket rightBracket =new RightBracket();
String[] strings = {"()()","(())()",")()(","(()("};
Boolean[] result ={true,true,false,false};
for(int i=0;i<4;i++) {
assertThat(rightBracket.solution(strings[i]), is(result[i]));
}
}
}
| 496 | 0.595833 | 0.589583 | 15 | 31 | 20.301067 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.133333 | false | false |
3
|
d070c4889427d03d6b00f3450040cf7c9a290b53
| 10,874,857,207,732 |
3fe781afae62e16044496f6ba92604bb8b116317
|
/src/main/java/com/sda/mark/webstore_backend/model/Product.java
|
ba40529121977767573ca337db7b17fc0c646d45
|
[] |
no_license
|
AcatalepticM/webstore-backend
|
https://github.com/AcatalepticM/webstore-backend
|
10f63a651136aefe906e37691e0145bef9ef3651
|
3b4aed7896314136d052c3c60f952c016d8ab9fb
|
refs/heads/master
| 2020-09-27T17:28:55.384000 | 2019-12-20T22:55:56 | 2019-12-20T22:55:56 | 226,570,000 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sda.mark.webstore_backend.model;
import com.sda.mark.webstore_backend.enums.ProductTypeEnums;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
@Entity
@Data
public class Product {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column (name = "ProductID", nullable = false)
private Long id;
@NotNull (message = "Product name required")
@Basic (optional = false)
@Column (name = "Name")
private String name;
@Column (name = "Price", nullable = false)
private BigDecimal price;
@Column (name = "Description")
private String description;
@Column (name = "ThumbnailURL")
private String thumbnailUrl;
@Column (name="CategoryID")
private Long categoryId; //get catId
@Column (name="Type", nullable = false)
private ProductTypeEnums type;
@Column (name="CreatorID")
private Long creatorId; //reference
public Product () {
}
public Product (String name, BigDecimal price, ProductTypeEnums productType, String thumbnailUrl) {
this.name = name;
this.price = price;
this.type = productType;
this.thumbnailUrl = thumbnailUrl;
}
}
|
UTF-8
|
Java
| 1,247 |
java
|
Product.java
|
Java
|
[] | null |
[] |
package com.sda.mark.webstore_backend.model;
import com.sda.mark.webstore_backend.enums.ProductTypeEnums;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
@Entity
@Data
public class Product {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column (name = "ProductID", nullable = false)
private Long id;
@NotNull (message = "Product name required")
@Basic (optional = false)
@Column (name = "Name")
private String name;
@Column (name = "Price", nullable = false)
private BigDecimal price;
@Column (name = "Description")
private String description;
@Column (name = "ThumbnailURL")
private String thumbnailUrl;
@Column (name="CategoryID")
private Long categoryId; //get catId
@Column (name="Type", nullable = false)
private ProductTypeEnums type;
@Column (name="CreatorID")
private Long creatorId; //reference
public Product () {
}
public Product (String name, BigDecimal price, ProductTypeEnums productType, String thumbnailUrl) {
this.name = name;
this.price = price;
this.type = productType;
this.thumbnailUrl = thumbnailUrl;
}
}
| 1,247 | 0.684042 | 0.684042 | 44 | 27.34091 | 20.285398 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
3
|
c3a0bc2dbd145c91fe73eaece11ef178f3a92a40
| 22,471,268,910,294 |
f5d774a3324e125367534ef01d1656efa94cc71a
|
/Taschenrechner/src/DataTypes/Stack.java
|
bcce26f42d2b867c6516f6cd78a26ad8759a624e
|
[] |
no_license
|
sillydomnom/silly
|
https://github.com/sillydomnom/silly
|
9ff1728bc486e10ef6ea66f59a89e377e013553b
|
82f5221934b4a6aba0dddfb99c90f1711597a88e
|
refs/heads/master
| 2021-11-20T12:52:46.257000 | 2018-06-08T21:57:35 | 2018-06-08T21:57:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* My own stack class
* ADS 1 - Telematik - TH Wildau
*
* @author Roman Kobosil
* @version 1.0, 29.03.17
*/
public class Stack<T> {
//set the maximum size
public final static int MAX_ITEMS = 20;
private Object[] array = new Object[MAX_ITEMS];
//point on the next position in the array
private int nextIndex = 0;
/**
* Add item to the stack, if MAX_ITEMS is not reached
*
* @param item the item to add
* @return success
*/
public boolean push(T item) {
//check if MAX_ITEMS is reached
if (nextIndex <= MAX_ITEMS - 1) {
//fill next position --> add to stack
array[nextIndex] = item;
//increase the index counter
nextIndex++;
//return success
return true;
} else {
return false;
}
}
/**
* Give the last item from stack and remove it from stack
*
* @return the last item on the stack
*/
public T pop() {
//check if stack contains item
if (nextIndex > 0) {
//go one index back
nextIndex--;
//get value
T result = (T) array[nextIndex];
//delete from array
array[nextIndex] = null;
//return
return result;
} else {
return null;
}
}
/**
* Give the last item from stack
*
* @return the last item on the stack
*/
public T peek() {
//check if stack contains item
if (nextIndex > 0) {
//return last item from stack
return (T) array[nextIndex - 1];
} else {
return null;
}
}
/**
* Check the stack contains items
*
* @return if the stack contains items
*/
public boolean isEmpty() {
//when next index is 0, the stack has no items
return nextIndex == 0;
}
}
|
UTF-8
|
Java
| 1,951 |
java
|
Stack.java
|
Java
|
[
{
"context": "ass\n * ADS 1 - Telematik - TH Wildau\n *\n * @author Roman Kobosil\n * @version 1.0, 29.03.17\n */\npublic class Stack<",
"end": 86,
"score": 0.9998151063919067,
"start": 73,
"tag": "NAME",
"value": "Roman Kobosil"
}
] | null |
[] |
/**
* My own stack class
* ADS 1 - Telematik - TH Wildau
*
* @author <NAME>
* @version 1.0, 29.03.17
*/
public class Stack<T> {
//set the maximum size
public final static int MAX_ITEMS = 20;
private Object[] array = new Object[MAX_ITEMS];
//point on the next position in the array
private int nextIndex = 0;
/**
* Add item to the stack, if MAX_ITEMS is not reached
*
* @param item the item to add
* @return success
*/
public boolean push(T item) {
//check if MAX_ITEMS is reached
if (nextIndex <= MAX_ITEMS - 1) {
//fill next position --> add to stack
array[nextIndex] = item;
//increase the index counter
nextIndex++;
//return success
return true;
} else {
return false;
}
}
/**
* Give the last item from stack and remove it from stack
*
* @return the last item on the stack
*/
public T pop() {
//check if stack contains item
if (nextIndex > 0) {
//go one index back
nextIndex--;
//get value
T result = (T) array[nextIndex];
//delete from array
array[nextIndex] = null;
//return
return result;
} else {
return null;
}
}
/**
* Give the last item from stack
*
* @return the last item on the stack
*/
public T peek() {
//check if stack contains item
if (nextIndex > 0) {
//return last item from stack
return (T) array[nextIndex - 1];
} else {
return null;
}
}
/**
* Check the stack contains items
*
* @return if the stack contains items
*/
public boolean isEmpty() {
//when next index is 0, the stack has no items
return nextIndex == 0;
}
}
| 1,944 | 0.507432 | 0.498206 | 82 | 22.792683 | 15.996751 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.219512 | false | false |
3
|
66db18bcd544056f13442af750e20a8c5abbe9d8
| 10,436,770,577,804 |
b883bf8305ad697a767c84915fc103c005d9eb0e
|
/2/Two_Numbers.java
|
be226f917f3eed81116fa19f108b287ae48093ad
|
[] |
no_license
|
S0m3-th1ng/LeetCode-Solutions
|
https://github.com/S0m3-th1ng/LeetCode-Solutions
|
91a7899d6b6f95466bc6559acf8b85e457e017f5
|
2ec06dde0ff7196c0d0435a12817f9bb57771d79
|
refs/heads/master
| 2023-08-14T23:02:21.179000 | 2021-09-28T16:52:14 | 2021-09-28T16:52:14 | 411,362,858 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class ListNode{
int val;
ListNode next;
ListNode(){
this.val = 0;
this.next = null;
}
ListNode(int val){
this.val = val;
this.next = null;
}
}
public class Two_Numbers{
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(0),temp = l3,head;
int n = 0;
while(l1 != null || l2 != null){
int x=0,y=0;
if (l1 != null){
x = l1.val;
l1=l1.next;
}
if (l2 != null){
y = l2.val;
l2=l2.next;
}
temp.next = new ListNode( ((x +y + n)%10));
n = (x + y + n)/10;
temp = temp.next;
}
if(n != 0){
temp.next = new ListNode(n);
}
return l3.next;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
ListNode l3 = addTwoNumbers(l1,l2);
while(l3 != null){
System.out.println(l3.val);
l3 = l3.next;
}
}
}
|
UTF-8
|
Java
| 1,101 |
java
|
Two_Numbers.java
|
Java
|
[] | null |
[] |
class ListNode{
int val;
ListNode next;
ListNode(){
this.val = 0;
this.next = null;
}
ListNode(int val){
this.val = val;
this.next = null;
}
}
public class Two_Numbers{
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(0),temp = l3,head;
int n = 0;
while(l1 != null || l2 != null){
int x=0,y=0;
if (l1 != null){
x = l1.val;
l1=l1.next;
}
if (l2 != null){
y = l2.val;
l2=l2.next;
}
temp.next = new ListNode( ((x +y + n)%10));
n = (x + y + n)/10;
temp = temp.next;
}
if(n != 0){
temp.next = new ListNode(n);
}
return l3.next;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
ListNode l3 = addTwoNumbers(l1,l2);
while(l3 != null){
System.out.println(l3.val);
l3 = l3.next;
}
}
}
| 1,101 | 0.520436 | 0.480472 | 49 | 21.489796 | 13.65332 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.959184 | false | false |
3
|
7f2b52296ecc8b5ec5ddafb61eec1050f02173b7
| 13,640,816,200,727 |
a10245d7651017204b989b5573dffa5dc1d78437
|
/src/main/java/com/ldq/study/reflexAndAnnotation/anno/FieldAnnotation.java
|
712bf16a105b0bbb2453cb81fa88c8b54909b108
|
[] |
no_license
|
DaqianLiao/StudyJavaCode
|
https://github.com/DaqianLiao/StudyJavaCode
|
39753db68cd0ad1c1b7fbea3eb730408dfec62e7
|
e34b455e19f4d7e89067ee425805aafecbc4b5e4
|
refs/heads/master
| 2022-06-26T17:51:25.329000 | 2021-03-15T03:03:16 | 2021-03-15T03:03:16 | 192,666,841 | 0 | 0 | null | false | 2022-06-17T03:30:52 | 2019-06-19T05:49:35 | 2021-03-15T03:03:45 | 2022-06-17T03:30:52 | 5,376 | 0 | 0 | 5 |
Java
| false | false |
package com.ldq.study.reflexAndAnnotation.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 长用在字段上的注解
* NotEmpty/NotBlank/NotNull
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
String name() default "field name";
String value() default "field value";
}
|
UTF-8
|
Java
| 466 |
java
|
FieldAnnotation.java
|
Java
|
[] | null |
[] |
package com.ldq.study.reflexAndAnnotation.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 长用在字段上的注解
* NotEmpty/NotBlank/NotNull
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
String name() default "field name";
String value() default "field value";
}
| 466 | 0.774554 | 0.774554 | 18 | 23.888889 | 17.479794 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false |
3
|
4a86f52bb580238fe5fe06c8d9ab058c39bdb886
| 7,456,063,244,696 |
50a78281ccbb616a0a61734476d80bc73c76bcd2
|
/PaintHouseII_265.java
|
7c6b36a3b6f3758f9f71bc219c83d74b20a2a698
|
[] |
no_license
|
Martin1991/leetcode
|
https://github.com/Martin1991/leetcode
|
f25acf83fbd3cccde587258b9d876e445f5b745f
|
0d313cc6a336d3e19bffe970a9d4a1dcad97a8f4
|
refs/heads/master
| 2020-12-24T11:37:11.334000 | 2016-11-13T03:32:58 | 2016-11-13T03:32:58 | 73,027,116 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class PaintHouseII_265 {
//O(nk^2) time, O(nk) space
public static int minCostII(int[][] costs) {
if(costs == null || costs.length == 0 || costs[0].length == 0) return 0;
int n = costs.length;
int k = costs[0].length;
if(k == 1) return (n==1? costs[0][0] : -1);
int[][] dp = new int[n][k];
for(int i = 0; i<n; i++){
for(int j = 0; j<k; j++){
dp[i][j] = Integer.MAX_VALUE;
}
}
for(int j = 0; j<k; j++){
dp[0][j] = costs[0][j];
}
for(int i = 1; i<n; i++){
for(int j = 0; j<k; j++){
for(int l = 0; l<k; l++){
if(l!=j){
dp[i][j] = Math.min(dp[i-1][l]+costs[i][j], dp[i][j]);
}
}
}
}
int min = Integer.MAX_VALUE;
for(int j = 0; j<k; j++){
min = Math.min(dp[n-1][j],min);
}
return min;
}
//O(nk) time, O(1) space
public static int minCostII2(int[][] costs) {
//base case
if(costs == null || costs.length == 0 || costs[0].length == 0) return 0;
int n = costs.length, k = costs[0].length;
int preMin = 0, preSecMin = 0, preMinIdx = -1;
for(int i = 0; i<n; i++){
int min = Integer.MIN_VALUE, secMin = Integer.MAX_VALUE, minIdx = -1;
for(int j = 0; j<k; j++){
int val = costs[i][j] + (preMinIdx == j? preSecMin : preMin);
if(minIdx < 0) {
min = val;
minIdx = j;
}else if(val < min){
secMin = min;
min = val;
minIdx = j;
}else if(val < secMin){
secMin = val;
}
}
preMin = min;
preSecMin = secMin;
preMinIdx = minIdx;
}
return preMin;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
UTF-8
|
Java
| 2,177 |
java
|
PaintHouseII_265.java
|
Java
|
[] | null |
[] |
public class PaintHouseII_265 {
//O(nk^2) time, O(nk) space
public static int minCostII(int[][] costs) {
if(costs == null || costs.length == 0 || costs[0].length == 0) return 0;
int n = costs.length;
int k = costs[0].length;
if(k == 1) return (n==1? costs[0][0] : -1);
int[][] dp = new int[n][k];
for(int i = 0; i<n; i++){
for(int j = 0; j<k; j++){
dp[i][j] = Integer.MAX_VALUE;
}
}
for(int j = 0; j<k; j++){
dp[0][j] = costs[0][j];
}
for(int i = 1; i<n; i++){
for(int j = 0; j<k; j++){
for(int l = 0; l<k; l++){
if(l!=j){
dp[i][j] = Math.min(dp[i-1][l]+costs[i][j], dp[i][j]);
}
}
}
}
int min = Integer.MAX_VALUE;
for(int j = 0; j<k; j++){
min = Math.min(dp[n-1][j],min);
}
return min;
}
//O(nk) time, O(1) space
public static int minCostII2(int[][] costs) {
//base case
if(costs == null || costs.length == 0 || costs[0].length == 0) return 0;
int n = costs.length, k = costs[0].length;
int preMin = 0, preSecMin = 0, preMinIdx = -1;
for(int i = 0; i<n; i++){
int min = Integer.MIN_VALUE, secMin = Integer.MAX_VALUE, minIdx = -1;
for(int j = 0; j<k; j++){
int val = costs[i][j] + (preMinIdx == j? preSecMin : preMin);
if(minIdx < 0) {
min = val;
minIdx = j;
}else if(val < min){
secMin = min;
min = val;
minIdx = j;
}else if(val < secMin){
secMin = val;
}
}
preMin = min;
preSecMin = secMin;
preMinIdx = minIdx;
}
return preMin;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| 2,177 | 0.376665 | 0.358751 | 75 | 28.013334 | 19.511702 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.96 | false | false |
3
|
bbd51796f4d40ee7e0a3a42a6b17829e7d330337
| 7,456,063,246,814 |
68be93ccae73afeeebd8c0b46698016b4c19e665
|
/src/main/java/info/hexin/lang/reflect/Klass.java
|
ac8307d05b73cf2f51a3e82a91aa9acc05fbd9dd
|
[] |
no_license
|
maczam/jmacs
|
https://github.com/maczam/jmacs
|
0a47ea9666d4037933a0c39a1773e9915facddbb
|
f95f32ae60c7e740a1793b26bba6f22788b314e8
|
refs/heads/master
| 2020-05-05T07:08:48.949000 | 2015-04-05T14:43:37 | 2015-04-05T14:43:37 | 12,884,496 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package info.hexin.lang.reflect;
/**
* class 部分工具
*
* @author hexin
*
*/
public abstract class Klass {
/**
* 判断klass 是不是interFaceClass接口的实现类
*
* @param klass
* @param interFaceClass
* @return
*/
public static boolean isInterfaceFrom(Class<?> klass, Class<?> interFaceClass) {
if (klass.isInterface()) {
return false;
}
while (klass != null) {
Class<?>[] interfaces = klass.getInterfaces();
for (Class<?> type : interfaces) {
if (interFaceClass == type) {
return true;
}
}
klass = klass.getSuperclass();
}
return false;
}
}
|
UTF-8
|
Java
| 792 |
java
|
Klass.java
|
Java
|
[
{
"context": "ng.reflect;\r\n\r\n/**\r\n * class 部分工具\r\n * \r\n * @author hexin\r\n * \r\n */\r\npublic abstract class Klass {\r\n\r\n /",
"end": 77,
"score": 0.9988083243370056,
"start": 72,
"tag": "USERNAME",
"value": "hexin"
}
] | null |
[] |
package info.hexin.lang.reflect;
/**
* class 部分工具
*
* @author hexin
*
*/
public abstract class Klass {
/**
* 判断klass 是不是interFaceClass接口的实现类
*
* @param klass
* @param interFaceClass
* @return
*/
public static boolean isInterfaceFrom(Class<?> klass, Class<?> interFaceClass) {
if (klass.isInterface()) {
return false;
}
while (klass != null) {
Class<?>[] interfaces = klass.getInterfaces();
for (Class<?> type : interfaces) {
if (interFaceClass == type) {
return true;
}
}
klass = klass.getSuperclass();
}
return false;
}
}
| 792 | 0.473753 | 0.473753 | 34 | 20.411764 | 18.997086 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.205882 | false | false |
3
|
0adbd3034755bdb290ed2d37f3e326cf5a7c5283
| 7,456,063,243,540 |
7101d9ca08c5376182ea4c41eeb871e51e3f9c72
|
/A0121I1-Module2/06 Inheritance/Bai Tap/src/circleAndCylinder/CircleTest.java
|
8ee17fd0d4fe9b1d4e1f500a9931b9ca49cf9bf3
|
[] |
no_license
|
lehoanglong12345/A0121I1-Module2-LeHoangLong
|
https://github.com/lehoanglong12345/A0121I1-Module2-LeHoangLong
|
526450cb97072a83d894ee8df51cbe5fc5bb72f5
|
3ce11fc82bf42981243c722dbdac0821a71838e6
|
refs/heads/master
| 2023-05-26T06:53:17.938000 | 2021-06-18T12:20:39 | 2021-06-18T12:20:39 | 364,979,574 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package circleAndCylinder;
import java.util.Scanner;
public class CircleTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Circle circle1 = new Circle();
System.out.println("Nhap color circle1: ");
circle1.setColor(input.nextLine());
System.out.println("Nhap ban kinh circle1: ");
circle1.setRadius(input.nextDouble());
System.out.println("Co to mau ko?");
circle1.setFilled(input.nextBoolean());
System.out.println(circle1.toString());
Circle circle2 = new Circle(3.5);
System.out.println("Circle2 co to mau ko?");
circle2.setFilled(input.nextBoolean());
System.out.println(circle2.toString());
Circle circle3 = new Circle(6, "indigo", false);
System.out.println(circle3.toString());
}
}
|
UTF-8
|
Java
| 858 |
java
|
CircleTest.java
|
Java
|
[] | null |
[] |
package circleAndCylinder;
import java.util.Scanner;
public class CircleTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Circle circle1 = new Circle();
System.out.println("Nhap color circle1: ");
circle1.setColor(input.nextLine());
System.out.println("Nhap ban kinh circle1: ");
circle1.setRadius(input.nextDouble());
System.out.println("Co to mau ko?");
circle1.setFilled(input.nextBoolean());
System.out.println(circle1.toString());
Circle circle2 = new Circle(3.5);
System.out.println("Circle2 co to mau ko?");
circle2.setFilled(input.nextBoolean());
System.out.println(circle2.toString());
Circle circle3 = new Circle(6, "indigo", false);
System.out.println(circle3.toString());
}
}
| 858 | 0.635198 | 0.61655 | 25 | 33.32 | 19.768095 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.76 | false | false |
3
|
189aa486a84327ddd9d024e9401cd13fab1738e4
| 30,253,749,638,555 |
f75d1d69fda1084f9782ecd968190ccb1efc2d14
|
/dd_zyz/src/main/java/com/baizhi/service/UserBookService.java
|
c777753717df9e96b62c5024213e2e0d30cd04c7
|
[] |
no_license
|
zhuyanzhuo/testhq
|
https://github.com/zhuyanzhuo/testhq
|
053c49f170d61141bb4fdca189b76a96ffe8efb7
|
010bbc2ac59645d59cdd957547a315a6911dcc61
|
refs/heads/master
| 2020-05-16T08:00:49.280000 | 2019-05-20T09:07:43 | 2019-05-20T09:07:43 | 182,895,266 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.baizhi.service;
public interface UserBookService {
/**
* 将用户id和图书id存入用户——图书表
* @param bookId
* @param userId
*/
void save(String bookId,String userId);
}
|
UTF-8
|
Java
| 208 |
java
|
UserBookService.java
|
Java
|
[] | null |
[] |
package com.baizhi.service;
public interface UserBookService {
/**
* 将用户id和图书id存入用户——图书表
* @param bookId
* @param userId
*/
void save(String bookId,String userId);
}
| 208 | 0.696629 | 0.696629 | 11 | 15.181818 | 13.782849 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false |
3
|
1d485437a03ec2baa5267eb32dae308ce6aecf8d
| 15,556,371,551,728 |
9744728bc4e860b9012abb60c5d27b7b44ab6772
|
/src/test/java/com/gooalgene/wutbiolab/SRTests.java
|
e9de64441eaaba22cbf228c645023e42b2375af0
|
[] |
no_license
|
HastyFish/wutbiolab
|
https://github.com/HastyFish/wutbiolab
|
80e0520ac5a75546d292d61626c1ddf9cccc4dbb
|
88319ba1513ef3033de6cf16b3b6502d90c97df8
|
refs/heads/dev
| 2023-01-20T14:06:04.170000 | 2019-12-04T10:12:51 | 2019-12-04T10:12:51 | 224,325,841 | 0 | 0 | null | false | 2023-01-04T13:21:25 | 2019-11-27T02:19:48 | 2019-12-04T10:13:15 | 2023-01-04T13:21:24 | 6,254 | 0 | 0 | 49 |
JavaScript
| false | false |
package com.gooalgene.wutbiolab;
import com.gooalgene.wutbiolab.dao.scientific.ScientificResearchDetailDAO;
import com.gooalgene.wutbiolab.entity.scientificResearch.ScientificResearchCategory;
import com.gooalgene.wutbiolab.entity.scientificResearch.ScientificResearchDetail;
import com.gooalgene.wutbiolab.service.ScientificResearchService;
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.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SRTests {
@Autowired
private ScientificResearchService scientificResearchService;
@Autowired
private ScientificResearchDetailDAO scientificResearchDetailDAO;
@Test
public void testService(){
ScientificResearchDetail scientificResearchDetail=new ScientificResearchDetail();
scientificResearchDetail.setAuthor("huyao4");
scientificResearchDetail.setContext("胡尧牛逼4");
scientificResearchDetail.setPeriodicalName("干大事的4");
// scientificResearchDetail.setId(3l);
// scientificResearchService.saveOrPublish(scientificResearchDetail, CommonConstants.PUBLISHED);
}
@Test
public void testService2(){
// Map<String, ScientificResearchDetail> publishedById62 = scientificResearchService.getPublishedById(62l);
// Map<String, ScientificResearchDetail> publishedById61 = scientificResearchService.getPublishedById(61l);
// Map<String, ScientificResearchDetail> publishedById60 = scientificResearchService.getPublishedById(60l);
// Map<String, ScientificResearchDetail> publishedById59 = scientificResearchService.getPublishedById(59l);
// Map<String, ScientificResearchDetail> publishedById58 = scientificResearchService.getPublishedById(58l);
System.out.println(1);
}
@Test
public void testDao(){
List<Object[]> srAcademicList = scientificResearchDetailDAO.getSRAcademicList(0,19);
Long srAcademicListCount = scientificResearchDetailDAO.getSRAcademicListCount();
System.out.println(1);
}
}
|
UTF-8
|
Java
| 2,251 |
java
|
SRTests.java
|
Java
|
[
{
"context": "il();\n scientificResearchDetail.setAuthor(\"huyao4\");\n scientificResearchDetail.setContext(\"胡",
"end": 1046,
"score": 0.9517759084701538,
"start": 1040,
"tag": "USERNAME",
"value": "huyao4"
}
] | null |
[] |
package com.gooalgene.wutbiolab;
import com.gooalgene.wutbiolab.dao.scientific.ScientificResearchDetailDAO;
import com.gooalgene.wutbiolab.entity.scientificResearch.ScientificResearchCategory;
import com.gooalgene.wutbiolab.entity.scientificResearch.ScientificResearchDetail;
import com.gooalgene.wutbiolab.service.ScientificResearchService;
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.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SRTests {
@Autowired
private ScientificResearchService scientificResearchService;
@Autowired
private ScientificResearchDetailDAO scientificResearchDetailDAO;
@Test
public void testService(){
ScientificResearchDetail scientificResearchDetail=new ScientificResearchDetail();
scientificResearchDetail.setAuthor("huyao4");
scientificResearchDetail.setContext("胡尧牛逼4");
scientificResearchDetail.setPeriodicalName("干大事的4");
// scientificResearchDetail.setId(3l);
// scientificResearchService.saveOrPublish(scientificResearchDetail, CommonConstants.PUBLISHED);
}
@Test
public void testService2(){
// Map<String, ScientificResearchDetail> publishedById62 = scientificResearchService.getPublishedById(62l);
// Map<String, ScientificResearchDetail> publishedById61 = scientificResearchService.getPublishedById(61l);
// Map<String, ScientificResearchDetail> publishedById60 = scientificResearchService.getPublishedById(60l);
// Map<String, ScientificResearchDetail> publishedById59 = scientificResearchService.getPublishedById(59l);
// Map<String, ScientificResearchDetail> publishedById58 = scientificResearchService.getPublishedById(58l);
System.out.println(1);
}
@Test
public void testDao(){
List<Object[]> srAcademicList = scientificResearchDetailDAO.getSRAcademicList(0,19);
Long srAcademicListCount = scientificResearchDetailDAO.getSRAcademicListCount();
System.out.println(1);
}
}
| 2,251 | 0.789262 | 0.775392 | 51 | 42.823528 | 37.226761 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false |
3
|
50c675b887a99095b764057aec81998e61686107
| 4,664,334,518,605 |
9c6bd20f88d40bbc24d26eff58c95ef1fb2af8dc
|
/app/src/main/java/ren/shimian/sleeplessness/activity/SplashActivity.java
|
640409263e06ffa8344ab41229aa6bceac36a108
|
[] |
no_license
|
98ki/Sleeplessness
|
https://github.com/98ki/Sleeplessness
|
92c20218218803bae0d1abb1b1830a271122450d
|
eb2e696ed92ee35d22e32df768f2b5c980dbb2d0
|
refs/heads/master
| 2016-02-24T21:44:05.838000 | 2015-12-10T09:21:22 | 2015-12-10T09:21:22 | 35,029,038 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ren.shimian.sleeplessness.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import com.a98ki.common.util.Utils;
import com.a98ki.mycenter.activity.LoginActivity;
import ren.shimian.sleeplessness.MainApplication;
import ren.shimian.sleeplessness.R;
public class SplashActivity extends Activity {
private final int REQUEST_CODE_LOGIN = 1;
private final int RESULT_CODE_LOGIN_SUCCESS = 1;
private Context mContext;
private ImageView mImageView;
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mContext = this;
mActivity = this;
findView();
init();
}
private void findView() {
mImageView = (ImageView) findViewById(R.id.iv_welcome);
}
@SuppressWarnings("static-access")
private void init() {
mImageView.postDelayed(new Runnable() {
@Override
public void run() {
boolean isFirst = Utils.isFirstStart(MainApplication.getInstance());
if (!isFirst) {
Utils.setFirstStart(MainApplication.getInstance(), false);
Intent intent = new Intent(mActivity, LoginActivity.class);
startActivityForResult(intent, REQUEST_CODE_LOGIN);
} else {
Utils.setFirstStart(MainApplication.getInstance(), false);
Intent intent = new Intent(mActivity, LoginActivity.class);
startActivityForResult(intent, REQUEST_CODE_LOGIN); }
}
}, 4000);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_LOGIN:
if (resultCode == RESULT_CODE_LOGIN_SUCCESS) {
MainActivity.startActivity(this);
}
}
}
}
|
UTF-8
|
Java
| 2,312 |
java
|
SplashActivity.java
|
Java
|
[] | null |
[] |
package ren.shimian.sleeplessness.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import com.a98ki.common.util.Utils;
import com.a98ki.mycenter.activity.LoginActivity;
import ren.shimian.sleeplessness.MainApplication;
import ren.shimian.sleeplessness.R;
public class SplashActivity extends Activity {
private final int REQUEST_CODE_LOGIN = 1;
private final int RESULT_CODE_LOGIN_SUCCESS = 1;
private Context mContext;
private ImageView mImageView;
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mContext = this;
mActivity = this;
findView();
init();
}
private void findView() {
mImageView = (ImageView) findViewById(R.id.iv_welcome);
}
@SuppressWarnings("static-access")
private void init() {
mImageView.postDelayed(new Runnable() {
@Override
public void run() {
boolean isFirst = Utils.isFirstStart(MainApplication.getInstance());
if (!isFirst) {
Utils.setFirstStart(MainApplication.getInstance(), false);
Intent intent = new Intent(mActivity, LoginActivity.class);
startActivityForResult(intent, REQUEST_CODE_LOGIN);
} else {
Utils.setFirstStart(MainApplication.getInstance(), false);
Intent intent = new Intent(mActivity, LoginActivity.class);
startActivityForResult(intent, REQUEST_CODE_LOGIN); }
}
}, 4000);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_LOGIN:
if (resultCode == RESULT_CODE_LOGIN_SUCCESS) {
MainActivity.startActivity(this);
}
}
}
}
| 2,312 | 0.634948 | 0.630623 | 74 | 30.243244 | 25.299723 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594595 | false | false |
3
|
26eeaa2efb5bf8ce5af0b1f73db830004ee35705
| 6,210,522,776,690 |
d674394945a3f714adf0ba6cd431079c4881e94e
|
/palace-java-basics/src/main/java/com/flysnow/palace/basics/javaBase/clone/StudentB.java
|
aa40e84313b54538ca816c3b515237af5c094910
|
[] |
no_license
|
gelysting/palace-java
|
https://github.com/gelysting/palace-java
|
53073ac601f9763b7b48c4b25ecda0c915f150f3
|
798e49114a881b445f9996dd486d2bf899ea09a8
|
refs/heads/master
| 2023-04-27T10:33:30.428000 | 2020-01-07T05:53:08 | 2020-01-07T05:53:08 | 228,348,664 | 3 | 0 | null | false | 2023-04-17T19:39:41 | 2019-12-16T09:21:21 | 2020-01-07T05:53:55 | 2023-04-17T19:39:38 | 758 | 1 | 0 | 2 |
Java
| false | false |
package com.flysnow.palace.basics.javaBase.clone;
/**
* @Package com.flysnow.palace.basics.javaBase.clone
* @Description
* @Author Fly
* @Date 2019-11-26 14:36
* @Version V1.0
*/
public class StudentB implements Cloneable {
private int age;
private String name;
private Teacher teacher;
// getter和setter省略
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public Object clone() throws CloneNotSupportedException {
// 这一步返回的这个student还只是一个浅克隆,
StudentB student = (StudentB) super.clone();
// 然后克隆的过程中获得这个克隆的student,然后调用这个getTeacher这个方方法得到这个Teacher对象。
// 然后实现克隆。在设置到这个student中的Teacher。
// 这样实现了双层克隆使得那个teacher对象也得到了复制。
student.setTeacher((Teacher) student.getTeacher().clone());
// 双层克隆使得那个teacher对象也得到了复制
return student;
}
}
|
UTF-8
|
Java
| 1,399 |
java
|
StudentB.java
|
Java
|
[
{
"context": "e.basics.javaBase.clone\n * @Description\n * @Author Fly\n * @Date 2019-11-26 14:36\n * @Version V1.0\n */\n\np",
"end": 138,
"score": 0.9790352582931519,
"start": 135,
"tag": "NAME",
"value": "Fly"
}
] | null |
[] |
package com.flysnow.palace.basics.javaBase.clone;
/**
* @Package com.flysnow.palace.basics.javaBase.clone
* @Description
* @Author Fly
* @Date 2019-11-26 14:36
* @Version V1.0
*/
public class StudentB implements Cloneable {
private int age;
private String name;
private Teacher teacher;
// getter和setter省略
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public Object clone() throws CloneNotSupportedException {
// 这一步返回的这个student还只是一个浅克隆,
StudentB student = (StudentB) super.clone();
// 然后克隆的过程中获得这个克隆的student,然后调用这个getTeacher这个方方法得到这个Teacher对象。
// 然后实现克隆。在设置到这个student中的Teacher。
// 这样实现了双层克隆使得那个teacher对象也得到了复制。
student.setTeacher((Teacher) student.getTeacher().clone());
// 双层克隆使得那个teacher对象也得到了复制
return student;
}
}
| 1,399 | 0.636517 | 0.624683 | 53 | 21.320755 | 19.05382 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.245283 | false | false |
3
|
03ea6bc393ee951097e392cc29014b81ee2e3955
| 11,484,742,611,773 |
462f3caf3c63a7d5e559bea3eb4a8ba06b4d8073
|
/common/src/main/java/com/example/wirelessdroid/common/route/RouteBuilder.java
|
a6dff47fe18196014d6b6a582df8f5ed9562e5cf
|
[] |
no_license
|
Murmurl912/WirelessDorid
|
https://github.com/Murmurl912/WirelessDorid
|
ce9c223b068aef34cabd41ba09caefcfd1212836
|
4f69131f22dfe624518bedc2a2bad242380d95e5
|
refs/heads/master
| 2023-01-20T17:17:42.574000 | 2020-11-23T12:41:09 | 2020-11-23T12:41:09 | 305,087,873 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.wirelessdroid.common.route;
import java.util.function.BiFunction;
public class RouteBuilder {
private final PathPatternParser DEFAULT_PATH_PATTERN_PARSER = new PathPatternParser();
public RouteBuilder() {
}
public <T, U, R> RouteBuilder GET(String url, BiFunction<T, U, R> handler) {
PathPattern pattern = pattern(url);
return this;
}
;
private PathPattern pattern(String url) {
return DEFAULT_PATH_PATTERN_PARSER.parse(url);
}
}
|
UTF-8
|
Java
| 516 |
java
|
RouteBuilder.java
|
Java
|
[] | null |
[] |
package com.example.wirelessdroid.common.route;
import java.util.function.BiFunction;
public class RouteBuilder {
private final PathPatternParser DEFAULT_PATH_PATTERN_PARSER = new PathPatternParser();
public RouteBuilder() {
}
public <T, U, R> RouteBuilder GET(String url, BiFunction<T, U, R> handler) {
PathPattern pattern = pattern(url);
return this;
}
;
private PathPattern pattern(String url) {
return DEFAULT_PATH_PATTERN_PARSER.parse(url);
}
}
| 516 | 0.678295 | 0.678295 | 25 | 19.639999 | 26.217369 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false |
3
|
fb55c745a6a10d5703f32f19e06fbcf8ff25dad9
| 20,486,994,009,999 |
97bf78a22e9c027f15a09615be0eba72070c86bc
|
/solutions/java/0560.java
|
b67879d22958b168c3001f067f4512a2fa60dd1e
|
[] |
no_license
|
angelahxchen/LeetCode
|
https://github.com/angelahxchen/LeetCode
|
ddeb886c8077445659042d8de16112ea2fd33963
|
6ef61ef32b4006b0771317242e416290f76c78d1
|
refs/heads/master
| 2022-08-28T00:24:41.223000 | 2020-05-24T16:47:20 | 2020-05-24T16:47:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Solution {
public int subarraySum(int[] nums, int k) {
int ans = 0;
int sum = 0;
Map<Integer, Integer> count = new HashMap<>();
count.put(0, 1);
for (int num : nums) {
sum += num;
ans += count.getOrDefault(sum - k, 0);
count.put(sum, count.getOrDefault(sum, 0) + 1);
}
return ans;
}
}
|
UTF-8
|
Java
| 342 |
java
|
0560.java
|
Java
|
[] | null |
[] |
class Solution {
public int subarraySum(int[] nums, int k) {
int ans = 0;
int sum = 0;
Map<Integer, Integer> count = new HashMap<>();
count.put(0, 1);
for (int num : nums) {
sum += num;
ans += count.getOrDefault(sum - k, 0);
count.put(sum, count.getOrDefault(sum, 0) + 1);
}
return ans;
}
}
| 342 | 0.54386 | 0.523392 | 16 | 20.4375 | 17.642168 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false |
3
|
c610d7f4f52de902b8263ef5b0488c7c96948deb
| 10,273,561,789,035 |
305fd32b8bcd256224b229fa12bd0a2e15558ec1
|
/2021-04-19/RemoveEle.java
|
7519d62171a5c47a0d27a45aead2e9a4749fcd93
|
[] |
no_license
|
RanjithKumar-droid/leetcode
|
https://github.com/RanjithKumar-droid/leetcode
|
4f69f8d7763f1846d3ce5d812c5f7cdfb7319935
|
3f0f519a181bf622494e523b00698c81bb767161
|
refs/heads/main
| 2023-06-01T09:01:19.879000 | 2021-07-03T07:19:02 | 2021-07-03T07:19:02 | 355,102,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class RemoveEle{
public int removeElement(int[] nums, int val) {
int ptr = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] != val) nums[ptr++] = nums[i];
}
return ptr;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter len of array");
int len = scan.nextInt();
int arr[] = new int[len];
System.out.println("Enter "+len+" no of inputs");
for(int i=0;i<len;i++) {
int arr[i] = scan.nextInt();
}
System.out.println("Enter value");
int value= scan.nextLine();
System.out.println(sum(arr, value));
}
}
|
UTF-8
|
Java
| 644 |
java
|
RemoveEle.java
|
Java
|
[] | null |
[] |
class RemoveEle{
public int removeElement(int[] nums, int val) {
int ptr = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] != val) nums[ptr++] = nums[i];
}
return ptr;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter len of array");
int len = scan.nextInt();
int arr[] = new int[len];
System.out.println("Enter "+len+" no of inputs");
for(int i=0;i<len;i++) {
int arr[i] = scan.nextInt();
}
System.out.println("Enter value");
int value= scan.nextLine();
System.out.println(sum(arr, value));
}
}
| 644 | 0.569876 | 0.565217 | 22 | 27.363636 | 16.221605 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false |
3
|
23a43c262f5bf455946bea651a2b18c2c0fa2661
| 16,569,983,886,394 |
a7d23393561cbd51920de42255cc7148178961e5
|
/src/server/model/players/skills/Firemaking.java
|
7f138b0b251c97171652ff0ed9e4cbffcda24e51
|
[] |
no_license
|
LoveLeAnon/Area59
|
https://github.com/LoveLeAnon/Area59
|
e9fe800a6a4b3340f3519e9152f3de7032b52df0
|
84e9bc29bf2db5d01149f0151b6332d2f58d09b4
|
refs/heads/master
| 2017-04-28T17:22:17.594000 | 2014-09-19T09:11:43 | 2014-09-19T09:11:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package server.model.players.skills;
import server.model.objects.*;
import server.model.players.*;
import server.*;
import server.clip.region.*;
import server.util.Misc;
import server.world.ObjectHandler;
import server.event.CycleEvent;
import server.event.CycleEventContainer;
import server.event.CycleEventHandler;
/**
* Firemaking.java
*
* @author Sanity
*
**/
public class Firemaking {
private Client c;
private int[] logs = { 1511, 1521, 1519, 1517, 1515, 1513 };
private int[] exp = {30,60,80,100,120,150};
private int[] level = { 1, 15, 30, 45, 60, 75 };
public long lastLight;
private int fireId = 2732;
private int DELAY = 1250;
public boolean resetAnim = false;
public Firemaking(Client c) {
this.c = c;
}
public void checkLogType(int logType, int otherItem) {
for (int j = 0; j < logs.length; j++) {
if (logs[j] == logType || logs[j] == otherItem) {
lightFire(j);
return;
}
}
}
public void lightFire(int slot) {
if(c.absX == Objects.getObjectX() && c.absY == Objects.getObjectY() && Objects.getObjectId() > 0) {
c.sendMessage("You can't light a fire here!");
return;
}
if (c.duelStatus >= 5) {
c.sendMessage("Why am I trying to light a fire in the duel arena?");
return;
}
final int x = c.getX();
final int y = c.getY();
if (Region.getClipping(c.getX() - 1, c.getY(), c.heightLevel, -1, 0)) {
c.getPA().walkTo(-1, 0);
} else if (Region.getClipping(c.getX() + 1, c.getY(), c.heightLevel, 1, 0)) {
c.getPA().walkTo(1, 0);
} else if (Region.getClipping(c.getX(), c.getY() - 1, c.heightLevel, 0, -1)) {
c.getPA().walkTo(0, -1);
} else if (Region.getClipping(c.getX(), c.getY() + 1, c.heightLevel, 0, 1)) {
c.getPA().walkTo(0, 1);
}
//}
if (c.playerLevel[c.playerFiremaking] >= level[slot]) {
if (c.getItems().playerHasItem(590) && c.getItems().playerHasItem(logs[slot])) {
if (System.currentTimeMillis() - lastLight > DELAY) {
c.startAnimation(733,0);
c.getItems().deleteItem(logs[slot],
c.getItems().getItemSlot(logs[slot]), 1);
c.getPA().addSkillXP(
exp[slot] * Config.FIREMAKING_EXPERIENCE,
c.playerFiremaking);
c.sendMessage("You light the fire.");
//c.getPA().walkTo(0,0);
//c.getPA().checkObjectSpawn(fireId, x, y, 1, 10);
Server.objectHandler.createAnObject(c, fireId, x, y);
c.turnPlayerTo(c.getX() + 1, c.getY());
CycleEventHandler.getSingleton().addEvent(c, new CycleEvent() {
int timer = 1;
@Override
public void execute(CycleEventContainer container) {
if (timer == 0) {
container.stop();
}
timer--;
}
@Override
public void stop() {
c.getPA().checkObjectSpawn(-1, x, y, 1, 10);
//c.sendMessage("Your fire has been extinguished.");
Server.itemHandler.createGroundItem(c, 592, x, y, 1, c.playerId);
}
}, 45);
this.lastLight = System.currentTimeMillis();
//c.getPA().frame1();
//resetAnim = true;
c.startAnimation(65535);
}
}
}
}
}
|
UTF-8
|
Java
| 3,053 |
java
|
Firemaking.java
|
Java
|
[
{
"context": "ntHandler;\n\n\n/**\n * Firemaking.java\n * \n * @author Sanity\n * \n **/\npublic class Firemaking {\n\n private C",
"end": 364,
"score": 0.9985437393188477,
"start": 358,
"tag": "NAME",
"value": "Sanity"
}
] | null |
[] |
package server.model.players.skills;
import server.model.objects.*;
import server.model.players.*;
import server.*;
import server.clip.region.*;
import server.util.Misc;
import server.world.ObjectHandler;
import server.event.CycleEvent;
import server.event.CycleEventContainer;
import server.event.CycleEventHandler;
/**
* Firemaking.java
*
* @author Sanity
*
**/
public class Firemaking {
private Client c;
private int[] logs = { 1511, 1521, 1519, 1517, 1515, 1513 };
private int[] exp = {30,60,80,100,120,150};
private int[] level = { 1, 15, 30, 45, 60, 75 };
public long lastLight;
private int fireId = 2732;
private int DELAY = 1250;
public boolean resetAnim = false;
public Firemaking(Client c) {
this.c = c;
}
public void checkLogType(int logType, int otherItem) {
for (int j = 0; j < logs.length; j++) {
if (logs[j] == logType || logs[j] == otherItem) {
lightFire(j);
return;
}
}
}
public void lightFire(int slot) {
if(c.absX == Objects.getObjectX() && c.absY == Objects.getObjectY() && Objects.getObjectId() > 0) {
c.sendMessage("You can't light a fire here!");
return;
}
if (c.duelStatus >= 5) {
c.sendMessage("Why am I trying to light a fire in the duel arena?");
return;
}
final int x = c.getX();
final int y = c.getY();
if (Region.getClipping(c.getX() - 1, c.getY(), c.heightLevel, -1, 0)) {
c.getPA().walkTo(-1, 0);
} else if (Region.getClipping(c.getX() + 1, c.getY(), c.heightLevel, 1, 0)) {
c.getPA().walkTo(1, 0);
} else if (Region.getClipping(c.getX(), c.getY() - 1, c.heightLevel, 0, -1)) {
c.getPA().walkTo(0, -1);
} else if (Region.getClipping(c.getX(), c.getY() + 1, c.heightLevel, 0, 1)) {
c.getPA().walkTo(0, 1);
}
//}
if (c.playerLevel[c.playerFiremaking] >= level[slot]) {
if (c.getItems().playerHasItem(590) && c.getItems().playerHasItem(logs[slot])) {
if (System.currentTimeMillis() - lastLight > DELAY) {
c.startAnimation(733,0);
c.getItems().deleteItem(logs[slot],
c.getItems().getItemSlot(logs[slot]), 1);
c.getPA().addSkillXP(
exp[slot] * Config.FIREMAKING_EXPERIENCE,
c.playerFiremaking);
c.sendMessage("You light the fire.");
//c.getPA().walkTo(0,0);
//c.getPA().checkObjectSpawn(fireId, x, y, 1, 10);
Server.objectHandler.createAnObject(c, fireId, x, y);
c.turnPlayerTo(c.getX() + 1, c.getY());
CycleEventHandler.getSingleton().addEvent(c, new CycleEvent() {
int timer = 1;
@Override
public void execute(CycleEventContainer container) {
if (timer == 0) {
container.stop();
}
timer--;
}
@Override
public void stop() {
c.getPA().checkObjectSpawn(-1, x, y, 1, 10);
//c.sendMessage("Your fire has been extinguished.");
Server.itemHandler.createGroundItem(c, 592, x, y, 1, c.playerId);
}
}, 45);
this.lastLight = System.currentTimeMillis();
//c.getPA().frame1();
//resetAnim = true;
c.startAnimation(65535);
}
}
}
}
}
| 3,053 | 0.617098 | 0.580085 | 112 | 26.267857 | 23.431505 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.973214 | false | false |
3
|
00bafe77f1b24700a5aeebc006de58f8f7bd440e
| 17,068,200,045,244 |
1f7d5e03ff49de78774dbadc57cdcfd13a2478c3
|
/app/src/main/java/corelyzer/data/lims/LIMSImageryDirectory.java
|
da50a277f1d4e208976c610305a23c5b6e880ef1
|
[] |
no_license
|
corewall/corelyzer
|
https://github.com/corewall/corelyzer
|
e04aa9c4c00292f8b2bc76754fb8e96398930633
|
190af643ea00c827b7b0b49e24d156a81eb07368
|
refs/heads/master
| 2023-08-31T17:46:36.461000 | 2023-08-17T19:10:53 | 2023-08-17T19:10:53 | 910,138 | 17 | 7 | null | false | 2020-11-26T00:20:42 | 2010-09-14T15:03:04 | 2020-11-10T23:16:37 | 2020-11-26T00:20:41 | 92,757 | 12 | 6 | 11 |
C
| false | false |
/******************************************************************************
*
* CoreWall / Corelyzer - An Initial Core Description Tool
* Copyright (C) 2008 Julian Yu-Chung Chen
* Electronic Visualization Laboratory, University of Illinois at Chicago
*
* This software is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either Version 2.1 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser Public License along
* with this software; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Questions or comments about CoreWall should be directed to
* cavern@evl.uic.edu
*
*****************************************************************************/
package corelyzer.data.lims;
import java.awt.Window;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import corelyzer.util.StringUtility;
public class LIMSImageryDirectory {
// Default values
public final static float DEFAULT_DPI = 254.0f;
public final static float DEFAULT_DEPTH = 0.0f;
public final static float DEFAULT_LENGTH = 1.0f;
// Section table column indices
static String[] mapping = { "Leg", "Site", "Hole", "Core", "Type", "Section", "TopOffset (m)", "BottomOffset (m)", "Depth (m)", "Length", "DPI", "URL" };
final static int LEG_INDEX = 0;
final static int SITE_INDEX = 1;
final static int HOLE_INDEX = 2;
final static int CORE_INDEX = 3;
final static int TYPE_INDEX = 4;
final static int SECTION_INDEX = 5;
final static int TOPOFFSET_INDEX = 6;
final static int BOTTOMOFFSET_INDEX = 7;
final static int DEPTH_INDEX = 8;
final static int LENGTH_INDEX = 9;
final static int DPI_INDEX = 10;
final static int URL_INDEX = 11;
// Affine table entries
final static String[] affineTableMapping = { "Leg", "Site", "Hole", "Core", "Type", "Shift (m)", "Apply only?" };
final static int OFFSET_INDEX = 5;
final static int APPLY_INDEX = 6;
// Splice table entries
final static String[] spliceTableMapping = { "Leg1", "Site1", "Hole1", "Core1", "Type1", "Section1", "Top1", "Bottom1", "mbsf1", "mcd1", "TIE/APPEND",
"Leg2", "Site2", "Hole2", "Core2", "Type2", "Section2", "Top2", "Bottom2", "mbsf2", "mcd2" };
final static int LEG1_INDEX = 0;
final static int SITE1_INDEX = 1;
final static int HOLE1_INDEX = 2;
final static int CORE1_INDEX = 3;
final static int TYPE1_INDEX = 4;
final static int SECT1_INDEX = 5;
final static int TOP1_INDEX = 6;
final static int BTM1_INDEX = 7;
final static int MBSF1_INDEX = 8;
final static int MCD1_INDEX = 9;
final static int OP_INDEX = 10;
final static int LEG2_INDEX = 11;
final static int SITE2_INDEX = 12;
final static int HOLE2_INDEX = 13;
final static int CORE2_INDEX = 14;
final static int TYPE2_INDEX = 15;
final static int SECT2_INDEX = 16;
final static int TOP2_INDEX = 17;
final static int BTM2_INDEX = 18;
final static int MBSF2_INDEX = 19;
final static int MCD2_INDEX = 20;
static LIMSImageryDirectory directory;
public static LIMSImageryDirectory getDirectory() {
if (directory == null) {
directory = new LIMSImageryDirectory();
}
return directory;
}
public static String getImageName(final String leg, final String site, final String hole, final String core, final String type, final String section) {
return site + hole.toLowerCase() + "_" + StringUtility.expandNums(core, 3) + type.toLowerCase() + "_" + StringUtility.expandNums(section, 2);
}
// Could be better DS
// section list table
Vector<String[]> allSections;
String sectionListFileStr;
// affine table
Vector<String[]> affineTable;
// splice table
Vector<String[]> spliceTable;
public LIMSImageryDirectory() {
super();
allSections = new Vector<String[]>();
affineTable = new Vector<String[]>();
spliceTable = new Vector<String[]>();
directory = this;
}
public void addChronosOnlyTokensToSectionTable(final String[] toks) {
allSections.add(toks);
}
// leg site hole core sectionNumber sectionID sectionType coreType
// curatedLength linearLength
// MBSF FORMAT DPI imageURL
public void addChronosTokensToSectionTable(final String[] toks) {
String[] inputTks = { toks[0].trim(), toks[1].trim(), toks[2].trim(), toks[3].trim(), toks[7].trim(), toks[4].trim(), "0.0", "0.0", toks[10].trim(),
toks[9].trim(), toks[12].trim(), toks[13].trim() };
allSections.add(inputTks);
}
// leg site hole core coreType Section TopOffset BottomOffset Depth Length
// cropped_asman_id
private void addLIMSTokensToSectionTable(final String[] toks) {
// hack to allow SPACE in URL string
String urlString = "";
for (int i = 10; i < toks.length; i++) {
String space = i > 10 ? " " : "";
urlString = urlString + space + toks[i];
}
String[] inputTks = { toks[0].trim(), toks[1].trim(), toks[2].trim(), toks[3].trim(), toks[4].trim(), toks[5].trim(), toks[6].trim(), toks[7].trim(),
toks[8].trim(), toks[9].trim(), "0.0", urlString };
allSections.add(inputTks);
}
public void clearAffineTable() {
if (affineTable != null) {
affineTable.clear();
}
}
public void clearSectionList() {
if (allSections != null) {
allSections.clear();
}
}
public void clearSpliceTable() {
if (spliceTable != null) {
spliceTable.clear();
}
}
public String[] findNextCoreInATie(final String leg, final String site, final String hole, final String core, final String section) {
String[] ret = null;
for (int i = 0; i < getNumberOfSpliceTableEntries(); i++) {
if (getSpliceTableCell(i, OP_INDEX).equalsIgnoreCase("tie") && getSpliceTableCell(i, LEG1_INDEX).equalsIgnoreCase(leg.toLowerCase())
&& getSpliceTableCell(i, SITE1_INDEX).equalsIgnoreCase(site.toLowerCase())
&& getSpliceTableCell(i, HOLE1_INDEX).equalsIgnoreCase(hole.toLowerCase())
&& getSpliceTableCell(i, CORE1_INDEX).equalsIgnoreCase(core.toLowerCase())
&& getSpliceTableCell(i, SECT1_INDEX).equalsIgnoreCase(section.toLowerCase())) {
ret = new String[2];
ret[0] = getSpliceTableCell(i, HOLE2_INDEX);
ret[1] = getSpliceTableCell(i, CORE2_INDEX);
break;
}
}
return ret;
}
public String getAffineTableCell(final int row, final int col) {
String[] toks = affineTable.elementAt(row);
if (toks == null) {
return null;
}
if (toks[col] != null) {
return toks[col].trim();
} else {
return null;
}
}
public String getAffineTableFieldName(final int col) {
if ((col >= 0) && (col < affineTableMapping.length)) {
return affineTableMapping[col];
} else {
return "N/A";
}
}
public float getAffineTableShift(final String leg, final String site, final String hole, final String core) {
String ret = "0.0";
String type = getCoreType(leg, site, hole, core);
if (type != null) {
for (String[] line : affineTable) {
if (line.length >= 7) { // leg, site, hole, core, type, shift,
// apply?
if (leg.equalsIgnoreCase(line[0].trim()) && site.equalsIgnoreCase(line[1].trim()) && hole.equalsIgnoreCase(line[2].trim())
&& core.equalsIgnoreCase(line[3].trim()) && type.equalsIgnoreCase(line[4].trim())) {
ret = line[5].trim();
} else {
}
} else {
}
}
}
float v = 0.0f;
try {
v = Float.parseFloat(ret);
} catch (NumberFormatException e) {
v = 0.0f;
}
return v;
}
public String getCell(final int row, final int column) {
String[] toks = allSections.elementAt(row);
return toks[column];
}
public String[] getCoreInfo(final String leg, final String site, final String hole, final String core) {
return getCoreInfo(leg, site, hole, core, "-999");
}
public String[] getCoreInfo(final String leg, final String site, final String hole, final String core, final String startDepthString) {
String[] ret = { "NA", "0", "0", "0" }; // type, 1st section ID, last
// section ID, sectionID at
// 'startDepth'
String type = getCoreType(leg, site, hole, core);
ret[0] = type;
int min = 0;
int max = 0;
int start = 0;
String[] sections = getSectionInACore(leg, site, hole, core, type);
float startDepth = Float.valueOf(startDepthString);
for (int i = 0; i < sections.length; i++) {
String section = sections[i];
if (section.equalsIgnoreCase("cc")) {
continue; // ignore core catcher
}
int id = Integer.parseInt(section);
// Begin & end section IDs of the core
if (i == 0) {
min = id;
max = id;
start = id;
}
if (id >= max) {
max = id;
}
if (id <= min) {
min = id;
}
// Determine which section the 'startDepth' belongs to
float depth = getSectionMCDDepth(leg, site, hole, core, type, section);
float length = getSectionLength(leg, site, hole, core, type, section);
if ((startDepth >= depth) && (startDepth < depth + length)) {
start = id;
}
}
ret[1] = String.valueOf(min);
ret[2] = String.valueOf(max);
ret[3] = String.valueOf(start);
return ret;
}
public String[] getCoresInAHoleBelowDepth(final String leg, final String site, final String hole, final float depth) {
Vector<String> coresBelow = new Vector<String>();
for (String[] row : allSections) {
if (row[LEG_INDEX].trim().equalsIgnoreCase(leg) && row[SITE_INDEX].trim().equalsIgnoreCase(site) && row[HOLE_INDEX].trim().equalsIgnoreCase(hole)
&& row[SECTION_INDEX].trim().equals("1")) {
String core = row[CORE_INDEX].trim();
String type = row[TYPE_INDEX].trim();
float topCoreDepth = getSectionDepth(leg, site, hole, core, type, "1");
if (topCoreDepth > depth) {
coresBelow.add(row[CORE_INDEX]);
}
}
}
Vector<String> uniq = unique(coresBelow);
return uniq.toArray(new String[uniq.size()]);
}
public String getCoreType(final String leg, final String site, final String hole, final String core) {
for (String[] row : allSections) {
if (row[LEG_INDEX].trim().equalsIgnoreCase(leg) && row[SITE_INDEX].trim().equalsIgnoreCase(site) && row[HOLE_INDEX].trim().equalsIgnoreCase(hole)
&& row[CORE_INDEX].trim().equals(core)) {
return row[TYPE_INDEX].trim();
}
}
return null;
}
public String getFieldName(final int col) {
return mapping[col];
}
public int getNumberOfAffineTableColumns() {
return affineTableMapping.length;
}
// affine table accessors
public int getNumberOfAffineTableEntries() {
return affineTable.size();
}
public int getNumberOfFields() {
return mapping.length;
}
public int getNumberOfSections() {
return allSections.size();
}
public int getNumberOfSpliceTableColumns() {
return spliceTableMapping.length;
}
// splice table accessors
public int getNumberOfSpliceTableEntries() {
return spliceTable.size();
}
public float getSectionDepth(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks[LEG_INDEX].equalsIgnoreCase(leg) && toks[SITE_INDEX].equalsIgnoreCase(site) && toks[HOLE_INDEX].equalsIgnoreCase(hole)
&& toks[CORE_INDEX].equalsIgnoreCase(core) && toks[TYPE_INDEX].equalsIgnoreCase(type) && toks[SECTION_INDEX].equalsIgnoreCase(section)) {
try {
return Float.parseFloat(toks[DEPTH_INDEX]);
} catch (NumberFormatException e) {
return DEFAULT_DEPTH;
}
}
}
return DEFAULT_DEPTH;
}
public float getSectionDPI(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks != null) {
if (toks[LEG_INDEX].equals(leg) && toks[SITE_INDEX].equals(site) && toks[HOLE_INDEX].equals(hole) && toks[CORE_INDEX].equals(core)
&& toks[TYPE_INDEX].equals(type) && toks[SECTION_INDEX].equals(section)) {
float dpi;
try {
dpi = Float.valueOf(toks[DPI_INDEX].trim());
} catch (Exception e) { // arrayindexOBex or numberformatex
dpi = 0.0f;
}
return dpi;
}
}
}
return 0.0f;
}
public String[] getSectionInACore(final String leg, final String site, final String hole, final String core, final String type) {
Vector<String> sections = new Vector<String>();
for (String[] row : allSections) {
if (row[LEG_INDEX].trim().equalsIgnoreCase(leg) && row[SITE_INDEX].trim().equalsIgnoreCase(site) && row[HOLE_INDEX].trim().equalsIgnoreCase(hole)
&& row[CORE_INDEX].trim().equalsIgnoreCase(core) && row[TYPE_INDEX].trim().equalsIgnoreCase(type)) {
sections.add(row[SECTION_INDEX]);
}
}
return sections.toArray(new String[sections.size()]);
}
public String getSectionInfoString(final String leg, final String site, final String hole, final String core, final String type, final String section) {
return "Leg: " + leg + ", site: " + site + ", hole: " + hole + ", core: " + core + ", type: " + type + ", section: " + section;
}
public float getSectionLength(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks != null) {
if (toks[LEG_INDEX].equals(leg) && toks[SITE_INDEX].equals(site) && toks[HOLE_INDEX].equals(hole) && toks[CORE_INDEX].equals(core)
&& toks[TYPE_INDEX].equals(type) && toks[SECTION_INDEX].equals(section)) {
float length;
try {
length = Float.valueOf(toks[LENGTH_INDEX].trim());
} catch (Exception e) { // arrayindexOBex or numberformatex
length = DEFAULT_LENGTH;
}
return length;
}
}
}
return DEFAULT_LENGTH;
}
public String getSectionListFileStr() {
return sectionListFileStr;
}
public float getSectionMCDDepth(final String leg, final String site, final String hole, final String core, final String type, final String section) {
float depth = 0.0f;
// Get mbsf
for (String[] toks : allSections) {
if (toks[LEG_INDEX].equalsIgnoreCase(leg) && toks[SITE_INDEX].equalsIgnoreCase(site) && toks[HOLE_INDEX].equalsIgnoreCase(hole)
&& toks[CORE_INDEX].equalsIgnoreCase(core) && toks[TYPE_INDEX].equalsIgnoreCase(type) && toks[SECTION_INDEX].equalsIgnoreCase(section)) {
try {
depth = Float.parseFloat(toks[DEPTH_INDEX]);
} catch (NumberFormatException e) {
depth = DEFAULT_DEPTH;
}
}
}
float affineShift = getAffineTableShift(leg, site, hole, core);
return depth + affineShift;
}
public String getSectionURL(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks[LEG_INDEX].equals(leg) && toks[SITE_INDEX].equals(site) && toks[HOLE_INDEX].equals(hole) && toks[CORE_INDEX].equals(core)
&& toks[TYPE_INDEX].equals(type) && toks[SECTION_INDEX].equals(section)) {
// String mesg = "[] "
// + getSectionInfoString(leg, site, hole, core, type, section)
// + " has url: " + toks[URL_INDEX];
// System.out.println(mesg);
return toks[URL_INDEX];
}
}
return null;
}
public String getSpliceTableCell(final int row, final int col) {
String[] toks = spliceTable.elementAt(row);
if (toks == null) {
return null;
}
if (toks[col] != null) {
return toks[col].trim();
} else {
return null;
}
}
public String getSpliceTableFieldName(final int col) {
if ((col >= 0) && (col < spliceTableMapping.length)) {
return spliceTableMapping[col];
} else {
return "N/A";
}
}
public void loadImagesTableFiles(final Window parent, final String[] fileStrs) {
if (fileStrs != null) {
for (String str : fileStrs) {
boolean isLoaded = loadImageTable(str);
if (!isLoaded) {
JOptionPane.showMessageDialog(parent, "Unknown format: '" + str + "'");
}
}
}
}
private boolean loadImageTable(final String fileStr) {
File f = new File(fileStr);
if (!f.exists()) {
System.out.println("[LIMSDir] '" + f + "' does not exist, ignore.");
return false;
}
System.out.println("- Loading listing file: '" + fileStr + "'");
sectionListFileStr = fileStr;
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
// ignore 1st line header/labels
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
// Identify format and length of token array
// LIMS: 11 tokens separated with SPACE
// leg site hole core coreType Section TopOffset BottomOffset
// Depth Length cropped_asman_id
// Chronos: 14 tokens separated with TAB
// leg site hole core sectionNumber sectionID sectionType
// coreType curatedLength linearLength
// MBSF FORMAT DPI imageURL
String[] spaceTks = line.split(" ");
String[] tabTks = line.split("\t");
if (spaceTks.length >= 11) {
addLIMSTokensToSectionTable(spaceTks);
} else if (tabTks.length == 14) {
addChronosTokensToSectionTable(tabTks);
} else {
// ignore
return false;
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public void loadPlainTextAffineTable(final File f) {
if (!f.exists()) {
return;
}
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String line;
String[] toks;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
toks = line.split("\t");
affineTable.add(toks);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// need "leg" parameter because the plain text splice file doesn't have
// leg column
public void loadPlainTextSpliceTableFile(final File f, final String leg) {
if (!f.exists()) {
System.out.println("[LIMSDir] Splice table file '" + f + "' does not exist, ignore.");
return;
}
System.out.println("- Loading splice table file: '" + f.getAbsolutePath() + "'");
spliceTable.clear();
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String line;
String[] toks;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
toks = line.split("\t");
if (leg != null) {
String[] new_toks = new String[spliceTableMapping.length];
new_toks[0] = leg;
if (toks.length >= 10) {
System.arraycopy(toks, 0, new_toks, 1, 10);
if (toks.length > 10) {
System.arraycopy(toks, 10, new_toks, 12, 9);
new_toks[11] = leg;
}
} else {
System.arraycopy(toks, 0, new_toks, 1, toks.length);
}
spliceTable.add(new_toks);
} else {
spliceTable.add(toks);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "ConstantConditions" })
public boolean loadXMLAffineTable(final File f) {
if (!f.exists()) {
return false;
}
try {
DOMParser parser = new DOMParser();
parser.setFeature("http://apache.org/xml/features/dom/" + "include-ignorable-whitespace", false);
parser.parse(f.toURI().toURL().toString());
Document doc = parser.getDocument();
Element e = doc.getDocumentElement(); // <Correlator>
NodeList dataList = e.getChildNodes();
for (int i = 0; i < dataList.getLength(); i++) {
if (!(dataList.item(i) instanceof Element)) {
continue;
}
Element dataElement = (Element) dataList.item(i);
String dataType = dataElement.getAttribute("affine table");
if (!dataType.equalsIgnoreCase("affine table")) {
continue;
}
String leg = dataElement.getAttribute("leg");
String site = dataElement.getAttribute("site");
NodeList holeList = dataElement.getChildNodes();
for (int j = 0; j < holeList.getLength(); j++) {
if (!(holeList.item(j) instanceof Element)) {
continue;
}
Element holeElement = (Element) holeList.item(j);
String hole = holeElement.getAttribute("value");
NodeList coreList = holeElement.getChildNodes();
for (int k = 0; k < coreList.getLength(); k++) {
if (!(coreList.item(k) instanceof Element)) {
continue;
}
Element coreElement = (Element) coreList.item(k);
String core = coreElement.getAttribute("id");
String type = coreElement.getAttribute("type");
String applied = coreElement.getAttribute("applied");
String offset = coreElement.getAttribute("offset");
// add to local affine table
String[] row = { leg, site, hole, core, type, offset, applied };
affineTable.add(row);
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@SuppressWarnings({ "ConstantConditions" })
public boolean loadXMLSpliceTableFile(final File f) {
if (!f.exists()) {
return false;
}
try {
DOMParser parser = new DOMParser();
parser.setFeature("http://apache.org/xml/features/dom/" + "include-ignorable-whitespace", false);
parser.parse(f.toURI().toURL().toString());
Document doc = parser.getDocument();
Element e = doc.getDocumentElement(); // <Correlator>
NodeList dataList = e.getChildNodes();
for (int i = 0; i < dataList.getLength(); i++) {
if (!(dataList.item(i) instanceof Element)) {
continue;
}
Element dataElement = (Element) dataList.item(i);
String dataType = dataElement.getAttribute("type");
if (!dataType.equalsIgnoreCase("splice table")) {
continue;
}
String leg = dataElement.getAttribute("leg");
String site = dataElement.getAttribute("site");
NodeList tieList = dataElement.getChildNodes();
for (int j = 0; j < tieList.getLength(); j++) {
if (!(tieList.item(j) instanceof Element)) {
continue;
}
Element tieElement = (Element) tieList.item(j);
Vector<String> row = new Vector<String>();
NodeList coreList = tieElement.getChildNodes();
for (int k = 0; k < coreList.getLength(); k++) {
if (!(coreList.item(k) instanceof Element)) {
continue;
}
Element coreElement = (Element) coreList.item(k);
String core = coreElement.getAttribute("id");
String hole = coreElement.getAttribute("hole");
String type = coreElement.getAttribute("type");
String section = coreElement.getAttribute("section");
String top = coreElement.getAttribute("top");
String bottom = coreElement.getAttribute("bottom");
String mbsf = coreElement.getAttribute("mbsf");
String mcd = coreElement.getAttribute("mcd");
String tietype = coreElement.getAttribute("tietype");
if ((tietype == null) || tietype.equals("")) {
row.clear();
row.add(leg);
row.add(site);
row.add(hole);
row.add(core);
row.add(type);
row.add(section);
row.add(top);
row.add(bottom);
row.add(mbsf);
row.add(mcd);
} else {
if (tietype.toLowerCase().startsWith("tie")) {
row.add("TIE");
} else {
row.add(tietype.toUpperCase());
}
if ((core == null) || core.equals("")) {
row.add(""); // leg
row.add(""); // site
} else {
row.add(leg);
row.add(site);
}
row.add(hole);
row.add(core);
row.add(type);
row.add(section);
row.add(top);
row.add(bottom);
row.add(mbsf);
row.add(mcd);
String[] rowArray = row.toArray(new String[row.size()]);
spliceTable.add(rowArray);
row.clear();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void setSectionListFileStr(final String sectionListFileStr) {
this.sectionListFileStr = sectionListFileStr;
}
private Vector<String> unique(final Vector<String> v) {
Vector<String> tmpVector = new Vector<String>();
if (v.isEmpty()) {
return v;
}
for (int i = 0; i < v.size(); i++) {
String tmpValue = v.elementAt(i);
if (tmpValue != null) {
if (tmpVector.isEmpty()) {
tmpVector.addElement(tmpValue);
}
if (tmpVector.indexOf(tmpValue) == -1) {
tmpVector.addElement(tmpValue);
}
}
}
return tmpVector;
}
}
|
UTF-8
|
Java
| 24,716 |
java
|
LIMSImageryDirectory.java
|
Java
|
[
{
"context": "nitial Core Description Tool\n * Copyright (C) 2008 Julian Yu-Chung Chen\n * Electronic Visualization Laboratory, Universit",
"end": 184,
"score": 0.9846309423446655,
"start": 164,
"tag": "NAME",
"value": "Julian Yu-Chung Chen"
},
{
"context": "r comments about CoreWall should be directed to\n * cavern@evl.uic.edu\n *\n *********************************************",
"end": 1076,
"score": 0.9999315142631531,
"start": 1058,
"tag": "EMAIL",
"value": "cavern@evl.uic.edu"
}
] | null |
[] |
/******************************************************************************
*
* CoreWall / Corelyzer - An Initial Core Description Tool
* Copyright (C) 2008 <NAME>
* Electronic Visualization Laboratory, University of Illinois at Chicago
*
* This software is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either Version 2.1 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser Public License along
* with this software; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Questions or comments about CoreWall should be directed to
* <EMAIL>
*
*****************************************************************************/
package corelyzer.data.lims;
import java.awt.Window;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import corelyzer.util.StringUtility;
public class LIMSImageryDirectory {
// Default values
public final static float DEFAULT_DPI = 254.0f;
public final static float DEFAULT_DEPTH = 0.0f;
public final static float DEFAULT_LENGTH = 1.0f;
// Section table column indices
static String[] mapping = { "Leg", "Site", "Hole", "Core", "Type", "Section", "TopOffset (m)", "BottomOffset (m)", "Depth (m)", "Length", "DPI", "URL" };
final static int LEG_INDEX = 0;
final static int SITE_INDEX = 1;
final static int HOLE_INDEX = 2;
final static int CORE_INDEX = 3;
final static int TYPE_INDEX = 4;
final static int SECTION_INDEX = 5;
final static int TOPOFFSET_INDEX = 6;
final static int BOTTOMOFFSET_INDEX = 7;
final static int DEPTH_INDEX = 8;
final static int LENGTH_INDEX = 9;
final static int DPI_INDEX = 10;
final static int URL_INDEX = 11;
// Affine table entries
final static String[] affineTableMapping = { "Leg", "Site", "Hole", "Core", "Type", "Shift (m)", "Apply only?" };
final static int OFFSET_INDEX = 5;
final static int APPLY_INDEX = 6;
// Splice table entries
final static String[] spliceTableMapping = { "Leg1", "Site1", "Hole1", "Core1", "Type1", "Section1", "Top1", "Bottom1", "mbsf1", "mcd1", "TIE/APPEND",
"Leg2", "Site2", "Hole2", "Core2", "Type2", "Section2", "Top2", "Bottom2", "mbsf2", "mcd2" };
final static int LEG1_INDEX = 0;
final static int SITE1_INDEX = 1;
final static int HOLE1_INDEX = 2;
final static int CORE1_INDEX = 3;
final static int TYPE1_INDEX = 4;
final static int SECT1_INDEX = 5;
final static int TOP1_INDEX = 6;
final static int BTM1_INDEX = 7;
final static int MBSF1_INDEX = 8;
final static int MCD1_INDEX = 9;
final static int OP_INDEX = 10;
final static int LEG2_INDEX = 11;
final static int SITE2_INDEX = 12;
final static int HOLE2_INDEX = 13;
final static int CORE2_INDEX = 14;
final static int TYPE2_INDEX = 15;
final static int SECT2_INDEX = 16;
final static int TOP2_INDEX = 17;
final static int BTM2_INDEX = 18;
final static int MBSF2_INDEX = 19;
final static int MCD2_INDEX = 20;
static LIMSImageryDirectory directory;
public static LIMSImageryDirectory getDirectory() {
if (directory == null) {
directory = new LIMSImageryDirectory();
}
return directory;
}
public static String getImageName(final String leg, final String site, final String hole, final String core, final String type, final String section) {
return site + hole.toLowerCase() + "_" + StringUtility.expandNums(core, 3) + type.toLowerCase() + "_" + StringUtility.expandNums(section, 2);
}
// Could be better DS
// section list table
Vector<String[]> allSections;
String sectionListFileStr;
// affine table
Vector<String[]> affineTable;
// splice table
Vector<String[]> spliceTable;
public LIMSImageryDirectory() {
super();
allSections = new Vector<String[]>();
affineTable = new Vector<String[]>();
spliceTable = new Vector<String[]>();
directory = this;
}
public void addChronosOnlyTokensToSectionTable(final String[] toks) {
allSections.add(toks);
}
// leg site hole core sectionNumber sectionID sectionType coreType
// curatedLength linearLength
// MBSF FORMAT DPI imageURL
public void addChronosTokensToSectionTable(final String[] toks) {
String[] inputTks = { toks[0].trim(), toks[1].trim(), toks[2].trim(), toks[3].trim(), toks[7].trim(), toks[4].trim(), "0.0", "0.0", toks[10].trim(),
toks[9].trim(), toks[12].trim(), toks[13].trim() };
allSections.add(inputTks);
}
// leg site hole core coreType Section TopOffset BottomOffset Depth Length
// cropped_asman_id
private void addLIMSTokensToSectionTable(final String[] toks) {
// hack to allow SPACE in URL string
String urlString = "";
for (int i = 10; i < toks.length; i++) {
String space = i > 10 ? " " : "";
urlString = urlString + space + toks[i];
}
String[] inputTks = { toks[0].trim(), toks[1].trim(), toks[2].trim(), toks[3].trim(), toks[4].trim(), toks[5].trim(), toks[6].trim(), toks[7].trim(),
toks[8].trim(), toks[9].trim(), "0.0", urlString };
allSections.add(inputTks);
}
public void clearAffineTable() {
if (affineTable != null) {
affineTable.clear();
}
}
public void clearSectionList() {
if (allSections != null) {
allSections.clear();
}
}
public void clearSpliceTable() {
if (spliceTable != null) {
spliceTable.clear();
}
}
public String[] findNextCoreInATie(final String leg, final String site, final String hole, final String core, final String section) {
String[] ret = null;
for (int i = 0; i < getNumberOfSpliceTableEntries(); i++) {
if (getSpliceTableCell(i, OP_INDEX).equalsIgnoreCase("tie") && getSpliceTableCell(i, LEG1_INDEX).equalsIgnoreCase(leg.toLowerCase())
&& getSpliceTableCell(i, SITE1_INDEX).equalsIgnoreCase(site.toLowerCase())
&& getSpliceTableCell(i, HOLE1_INDEX).equalsIgnoreCase(hole.toLowerCase())
&& getSpliceTableCell(i, CORE1_INDEX).equalsIgnoreCase(core.toLowerCase())
&& getSpliceTableCell(i, SECT1_INDEX).equalsIgnoreCase(section.toLowerCase())) {
ret = new String[2];
ret[0] = getSpliceTableCell(i, HOLE2_INDEX);
ret[1] = getSpliceTableCell(i, CORE2_INDEX);
break;
}
}
return ret;
}
public String getAffineTableCell(final int row, final int col) {
String[] toks = affineTable.elementAt(row);
if (toks == null) {
return null;
}
if (toks[col] != null) {
return toks[col].trim();
} else {
return null;
}
}
public String getAffineTableFieldName(final int col) {
if ((col >= 0) && (col < affineTableMapping.length)) {
return affineTableMapping[col];
} else {
return "N/A";
}
}
public float getAffineTableShift(final String leg, final String site, final String hole, final String core) {
String ret = "0.0";
String type = getCoreType(leg, site, hole, core);
if (type != null) {
for (String[] line : affineTable) {
if (line.length >= 7) { // leg, site, hole, core, type, shift,
// apply?
if (leg.equalsIgnoreCase(line[0].trim()) && site.equalsIgnoreCase(line[1].trim()) && hole.equalsIgnoreCase(line[2].trim())
&& core.equalsIgnoreCase(line[3].trim()) && type.equalsIgnoreCase(line[4].trim())) {
ret = line[5].trim();
} else {
}
} else {
}
}
}
float v = 0.0f;
try {
v = Float.parseFloat(ret);
} catch (NumberFormatException e) {
v = 0.0f;
}
return v;
}
public String getCell(final int row, final int column) {
String[] toks = allSections.elementAt(row);
return toks[column];
}
public String[] getCoreInfo(final String leg, final String site, final String hole, final String core) {
return getCoreInfo(leg, site, hole, core, "-999");
}
public String[] getCoreInfo(final String leg, final String site, final String hole, final String core, final String startDepthString) {
String[] ret = { "NA", "0", "0", "0" }; // type, 1st section ID, last
// section ID, sectionID at
// 'startDepth'
String type = getCoreType(leg, site, hole, core);
ret[0] = type;
int min = 0;
int max = 0;
int start = 0;
String[] sections = getSectionInACore(leg, site, hole, core, type);
float startDepth = Float.valueOf(startDepthString);
for (int i = 0; i < sections.length; i++) {
String section = sections[i];
if (section.equalsIgnoreCase("cc")) {
continue; // ignore core catcher
}
int id = Integer.parseInt(section);
// Begin & end section IDs of the core
if (i == 0) {
min = id;
max = id;
start = id;
}
if (id >= max) {
max = id;
}
if (id <= min) {
min = id;
}
// Determine which section the 'startDepth' belongs to
float depth = getSectionMCDDepth(leg, site, hole, core, type, section);
float length = getSectionLength(leg, site, hole, core, type, section);
if ((startDepth >= depth) && (startDepth < depth + length)) {
start = id;
}
}
ret[1] = String.valueOf(min);
ret[2] = String.valueOf(max);
ret[3] = String.valueOf(start);
return ret;
}
public String[] getCoresInAHoleBelowDepth(final String leg, final String site, final String hole, final float depth) {
Vector<String> coresBelow = new Vector<String>();
for (String[] row : allSections) {
if (row[LEG_INDEX].trim().equalsIgnoreCase(leg) && row[SITE_INDEX].trim().equalsIgnoreCase(site) && row[HOLE_INDEX].trim().equalsIgnoreCase(hole)
&& row[SECTION_INDEX].trim().equals("1")) {
String core = row[CORE_INDEX].trim();
String type = row[TYPE_INDEX].trim();
float topCoreDepth = getSectionDepth(leg, site, hole, core, type, "1");
if (topCoreDepth > depth) {
coresBelow.add(row[CORE_INDEX]);
}
}
}
Vector<String> uniq = unique(coresBelow);
return uniq.toArray(new String[uniq.size()]);
}
public String getCoreType(final String leg, final String site, final String hole, final String core) {
for (String[] row : allSections) {
if (row[LEG_INDEX].trim().equalsIgnoreCase(leg) && row[SITE_INDEX].trim().equalsIgnoreCase(site) && row[HOLE_INDEX].trim().equalsIgnoreCase(hole)
&& row[CORE_INDEX].trim().equals(core)) {
return row[TYPE_INDEX].trim();
}
}
return null;
}
public String getFieldName(final int col) {
return mapping[col];
}
public int getNumberOfAffineTableColumns() {
return affineTableMapping.length;
}
// affine table accessors
public int getNumberOfAffineTableEntries() {
return affineTable.size();
}
public int getNumberOfFields() {
return mapping.length;
}
public int getNumberOfSections() {
return allSections.size();
}
public int getNumberOfSpliceTableColumns() {
return spliceTableMapping.length;
}
// splice table accessors
public int getNumberOfSpliceTableEntries() {
return spliceTable.size();
}
public float getSectionDepth(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks[LEG_INDEX].equalsIgnoreCase(leg) && toks[SITE_INDEX].equalsIgnoreCase(site) && toks[HOLE_INDEX].equalsIgnoreCase(hole)
&& toks[CORE_INDEX].equalsIgnoreCase(core) && toks[TYPE_INDEX].equalsIgnoreCase(type) && toks[SECTION_INDEX].equalsIgnoreCase(section)) {
try {
return Float.parseFloat(toks[DEPTH_INDEX]);
} catch (NumberFormatException e) {
return DEFAULT_DEPTH;
}
}
}
return DEFAULT_DEPTH;
}
public float getSectionDPI(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks != null) {
if (toks[LEG_INDEX].equals(leg) && toks[SITE_INDEX].equals(site) && toks[HOLE_INDEX].equals(hole) && toks[CORE_INDEX].equals(core)
&& toks[TYPE_INDEX].equals(type) && toks[SECTION_INDEX].equals(section)) {
float dpi;
try {
dpi = Float.valueOf(toks[DPI_INDEX].trim());
} catch (Exception e) { // arrayindexOBex or numberformatex
dpi = 0.0f;
}
return dpi;
}
}
}
return 0.0f;
}
public String[] getSectionInACore(final String leg, final String site, final String hole, final String core, final String type) {
Vector<String> sections = new Vector<String>();
for (String[] row : allSections) {
if (row[LEG_INDEX].trim().equalsIgnoreCase(leg) && row[SITE_INDEX].trim().equalsIgnoreCase(site) && row[HOLE_INDEX].trim().equalsIgnoreCase(hole)
&& row[CORE_INDEX].trim().equalsIgnoreCase(core) && row[TYPE_INDEX].trim().equalsIgnoreCase(type)) {
sections.add(row[SECTION_INDEX]);
}
}
return sections.toArray(new String[sections.size()]);
}
public String getSectionInfoString(final String leg, final String site, final String hole, final String core, final String type, final String section) {
return "Leg: " + leg + ", site: " + site + ", hole: " + hole + ", core: " + core + ", type: " + type + ", section: " + section;
}
public float getSectionLength(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks != null) {
if (toks[LEG_INDEX].equals(leg) && toks[SITE_INDEX].equals(site) && toks[HOLE_INDEX].equals(hole) && toks[CORE_INDEX].equals(core)
&& toks[TYPE_INDEX].equals(type) && toks[SECTION_INDEX].equals(section)) {
float length;
try {
length = Float.valueOf(toks[LENGTH_INDEX].trim());
} catch (Exception e) { // arrayindexOBex or numberformatex
length = DEFAULT_LENGTH;
}
return length;
}
}
}
return DEFAULT_LENGTH;
}
public String getSectionListFileStr() {
return sectionListFileStr;
}
public float getSectionMCDDepth(final String leg, final String site, final String hole, final String core, final String type, final String section) {
float depth = 0.0f;
// Get mbsf
for (String[] toks : allSections) {
if (toks[LEG_INDEX].equalsIgnoreCase(leg) && toks[SITE_INDEX].equalsIgnoreCase(site) && toks[HOLE_INDEX].equalsIgnoreCase(hole)
&& toks[CORE_INDEX].equalsIgnoreCase(core) && toks[TYPE_INDEX].equalsIgnoreCase(type) && toks[SECTION_INDEX].equalsIgnoreCase(section)) {
try {
depth = Float.parseFloat(toks[DEPTH_INDEX]);
} catch (NumberFormatException e) {
depth = DEFAULT_DEPTH;
}
}
}
float affineShift = getAffineTableShift(leg, site, hole, core);
return depth + affineShift;
}
public String getSectionURL(final String leg, final String site, final String hole, final String core, final String type, final String section) {
for (String[] toks : allSections) {
if (toks[LEG_INDEX].equals(leg) && toks[SITE_INDEX].equals(site) && toks[HOLE_INDEX].equals(hole) && toks[CORE_INDEX].equals(core)
&& toks[TYPE_INDEX].equals(type) && toks[SECTION_INDEX].equals(section)) {
// String mesg = "[] "
// + getSectionInfoString(leg, site, hole, core, type, section)
// + " has url: " + toks[URL_INDEX];
// System.out.println(mesg);
return toks[URL_INDEX];
}
}
return null;
}
public String getSpliceTableCell(final int row, final int col) {
String[] toks = spliceTable.elementAt(row);
if (toks == null) {
return null;
}
if (toks[col] != null) {
return toks[col].trim();
} else {
return null;
}
}
public String getSpliceTableFieldName(final int col) {
if ((col >= 0) && (col < spliceTableMapping.length)) {
return spliceTableMapping[col];
} else {
return "N/A";
}
}
public void loadImagesTableFiles(final Window parent, final String[] fileStrs) {
if (fileStrs != null) {
for (String str : fileStrs) {
boolean isLoaded = loadImageTable(str);
if (!isLoaded) {
JOptionPane.showMessageDialog(parent, "Unknown format: '" + str + "'");
}
}
}
}
private boolean loadImageTable(final String fileStr) {
File f = new File(fileStr);
if (!f.exists()) {
System.out.println("[LIMSDir] '" + f + "' does not exist, ignore.");
return false;
}
System.out.println("- Loading listing file: '" + fileStr + "'");
sectionListFileStr = fileStr;
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
// ignore 1st line header/labels
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
// Identify format and length of token array
// LIMS: 11 tokens separated with SPACE
// leg site hole core coreType Section TopOffset BottomOffset
// Depth Length cropped_asman_id
// Chronos: 14 tokens separated with TAB
// leg site hole core sectionNumber sectionID sectionType
// coreType curatedLength linearLength
// MBSF FORMAT DPI imageURL
String[] spaceTks = line.split(" ");
String[] tabTks = line.split("\t");
if (spaceTks.length >= 11) {
addLIMSTokensToSectionTable(spaceTks);
} else if (tabTks.length == 14) {
addChronosTokensToSectionTable(tabTks);
} else {
// ignore
return false;
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public void loadPlainTextAffineTable(final File f) {
if (!f.exists()) {
return;
}
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String line;
String[] toks;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
toks = line.split("\t");
affineTable.add(toks);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// need "leg" parameter because the plain text splice file doesn't have
// leg column
public void loadPlainTextSpliceTableFile(final File f, final String leg) {
if (!f.exists()) {
System.out.println("[LIMSDir] Splice table file '" + f + "' does not exist, ignore.");
return;
}
System.out.println("- Loading splice table file: '" + f.getAbsolutePath() + "'");
spliceTable.clear();
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String line;
String[] toks;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
toks = line.split("\t");
if (leg != null) {
String[] new_toks = new String[spliceTableMapping.length];
new_toks[0] = leg;
if (toks.length >= 10) {
System.arraycopy(toks, 0, new_toks, 1, 10);
if (toks.length > 10) {
System.arraycopy(toks, 10, new_toks, 12, 9);
new_toks[11] = leg;
}
} else {
System.arraycopy(toks, 0, new_toks, 1, toks.length);
}
spliceTable.add(new_toks);
} else {
spliceTable.add(toks);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "ConstantConditions" })
public boolean loadXMLAffineTable(final File f) {
if (!f.exists()) {
return false;
}
try {
DOMParser parser = new DOMParser();
parser.setFeature("http://apache.org/xml/features/dom/" + "include-ignorable-whitespace", false);
parser.parse(f.toURI().toURL().toString());
Document doc = parser.getDocument();
Element e = doc.getDocumentElement(); // <Correlator>
NodeList dataList = e.getChildNodes();
for (int i = 0; i < dataList.getLength(); i++) {
if (!(dataList.item(i) instanceof Element)) {
continue;
}
Element dataElement = (Element) dataList.item(i);
String dataType = dataElement.getAttribute("affine table");
if (!dataType.equalsIgnoreCase("affine table")) {
continue;
}
String leg = dataElement.getAttribute("leg");
String site = dataElement.getAttribute("site");
NodeList holeList = dataElement.getChildNodes();
for (int j = 0; j < holeList.getLength(); j++) {
if (!(holeList.item(j) instanceof Element)) {
continue;
}
Element holeElement = (Element) holeList.item(j);
String hole = holeElement.getAttribute("value");
NodeList coreList = holeElement.getChildNodes();
for (int k = 0; k < coreList.getLength(); k++) {
if (!(coreList.item(k) instanceof Element)) {
continue;
}
Element coreElement = (Element) coreList.item(k);
String core = coreElement.getAttribute("id");
String type = coreElement.getAttribute("type");
String applied = coreElement.getAttribute("applied");
String offset = coreElement.getAttribute("offset");
// add to local affine table
String[] row = { leg, site, hole, core, type, offset, applied };
affineTable.add(row);
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@SuppressWarnings({ "ConstantConditions" })
public boolean loadXMLSpliceTableFile(final File f) {
if (!f.exists()) {
return false;
}
try {
DOMParser parser = new DOMParser();
parser.setFeature("http://apache.org/xml/features/dom/" + "include-ignorable-whitespace", false);
parser.parse(f.toURI().toURL().toString());
Document doc = parser.getDocument();
Element e = doc.getDocumentElement(); // <Correlator>
NodeList dataList = e.getChildNodes();
for (int i = 0; i < dataList.getLength(); i++) {
if (!(dataList.item(i) instanceof Element)) {
continue;
}
Element dataElement = (Element) dataList.item(i);
String dataType = dataElement.getAttribute("type");
if (!dataType.equalsIgnoreCase("splice table")) {
continue;
}
String leg = dataElement.getAttribute("leg");
String site = dataElement.getAttribute("site");
NodeList tieList = dataElement.getChildNodes();
for (int j = 0; j < tieList.getLength(); j++) {
if (!(tieList.item(j) instanceof Element)) {
continue;
}
Element tieElement = (Element) tieList.item(j);
Vector<String> row = new Vector<String>();
NodeList coreList = tieElement.getChildNodes();
for (int k = 0; k < coreList.getLength(); k++) {
if (!(coreList.item(k) instanceof Element)) {
continue;
}
Element coreElement = (Element) coreList.item(k);
String core = coreElement.getAttribute("id");
String hole = coreElement.getAttribute("hole");
String type = coreElement.getAttribute("type");
String section = coreElement.getAttribute("section");
String top = coreElement.getAttribute("top");
String bottom = coreElement.getAttribute("bottom");
String mbsf = coreElement.getAttribute("mbsf");
String mcd = coreElement.getAttribute("mcd");
String tietype = coreElement.getAttribute("tietype");
if ((tietype == null) || tietype.equals("")) {
row.clear();
row.add(leg);
row.add(site);
row.add(hole);
row.add(core);
row.add(type);
row.add(section);
row.add(top);
row.add(bottom);
row.add(mbsf);
row.add(mcd);
} else {
if (tietype.toLowerCase().startsWith("tie")) {
row.add("TIE");
} else {
row.add(tietype.toUpperCase());
}
if ((core == null) || core.equals("")) {
row.add(""); // leg
row.add(""); // site
} else {
row.add(leg);
row.add(site);
}
row.add(hole);
row.add(core);
row.add(type);
row.add(section);
row.add(top);
row.add(bottom);
row.add(mbsf);
row.add(mcd);
String[] rowArray = row.toArray(new String[row.size()]);
spliceTable.add(rowArray);
row.clear();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void setSectionListFileStr(final String sectionListFileStr) {
this.sectionListFileStr = sectionListFileStr;
}
private Vector<String> unique(final Vector<String> v) {
Vector<String> tmpVector = new Vector<String>();
if (v.isEmpty()) {
return v;
}
for (int i = 0; i < v.size(); i++) {
String tmpValue = v.elementAt(i);
if (tmpValue != null) {
if (tmpVector.isEmpty()) {
tmpVector.addElement(tmpValue);
}
if (tmpVector.indexOf(tmpValue) == -1) {
tmpVector.addElement(tmpValue);
}
}
}
return tmpVector;
}
}
| 24,691 | 0.647678 | 0.638008 | 853 | 27.975382 | 31.318964 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.021102 | false | false |
3
|
87dc8dc8886a548277243c055edbfd55d214c52d
| 4,020,089,450,321 |
3540f92653a387171829a87f4d71ee5959498de3
|
/src/first_agents/edu/cwru/sepia/agent/MyCombatAgent.java
|
20ae4b1db79ed53f60ab1d32ca9be65018977fef
|
[] |
no_license
|
woodman898/https-csevcs.case.edu-git-2020_spring_391_22
|
https://github.com/woodman898/https-csevcs.case.edu-git-2020_spring_391_22
|
721d7dc505c2f354d34d6044a82b5f91f5e42d0e
|
af073bc9e08c62710d9911f8ce3516f07c0afed1
|
refs/heads/master
| 2020-12-31T23:17:31.708000 | 2020-02-08T21:08:05 | 2020-02-08T21:08:05 | 239,071,415 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package first_agents.edu.cwru.sepia.agent;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cwru.sepia.action.Action;
import edu.cwru.sepia.action.ActionFeedback;
import edu.cwru.sepia.action.ActionResult;
import edu.cwru.sepia.agent.Agent;
import edu.cwru.sepia.environment.model.history.DamageLog;
import edu.cwru.sepia.environment.model.history.History.HistoryView;
import edu.cwru.sepia.environment.model.state.State.StateView;
import edu.cwru.sepia.environment.model.state.Unit.UnitView;
public class MyCombatAgent extends Agent {
private int enemyPlayerNum = 1;
public MyCombatAgent(int playernum, String[] otherargs) {
super(playernum);
if(otherargs.length > 0)
{
enemyPlayerNum = new Integer(otherargs[0]);
}
System.out.println("Constructed MyCombatAgent");
}
@Override
public Map<Integer, Action> initialStep(StateView newstate,
HistoryView statehistory) {
Map<Integer, Action> actions = new HashMap<Integer, Action>();
List<Integer> myUnitIDs = newstate.getUnitIds(playernum);
List<Integer> enemyUnitIDs = newstate.getUnitIds(enemyPlayerNum);
if(enemyUnitIDs.size() == 0)
{
return actions;
}
for(Integer myUnitID : myUnitIDs)
{
actions.put(myUnitID, Action.createCompoundAttack(myUnitID, enemyUnitIDs.get(0)));
}
return actions;
}
@Override
public Map<Integer, Action> middleStep(StateView newstate,HistoryView statehistory) {
Map<Integer, Action> actions = new HashMap<Integer, Action>();
List<Integer> myUnitIds = newstate.getUnitIds(playernum);
List<Integer> footmanIds = new ArrayList<Integer>();
List<Integer> archerIds = new ArrayList<Integer>();
List<Integer> ballistaIds = new ArrayList<Integer>();
List<Integer> enemyUnitIDs = newstate.getUnitIds(enemyPlayerNum);
int targetX = 0;
int targetY = 0;
if (archerIds.size() > 0) {
UnitView archer = newstate.getUnit(archerIds.get(0));
targetX = archer.getXPosition();
targetY = archer.getYPosition();
}
for(Integer unitID : myUnitIds) {
UnitView unit = newstate.getUnit(unitID);
String unitTypeName = unit.getTemplateView().getName();
if(unitTypeName.toLowerCase().equals("footman")) {
footmanIds.add(unitID);
}else if(unitTypeName.toLowerCase().equals("archer")) {
archerIds.add(unitID);
}else if(unitTypeName.toLowerCase().equals("ballista")) {
ballistaIds.add(unitID);
}else
System.err.println("Unexpected Unit type: "+ unitTypeName);
}
if(enemyUnitIDs.size() == 0)
{
return actions;
}
int currentStep = newstate.getTurnNumber();
for(ActionResult feedback : statehistory.getCommandFeedback(playernum, currentStep-1).values())
{
int unitID = feedback.getAction().getUnitId();
List<DamageLog> damageLogs = statehistory.getDamageLogs(currentStep);
for (Integer footmanID : footmanIds) {
actions.put(footmanID, Action.createCompoundMove(footmanID, 16, 8));
if (currentStep >= 180) {
actions.put(footmanID, Action.createCompoundMove(footmanID, 15, 13));
}
if (currentStep >= 220) {
actions.put(footmanID, Action.createCompoundAttack(footmanID, enemyUnitIDs.get(0)));
}
}
for (Integer archer : archerIds) {
actions.put(archer, Action.createCompoundMove(archer, 16, 11));
if (currentStep >= 200) {
actions.put(archer, Action.createCompoundAttack(archer, enemyUnitIDs.get(0)));
}
}
for (Integer ballista : ballistaIds) {
actions.put(ballista, Action.createCompoundMove(ballista, 20, 13));
if (currentStep >= 500) {
actions.put(ballista, Action.createCompoundAttack(ballista, enemyUnitIDs.get(0)));
}
}
}
return actions;
}
@Override
public void terminalStep(StateView newstate, HistoryView statehistory) {
System.out.println("Finished the episode");
}
@Override
public void savePlayerData(OutputStream os) {
// TODO Auto-generated method stub
}
@Override
public void loadPlayerData(InputStream is) {
// TODO Auto-generated method stub
}
}
|
UTF-8
|
Java
| 4,160 |
java
|
MyCombatAgent.java
|
Java
|
[] | null |
[] |
package first_agents.edu.cwru.sepia.agent;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.cwru.sepia.action.Action;
import edu.cwru.sepia.action.ActionFeedback;
import edu.cwru.sepia.action.ActionResult;
import edu.cwru.sepia.agent.Agent;
import edu.cwru.sepia.environment.model.history.DamageLog;
import edu.cwru.sepia.environment.model.history.History.HistoryView;
import edu.cwru.sepia.environment.model.state.State.StateView;
import edu.cwru.sepia.environment.model.state.Unit.UnitView;
public class MyCombatAgent extends Agent {
private int enemyPlayerNum = 1;
public MyCombatAgent(int playernum, String[] otherargs) {
super(playernum);
if(otherargs.length > 0)
{
enemyPlayerNum = new Integer(otherargs[0]);
}
System.out.println("Constructed MyCombatAgent");
}
@Override
public Map<Integer, Action> initialStep(StateView newstate,
HistoryView statehistory) {
Map<Integer, Action> actions = new HashMap<Integer, Action>();
List<Integer> myUnitIDs = newstate.getUnitIds(playernum);
List<Integer> enemyUnitIDs = newstate.getUnitIds(enemyPlayerNum);
if(enemyUnitIDs.size() == 0)
{
return actions;
}
for(Integer myUnitID : myUnitIDs)
{
actions.put(myUnitID, Action.createCompoundAttack(myUnitID, enemyUnitIDs.get(0)));
}
return actions;
}
@Override
public Map<Integer, Action> middleStep(StateView newstate,HistoryView statehistory) {
Map<Integer, Action> actions = new HashMap<Integer, Action>();
List<Integer> myUnitIds = newstate.getUnitIds(playernum);
List<Integer> footmanIds = new ArrayList<Integer>();
List<Integer> archerIds = new ArrayList<Integer>();
List<Integer> ballistaIds = new ArrayList<Integer>();
List<Integer> enemyUnitIDs = newstate.getUnitIds(enemyPlayerNum);
int targetX = 0;
int targetY = 0;
if (archerIds.size() > 0) {
UnitView archer = newstate.getUnit(archerIds.get(0));
targetX = archer.getXPosition();
targetY = archer.getYPosition();
}
for(Integer unitID : myUnitIds) {
UnitView unit = newstate.getUnit(unitID);
String unitTypeName = unit.getTemplateView().getName();
if(unitTypeName.toLowerCase().equals("footman")) {
footmanIds.add(unitID);
}else if(unitTypeName.toLowerCase().equals("archer")) {
archerIds.add(unitID);
}else if(unitTypeName.toLowerCase().equals("ballista")) {
ballistaIds.add(unitID);
}else
System.err.println("Unexpected Unit type: "+ unitTypeName);
}
if(enemyUnitIDs.size() == 0)
{
return actions;
}
int currentStep = newstate.getTurnNumber();
for(ActionResult feedback : statehistory.getCommandFeedback(playernum, currentStep-1).values())
{
int unitID = feedback.getAction().getUnitId();
List<DamageLog> damageLogs = statehistory.getDamageLogs(currentStep);
for (Integer footmanID : footmanIds) {
actions.put(footmanID, Action.createCompoundMove(footmanID, 16, 8));
if (currentStep >= 180) {
actions.put(footmanID, Action.createCompoundMove(footmanID, 15, 13));
}
if (currentStep >= 220) {
actions.put(footmanID, Action.createCompoundAttack(footmanID, enemyUnitIDs.get(0)));
}
}
for (Integer archer : archerIds) {
actions.put(archer, Action.createCompoundMove(archer, 16, 11));
if (currentStep >= 200) {
actions.put(archer, Action.createCompoundAttack(archer, enemyUnitIDs.get(0)));
}
}
for (Integer ballista : ballistaIds) {
actions.put(ballista, Action.createCompoundMove(ballista, 20, 13));
if (currentStep >= 500) {
actions.put(ballista, Action.createCompoundAttack(ballista, enemyUnitIDs.get(0)));
}
}
}
return actions;
}
@Override
public void terminalStep(StateView newstate, HistoryView statehistory) {
System.out.println("Finished the episode");
}
@Override
public void savePlayerData(OutputStream os) {
// TODO Auto-generated method stub
}
@Override
public void loadPlayerData(InputStream is) {
// TODO Auto-generated method stub
}
}
| 4,160 | 0.7125 | 0.702644 | 149 | 26.926174 | 26.332691 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.664429 | false | false |
3
|
b07dfcfe995a1d64dc65ef2201d107923a2b046d
| 13,855,564,521,318 |
27cbf945c9f53256a304dacd0d6e37f2438c12c1
|
/Project_BC/src/main/java/dao/NoticeBoardDAO.java
|
b75f28d75c621504dab36a9ddb39f8ae78918347
|
[] |
no_license
|
ITWILL1TEAM/BC
|
https://github.com/ITWILL1TEAM/BC
|
990c545fec9c1bd9a0027fb00c19b531b6d17993
|
588184224c32161e96a6346aeebba139707962c0
|
refs/heads/master
| 2023-08-29T15:46:45.249000 | 2021-11-10T23:50:48 | 2021-11-10T23:50:48 | 426,505,863 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dao;
import static db.JdbcUtil.close;
import static db.JdbcUtil.getConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import vo.BoardBean;
import vo.NoticeBean;
public class NoticeBoardDAO {
private NoticeBoardDAO() {}
private static NoticeBoardDAO instance;
public static NoticeBoardDAO getInstance() {
// 기존의 인스턴스가 존재하지 않을 경우에만 인스턴스를 생성
if(instance == null) {
instance = new NoticeBoardDAO();
}
// 인스턴스 턴
return instance;
}
// ========================================================================
// DB 작업을 수행하기 위해 사용하는 Connection 타입 멤버변수 선언
Connection con;
// Connection 객체를 외부로부터 전달받아 저장하기 위한 Setter 메서드 정의
public void setConnection(Connection con) {
this.con = con;
}
public int insertArticle(NoticeBean board) {
int insertCount = 0;
PreparedStatement pstmt = null;
ResultSet rs = null;
int num = 1; // 새 글 번호를 저장할 변수 선언
try {
// 글 등록 작업을 위한 INSERT
// => 등록일(board_date)은 now() 함수 활용
String sql = "INSERT INTO notice VALUES (null,?,?,now())";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, board.getNotice_subject());
pstmt.setString(2, board.getNotice_content());
// INSERT 구문 실행 및 결과 리턴받기 => insertCount 에 저장
insertCount = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
System.out.println("insertArticle() 오류 - " + e.getMessage());
} finally {
close(pstmt);
}
return insertCount;
}
public ArrayList<NoticeBean> selectNoticeList() {
ArrayList<NoticeBean> articleList = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM notice ORDER BY notice_num DESC";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
articleList = new ArrayList<NoticeBean>();
while (rs.next()) {
// BoardBean 객체를 생성하여 1개 레코드 정보를 BoardBean 객체에 저장
// => 글번호, 작성자, 제목, 날짜, 조회수만 필요
// (답글에 대한 들여쓰기를 위해 board_re_lev 값도 추가)
NoticeBean notice = new NoticeBean();
notice.setNotice_num(rs.getInt("notice_num"));
notice.setNotice_subject(rs.getString("notice_subject"));
notice.setNotice_content(rs.getString("notice_content"));
notice.setNotice_date(rs.getDate("notice_date"));
// 1개 레코드가 저장된 BoardBean 객체를 List 객체에 추가
articleList.add(notice);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
// 자원 반환
close(rs);
close(pstmt);
}
return articleList;
}
public NoticeBean selectNotice(int notice_num) {
NoticeBean article = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = getConnection();
// 3단계. SQL 구문 작성 및 전달
// -> 글번호(num)에 해당하는 게시물 상세 정보 조회 후 BoardBean 객체에 저장
String sql = "SELECT * FROM notice WHERE notice_num=?";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, notice_num);
rs = pstmt.executeQuery();
if (rs.next()) {
// 조회된 상세 정보를 BoardBean 객체에 저장
article = new NoticeBean();
article.setNotice_num(rs.getInt("notice_num"));
article.setNotice_subject(rs.getString("notice_subject"));
article.setNotice_content(rs.getString("notice_content"));
article.setNotice_date(rs.getDate("notice_date"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 자원 반환
close(rs);
close(pstmt);
}
return article;
}
}
|
UTF-8
|
Java
| 4,180 |
java
|
NoticeBoardDAO.java
|
Java
|
[] | null |
[] |
package dao;
import static db.JdbcUtil.close;
import static db.JdbcUtil.getConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import vo.BoardBean;
import vo.NoticeBean;
public class NoticeBoardDAO {
private NoticeBoardDAO() {}
private static NoticeBoardDAO instance;
public static NoticeBoardDAO getInstance() {
// 기존의 인스턴스가 존재하지 않을 경우에만 인스턴스를 생성
if(instance == null) {
instance = new NoticeBoardDAO();
}
// 인스턴스 턴
return instance;
}
// ========================================================================
// DB 작업을 수행하기 위해 사용하는 Connection 타입 멤버변수 선언
Connection con;
// Connection 객체를 외부로부터 전달받아 저장하기 위한 Setter 메서드 정의
public void setConnection(Connection con) {
this.con = con;
}
public int insertArticle(NoticeBean board) {
int insertCount = 0;
PreparedStatement pstmt = null;
ResultSet rs = null;
int num = 1; // 새 글 번호를 저장할 변수 선언
try {
// 글 등록 작업을 위한 INSERT
// => 등록일(board_date)은 now() 함수 활용
String sql = "INSERT INTO notice VALUES (null,?,?,now())";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, board.getNotice_subject());
pstmt.setString(2, board.getNotice_content());
// INSERT 구문 실행 및 결과 리턴받기 => insertCount 에 저장
insertCount = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
System.out.println("insertArticle() 오류 - " + e.getMessage());
} finally {
close(pstmt);
}
return insertCount;
}
public ArrayList<NoticeBean> selectNoticeList() {
ArrayList<NoticeBean> articleList = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM notice ORDER BY notice_num DESC";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
articleList = new ArrayList<NoticeBean>();
while (rs.next()) {
// BoardBean 객체를 생성하여 1개 레코드 정보를 BoardBean 객체에 저장
// => 글번호, 작성자, 제목, 날짜, 조회수만 필요
// (답글에 대한 들여쓰기를 위해 board_re_lev 값도 추가)
NoticeBean notice = new NoticeBean();
notice.setNotice_num(rs.getInt("notice_num"));
notice.setNotice_subject(rs.getString("notice_subject"));
notice.setNotice_content(rs.getString("notice_content"));
notice.setNotice_date(rs.getDate("notice_date"));
// 1개 레코드가 저장된 BoardBean 객체를 List 객체에 추가
articleList.add(notice);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
// 자원 반환
close(rs);
close(pstmt);
}
return articleList;
}
public NoticeBean selectNotice(int notice_num) {
NoticeBean article = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = getConnection();
// 3단계. SQL 구문 작성 및 전달
// -> 글번호(num)에 해당하는 게시물 상세 정보 조회 후 BoardBean 객체에 저장
String sql = "SELECT * FROM notice WHERE notice_num=?";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, notice_num);
rs = pstmt.executeQuery();
if (rs.next()) {
// 조회된 상세 정보를 BoardBean 객체에 저장
article = new NoticeBean();
article.setNotice_num(rs.getInt("notice_num"));
article.setNotice_subject(rs.getString("notice_subject"));
article.setNotice_content(rs.getString("notice_content"));
article.setNotice_date(rs.getDate("notice_date"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 자원 반환
close(rs);
close(pstmt);
}
return article;
}
}
| 4,180 | 0.596652 | 0.594492 | 146 | 24.369864 | 20.195284 | 79 | false | false | 0 | 0 | 0 | 0 | 73 | 0.019708 | 1.753425 | false | false |
3
|
c46a1457fe86cd28f2e11db907dbc144f8024588
| 22,565,758,201,654 |
3bfbc473007c4d722312ad0e29f545409f40a52c
|
/storm_demo/src/com/tedu/WCTopologyDriver.java
|
a67013b9dbb0e5b3a12604b95dba24a2a0a5aa00
|
[] |
no_license
|
zengfanlin/hdfs_api
|
https://github.com/zengfanlin/hdfs_api
|
5f807d53e45aaf3caff5677d035a7cc09044684b
|
09295670728784ceb8ab5a7173f646dda15300c6
|
refs/heads/master
| 2020-05-01T03:42:29.077000 | 2019-04-05T09:06:37 | 2019-04-05T09:06:46 | 177,252,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tedu;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.generated.StormTopology;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
public class WCTopologyDriver {
public static void main(String[] args) throws Exception, InvalidTopologyException {
// 创建组件
SentenceSpout sentenceSpout = new SentenceSpout();
SentenceBolt sentenceBolt = new SentenceBolt();
WordCountBolt wpBolt = new WordCountBolt();
ReportBolt reportBolt = new ReportBolt();
// 拓扑构建者
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("sentence_Spout", sentenceSpout);
builder.setBolt("sentence_Bolt", sentenceBolt).shuffleGrouping("sentence_Spout");
builder.setBolt("WordCount_Bolt", wpBolt).fieldsGrouping("sentence_Bolt", new Fields("word"));
builder.setBolt("Report_Bolt", reportBolt).globalGrouping("WordCount_Bolt");
// 通过构建者创建拓扑
StormTopology topology = builder.createTopology();
// Config config = new Config();
// StormSubmitter.submitTopology("WC_StormTopology", config, topology);
LocalCluster cluster=new LocalCluster();
Config config = new Config();
cluster.submitTopology("WC_StormTopology", config, topology);
Thread.sleep(10000);
cluster.killTopology("WC_StormTopology");
cluster.shutdown();
}
}
|
UTF-8
|
Java
| 1,511 |
java
|
WCTopologyDriver.java
|
Java
|
[] | null |
[] |
package com.tedu;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.generated.StormTopology;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
public class WCTopologyDriver {
public static void main(String[] args) throws Exception, InvalidTopologyException {
// 创建组件
SentenceSpout sentenceSpout = new SentenceSpout();
SentenceBolt sentenceBolt = new SentenceBolt();
WordCountBolt wpBolt = new WordCountBolt();
ReportBolt reportBolt = new ReportBolt();
// 拓扑构建者
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("sentence_Spout", sentenceSpout);
builder.setBolt("sentence_Bolt", sentenceBolt).shuffleGrouping("sentence_Spout");
builder.setBolt("WordCount_Bolt", wpBolt).fieldsGrouping("sentence_Bolt", new Fields("word"));
builder.setBolt("Report_Bolt", reportBolt).globalGrouping("WordCount_Bolt");
// 通过构建者创建拓扑
StormTopology topology = builder.createTopology();
// Config config = new Config();
// StormSubmitter.submitTopology("WC_StormTopology", config, topology);
LocalCluster cluster=new LocalCluster();
Config config = new Config();
cluster.submitTopology("WC_StormTopology", config, topology);
Thread.sleep(10000);
cluster.killTopology("WC_StormTopology");
cluster.shutdown();
}
}
| 1,511 | 0.779661 | 0.776271 | 38 | 37.815788 | 25.297031 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.184211 | false | false |
3
|
adaa8170bb28d0def77058e4c32afbd449a88ba2
| 11,184,094,844,486 |
8bc370ed4c6fac594da809f44aca7ae7dbf69e16
|
/studyApp/src/main/java/com/mo/study/rx/RxBus.java
|
d664bb541dceb150dc11722f149df4ec8ad37109
|
[] |
no_license
|
tt905/study
|
https://github.com/tt905/study
|
3375c32adc19bcdb05622f11f0ac33260a1c7d0b
|
1f2a6c820ef85e2e3c69de08dcbb833fd7f438a9
|
refs/heads/master
| 2021-01-11T07:51:17.034000 | 2017-05-18T08:05:18 | 2017-05-18T08:05:18 | 72,088,651 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mo.study.rx;
import java.util.HashMap;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subscriptions.CompositeSubscription;
/**
* 事件总线 必须要先订阅,在发送事件。不然事件会丢失
* 如果想先发送事件,缓存事件。
* 用BehaviorSubject或者ReplaySubject来代替SerializedSubject
* Created by motw on 2016/9/6.
*/
public class RxBus {
private static volatile RxBus mInstance;
private SerializedSubject<Object,Object> mSubject; //SerializedSubject是线程安全的
private HashMap<String, CompositeSubscription> mSubscriptionMap;
private RxBus(){
mSubject = new SerializedSubject<>(PublishSubject.create());
}
/**
* 获取实例
* @return
*/
public static RxBus getInstance(){
if (mInstance == null){
synchronized (RxBus.class){
if (mInstance == null){
mInstance = new RxBus();
}
}
}
return mInstance;
}
/**
* 发送事件
* @param o
*/
public void post(Object o){
mSubject.onNext(o);
}
/**
* 返回指定类型的Obserable
* @param type 要转换的类
* @param <T> 类型
* @return
*/
public <T>Observable<T> toObservable(final Class<T> type){
return mSubject.ofType(type);
}
/**
* 是否有观察者订阅
* @return
*/
public boolean hasObserable(){
return mSubject.hasObservers();
}
/**
* 订阅方法
* @param type class 订阅哪种类型的事件 比如 String
* @param next action 收到事件后执行的回调
* @param error error 出错时执行的回调
* @param <T> 类型
* @return 返回一个Subscription 可取消订阅
*/
public <T> Subscription doSubscribe(Class<T> type, Action1<T> next, Action1<Throwable> error){
return toObservable(type)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(next, error);
}
/**
* 保存订阅后的subscrip
* @param o
* @param subscription
*/
public void addSubdcription(Object o, Subscription subscription){
if (mSubscriptionMap == null){
mSubscriptionMap = new HashMap<>();
}
String key = o.getClass().getName();
if (mSubscriptionMap.get(key) != null){
mSubscriptionMap.get(key).add(subscription);
}else {
CompositeSubscription compositeSubscription = new CompositeSubscription();
compositeSubscription.add(subscription);
mSubscriptionMap.put(key, compositeSubscription);
}
}
/**
* 取消订阅
* @param o
*/
public void unSubscription(Object o){
if (mSubscriptionMap == null){
return ;
}
String key = o.getClass().getName();
if (!mSubscriptionMap.containsKey(key)){
return ;
}
if (mSubscriptionMap.get(key) != null){
mSubscriptionMap.get(key).unsubscribe();
}
mSubscriptionMap.remove(key);
}
}
|
UTF-8
|
Java
| 3,381 |
java
|
RxBus.java
|
Java
|
[
{
"context": "t或者ReplaySubject来代替SerializedSubject\n * Created by motw on 2016/9/6.\n */\npublic class RxBus {\n\n privat",
"end": 454,
"score": 0.9993191957473755,
"start": 450,
"tag": "USERNAME",
"value": "motw"
},
{
"context": "<>();\n }\n String key = o.getClass().getName();\n\n if (mSubscriptionMap.get(key) != null",
"end": 2329,
"score": 0.6351958513259888,
"start": 2322,
"tag": "KEY",
"value": "getName"
}
] | null |
[] |
package com.mo.study.rx;
import java.util.HashMap;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subscriptions.CompositeSubscription;
/**
* 事件总线 必须要先订阅,在发送事件。不然事件会丢失
* 如果想先发送事件,缓存事件。
* 用BehaviorSubject或者ReplaySubject来代替SerializedSubject
* Created by motw on 2016/9/6.
*/
public class RxBus {
private static volatile RxBus mInstance;
private SerializedSubject<Object,Object> mSubject; //SerializedSubject是线程安全的
private HashMap<String, CompositeSubscription> mSubscriptionMap;
private RxBus(){
mSubject = new SerializedSubject<>(PublishSubject.create());
}
/**
* 获取实例
* @return
*/
public static RxBus getInstance(){
if (mInstance == null){
synchronized (RxBus.class){
if (mInstance == null){
mInstance = new RxBus();
}
}
}
return mInstance;
}
/**
* 发送事件
* @param o
*/
public void post(Object o){
mSubject.onNext(o);
}
/**
* 返回指定类型的Obserable
* @param type 要转换的类
* @param <T> 类型
* @return
*/
public <T>Observable<T> toObservable(final Class<T> type){
return mSubject.ofType(type);
}
/**
* 是否有观察者订阅
* @return
*/
public boolean hasObserable(){
return mSubject.hasObservers();
}
/**
* 订阅方法
* @param type class 订阅哪种类型的事件 比如 String
* @param next action 收到事件后执行的回调
* @param error error 出错时执行的回调
* @param <T> 类型
* @return 返回一个Subscription 可取消订阅
*/
public <T> Subscription doSubscribe(Class<T> type, Action1<T> next, Action1<Throwable> error){
return toObservable(type)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(next, error);
}
/**
* 保存订阅后的subscrip
* @param o
* @param subscription
*/
public void addSubdcription(Object o, Subscription subscription){
if (mSubscriptionMap == null){
mSubscriptionMap = new HashMap<>();
}
String key = o.getClass().getName();
if (mSubscriptionMap.get(key) != null){
mSubscriptionMap.get(key).add(subscription);
}else {
CompositeSubscription compositeSubscription = new CompositeSubscription();
compositeSubscription.add(subscription);
mSubscriptionMap.put(key, compositeSubscription);
}
}
/**
* 取消订阅
* @param o
*/
public void unSubscription(Object o){
if (mSubscriptionMap == null){
return ;
}
String key = o.getClass().getName();
if (!mSubscriptionMap.containsKey(key)){
return ;
}
if (mSubscriptionMap.get(key) != null){
mSubscriptionMap.get(key).unsubscribe();
}
mSubscriptionMap.remove(key);
}
}
| 3,381 | 0.594925 | 0.592033 | 124 | 24.104839 | 20.901388 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.306452 | false | false |
3
|
116b5cba623bb2cc7ce170d2e850078422772e82
| 30,313,879,208,788 |
b44600e38e17bfb08c200465909618cf397c0b98
|
/src/main/java/com/allibilli/recator/ReactorKafkaApplication.java
|
067be0292b4594974586f0be707a9bf5f2bcfd45
|
[] |
no_license
|
haigopi/ReactorKafkaExample
|
https://github.com/haigopi/ReactorKafkaExample
|
f4d575e2e29b972b73bc2603396decae9d985f59
|
62a8193879db8e6c64590fc7da7884f52fff8cbc
|
refs/heads/master
| 2020-03-23T20:43:35.192000 | 2019-08-04T22:33:51 | 2019-08-04T22:33:51 | 142,058,456 | 4 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.allibilli.recator;
import com.allibilli.recator.publisher.KafkaProducer;
import com.allibilli.recator.model.EventModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Gopi K Kancharla
* 7/23/18 2:22 PM
*/
@SpringBootApplication
@RestController
@Slf4j
@EnableKafka
@EmbeddedKafka
public class ReactorKafkaApplication {
@Autowired
private KafkaProducer producer;
public static void main(String[] args) {
SpringApplication.run(ReactorKafkaApplication.class, args);
}
@RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
public ResponseEntity recieveRequest(@RequestBody EventModel incomingMessage) {
log.info("Message Recieved: {}", incomingMessage);
producer.sendMessage(incomingMessage);
return ResponseEntity.ok("THANKS");
}
}
|
UTF-8
|
Java
| 1,431 |
java
|
ReactorKafkaApplication.java
|
Java
|
[
{
"context": "bind.annotation.RestController;\n\n/**\n * Created by Gopi K Kancharla\n * 7/23/18 2:22 PM\n */\n\n@SpringBootApplication\n@R",
"end": 799,
"score": 0.9998474717140198,
"start": 783,
"tag": "NAME",
"value": "Gopi K Kancharla"
}
] | null |
[] |
package com.allibilli.recator;
import com.allibilli.recator.publisher.KafkaProducer;
import com.allibilli.recator.model.EventModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by <NAME>
* 7/23/18 2:22 PM
*/
@SpringBootApplication
@RestController
@Slf4j
@EnableKafka
@EmbeddedKafka
public class ReactorKafkaApplication {
@Autowired
private KafkaProducer producer;
public static void main(String[] args) {
SpringApplication.run(ReactorKafkaApplication.class, args);
}
@RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
public ResponseEntity recieveRequest(@RequestBody EventModel incomingMessage) {
log.info("Message Recieved: {}", incomingMessage);
producer.sendMessage(incomingMessage);
return ResponseEntity.ok("THANKS");
}
}
| 1,421 | 0.79385 | 0.786164 | 45 | 30.733334 | 25.941301 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488889 | false | false |
3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.