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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b7ed89f7915bca554a6332478c9892a2dde7da6f
| 18,442,589,622,973 |
75c7922e96da7b7553e212b63aa95e386450c317
|
/src/main/java/net/smoofyuniverse/common/logger/LoggerProxy.java
|
f34aa6f769d4e496ca39fe603444498fc56d4c6d
|
[
"MIT"
] |
permissive
|
Yeregorix/AppCommon
|
https://github.com/Yeregorix/AppCommon
|
d27b1e8bf4a774e6cdf155a337e81bbd1f6a4cba
|
6b85dd84e4e40e13a74f23ced31895dcc67f3c7f
|
refs/heads/master
| 2022-05-30T23:17:09.812000 | 2022-05-13T17:17:20 | 2022-05-13T17:17:20 | 93,944,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (c) 2017-2021 Hugo Dupanloup (Yeregorix)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.smoofyuniverse.common.logger;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.Marker;
class LoggerProxy implements Logger {
private final String name;
private Logger delegate;
public LoggerProxy(String name) {
this.name = name;
this.delegate = new DefaultLogger(name);
}
void setDelegate(ILoggerFactory factory) {
this.delegate = factory.getLogger(this.name);
}
@Override
public String getName() {
return this.name;
}
@Override
public boolean isTraceEnabled() {
return this.delegate.isTraceEnabled();
}
@Override
public void trace(String msg) {
this.delegate.trace(msg);
}
@Override
public void trace(String format, Object arg) {
this.delegate.trace(format, arg);
}
@Override
public void trace(String format, Object arg1, Object arg2) {
this.delegate.trace(format, arg1, arg2);
}
@Override
public void trace(String format, Object... arguments) {
this.delegate.trace(format, arguments);
}
@Override
public void trace(String msg, Throwable t) {
this.delegate.trace(msg, t);
}
@Override
public boolean isTraceEnabled(Marker marker) {
return this.delegate.isTraceEnabled(marker);
}
@Override
public void trace(Marker marker, String msg) {
this.delegate.trace(marker, msg);
}
@Override
public void trace(Marker marker, String format, Object arg) {
this.delegate.trace(marker, format, arg);
}
@Override
public void trace(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.trace(marker, format, arg1, arg2);
}
@Override
public void trace(Marker marker, String format, Object... argArray) {
this.delegate.trace(marker, format, argArray);
}
@Override
public void trace(Marker marker, String msg, Throwable t) {
this.delegate.trace(marker, msg, t);
}
@Override
public boolean isDebugEnabled() {
return this.delegate.isDebugEnabled();
}
@Override
public void debug(String msg) {
this.delegate.debug(msg);
}
@Override
public void debug(String format, Object arg) {
this.delegate.debug(format, arg);
}
@Override
public void debug(String format, Object arg1, Object arg2) {
this.delegate.debug(format, arg1, arg2);
}
@Override
public void debug(String format, Object... arguments) {
this.delegate.debug(format, arguments);
}
@Override
public void debug(String msg, Throwable t) {
this.delegate.debug(msg, t);
}
@Override
public boolean isDebugEnabled(Marker marker) {
return this.delegate.isDebugEnabled(marker);
}
@Override
public void debug(Marker marker, String msg) {
this.delegate.debug(marker, msg);
}
@Override
public void debug(Marker marker, String format, Object arg) {
this.delegate.debug(marker, format, arg);
}
@Override
public void debug(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.debug(marker, format, arg1, arg2);
}
@Override
public void debug(Marker marker, String format, Object... arguments) {
this.delegate.debug(marker, format, arguments);
}
@Override
public void debug(Marker marker, String msg, Throwable t) {
this.delegate.debug(marker, msg, t);
}
@Override
public boolean isInfoEnabled() {
return this.delegate.isInfoEnabled();
}
@Override
public void info(String msg) {
this.delegate.info(msg);
}
@Override
public void info(String format, Object arg) {
this.delegate.info(format, arg);
}
@Override
public void info(String format, Object arg1, Object arg2) {
this.delegate.info(format, arg1, arg2);
}
@Override
public void info(String format, Object... arguments) {
this.delegate.info(format, arguments);
}
@Override
public void info(String msg, Throwable t) {
this.delegate.info(msg, t);
}
@Override
public boolean isInfoEnabled(Marker marker) {
return this.delegate.isInfoEnabled(marker);
}
@Override
public void info(Marker marker, String msg) {
this.delegate.info(marker, msg);
}
@Override
public void info(Marker marker, String format, Object arg) {
this.delegate.info(marker, format, arg);
}
@Override
public void info(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.info(marker, format, arg1, arg2);
}
@Override
public void info(Marker marker, String format, Object... arguments) {
this.delegate.info(marker, format, arguments);
}
@Override
public void info(Marker marker, String msg, Throwable t) {
this.delegate.info(marker, msg, t);
}
@Override
public boolean isWarnEnabled() {
return this.delegate.isWarnEnabled();
}
@Override
public void warn(String msg) {
this.delegate.warn(msg);
}
@Override
public void warn(String format, Object arg) {
this.delegate.warn(format, arg);
}
@Override
public void warn(String format, Object... arguments) {
this.delegate.warn(format, arguments);
}
@Override
public void warn(String format, Object arg1, Object arg2) {
this.delegate.warn(format, arg1, arg2);
}
@Override
public void warn(String msg, Throwable t) {
this.delegate.warn(msg, t);
}
@Override
public boolean isWarnEnabled(Marker marker) {
return this.delegate.isWarnEnabled(marker);
}
@Override
public void warn(Marker marker, String msg) {
this.delegate.warn(marker, msg);
}
@Override
public void warn(Marker marker, String format, Object arg) {
this.delegate.warn(marker, format, arg);
}
@Override
public void warn(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.warn(marker, format, arg1, arg2);
}
@Override
public void warn(Marker marker, String format, Object... arguments) {
this.delegate.warn(marker, format, arguments);
}
@Override
public void warn(Marker marker, String msg, Throwable t) {
this.delegate.warn(marker, msg, t);
}
@Override
public boolean isErrorEnabled() {
return this.delegate.isErrorEnabled();
}
@Override
public void error(String msg) {
this.delegate.error(msg);
}
@Override
public void error(String format, Object arg) {
this.delegate.error(format, arg);
}
@Override
public void error(String format, Object arg1, Object arg2) {
this.delegate.error(format, arg1, arg2);
}
@Override
public void error(String format, Object... arguments) {
this.delegate.error(format, arguments);
}
@Override
public void error(String msg, Throwable t) {
this.delegate.error(msg, t);
}
@Override
public boolean isErrorEnabled(Marker marker) {
return this.delegate.isErrorEnabled(marker);
}
@Override
public void error(Marker marker, String msg) {
this.delegate.error(marker, msg);
}
@Override
public void error(Marker marker, String format, Object arg) {
this.delegate.error(marker, format, arg);
}
@Override
public void error(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.error(marker, format, arg1, arg2);
}
@Override
public void error(Marker marker, String format, Object... arguments) {
this.delegate.error(marker, format, arguments);
}
@Override
public void error(Marker marker, String msg, Throwable t) {
this.delegate.error(marker, msg, t);
}
}
|
UTF-8
|
Java
| 8,158 |
java
|
LoggerProxy.java
|
Java
|
[
{
"context": "/*\n * Copyright (c) 2017-2021 Hugo Dupanloup (Yeregorix)\n *\n * Permission is hereby granted, f",
"end": 44,
"score": 0.9998762011528015,
"start": 30,
"tag": "NAME",
"value": "Hugo Dupanloup"
},
{
"context": "/*\n * Copyright (c) 2017-2021 Hugo Dupanloup (Yeregorix)\n *\n * Permission is hereby granted, free of char",
"end": 55,
"score": 0.9798443913459778,
"start": 46,
"tag": "USERNAME",
"value": "Yeregorix"
}
] | null |
[] |
/*
* Copyright (c) 2017-2021 <NAME> (Yeregorix)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.smoofyuniverse.common.logger;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.Marker;
class LoggerProxy implements Logger {
private final String name;
private Logger delegate;
public LoggerProxy(String name) {
this.name = name;
this.delegate = new DefaultLogger(name);
}
void setDelegate(ILoggerFactory factory) {
this.delegate = factory.getLogger(this.name);
}
@Override
public String getName() {
return this.name;
}
@Override
public boolean isTraceEnabled() {
return this.delegate.isTraceEnabled();
}
@Override
public void trace(String msg) {
this.delegate.trace(msg);
}
@Override
public void trace(String format, Object arg) {
this.delegate.trace(format, arg);
}
@Override
public void trace(String format, Object arg1, Object arg2) {
this.delegate.trace(format, arg1, arg2);
}
@Override
public void trace(String format, Object... arguments) {
this.delegate.trace(format, arguments);
}
@Override
public void trace(String msg, Throwable t) {
this.delegate.trace(msg, t);
}
@Override
public boolean isTraceEnabled(Marker marker) {
return this.delegate.isTraceEnabled(marker);
}
@Override
public void trace(Marker marker, String msg) {
this.delegate.trace(marker, msg);
}
@Override
public void trace(Marker marker, String format, Object arg) {
this.delegate.trace(marker, format, arg);
}
@Override
public void trace(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.trace(marker, format, arg1, arg2);
}
@Override
public void trace(Marker marker, String format, Object... argArray) {
this.delegate.trace(marker, format, argArray);
}
@Override
public void trace(Marker marker, String msg, Throwable t) {
this.delegate.trace(marker, msg, t);
}
@Override
public boolean isDebugEnabled() {
return this.delegate.isDebugEnabled();
}
@Override
public void debug(String msg) {
this.delegate.debug(msg);
}
@Override
public void debug(String format, Object arg) {
this.delegate.debug(format, arg);
}
@Override
public void debug(String format, Object arg1, Object arg2) {
this.delegate.debug(format, arg1, arg2);
}
@Override
public void debug(String format, Object... arguments) {
this.delegate.debug(format, arguments);
}
@Override
public void debug(String msg, Throwable t) {
this.delegate.debug(msg, t);
}
@Override
public boolean isDebugEnabled(Marker marker) {
return this.delegate.isDebugEnabled(marker);
}
@Override
public void debug(Marker marker, String msg) {
this.delegate.debug(marker, msg);
}
@Override
public void debug(Marker marker, String format, Object arg) {
this.delegate.debug(marker, format, arg);
}
@Override
public void debug(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.debug(marker, format, arg1, arg2);
}
@Override
public void debug(Marker marker, String format, Object... arguments) {
this.delegate.debug(marker, format, arguments);
}
@Override
public void debug(Marker marker, String msg, Throwable t) {
this.delegate.debug(marker, msg, t);
}
@Override
public boolean isInfoEnabled() {
return this.delegate.isInfoEnabled();
}
@Override
public void info(String msg) {
this.delegate.info(msg);
}
@Override
public void info(String format, Object arg) {
this.delegate.info(format, arg);
}
@Override
public void info(String format, Object arg1, Object arg2) {
this.delegate.info(format, arg1, arg2);
}
@Override
public void info(String format, Object... arguments) {
this.delegate.info(format, arguments);
}
@Override
public void info(String msg, Throwable t) {
this.delegate.info(msg, t);
}
@Override
public boolean isInfoEnabled(Marker marker) {
return this.delegate.isInfoEnabled(marker);
}
@Override
public void info(Marker marker, String msg) {
this.delegate.info(marker, msg);
}
@Override
public void info(Marker marker, String format, Object arg) {
this.delegate.info(marker, format, arg);
}
@Override
public void info(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.info(marker, format, arg1, arg2);
}
@Override
public void info(Marker marker, String format, Object... arguments) {
this.delegate.info(marker, format, arguments);
}
@Override
public void info(Marker marker, String msg, Throwable t) {
this.delegate.info(marker, msg, t);
}
@Override
public boolean isWarnEnabled() {
return this.delegate.isWarnEnabled();
}
@Override
public void warn(String msg) {
this.delegate.warn(msg);
}
@Override
public void warn(String format, Object arg) {
this.delegate.warn(format, arg);
}
@Override
public void warn(String format, Object... arguments) {
this.delegate.warn(format, arguments);
}
@Override
public void warn(String format, Object arg1, Object arg2) {
this.delegate.warn(format, arg1, arg2);
}
@Override
public void warn(String msg, Throwable t) {
this.delegate.warn(msg, t);
}
@Override
public boolean isWarnEnabled(Marker marker) {
return this.delegate.isWarnEnabled(marker);
}
@Override
public void warn(Marker marker, String msg) {
this.delegate.warn(marker, msg);
}
@Override
public void warn(Marker marker, String format, Object arg) {
this.delegate.warn(marker, format, arg);
}
@Override
public void warn(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.warn(marker, format, arg1, arg2);
}
@Override
public void warn(Marker marker, String format, Object... arguments) {
this.delegate.warn(marker, format, arguments);
}
@Override
public void warn(Marker marker, String msg, Throwable t) {
this.delegate.warn(marker, msg, t);
}
@Override
public boolean isErrorEnabled() {
return this.delegate.isErrorEnabled();
}
@Override
public void error(String msg) {
this.delegate.error(msg);
}
@Override
public void error(String format, Object arg) {
this.delegate.error(format, arg);
}
@Override
public void error(String format, Object arg1, Object arg2) {
this.delegate.error(format, arg1, arg2);
}
@Override
public void error(String format, Object... arguments) {
this.delegate.error(format, arguments);
}
@Override
public void error(String msg, Throwable t) {
this.delegate.error(msg, t);
}
@Override
public boolean isErrorEnabled(Marker marker) {
return this.delegate.isErrorEnabled(marker);
}
@Override
public void error(Marker marker, String msg) {
this.delegate.error(marker, msg);
}
@Override
public void error(Marker marker, String format, Object arg) {
this.delegate.error(marker, format, arg);
}
@Override
public void error(Marker marker, String format, Object arg1, Object arg2) {
this.delegate.error(marker, format, arg1, arg2);
}
@Override
public void error(Marker marker, String format, Object... arguments) {
this.delegate.error(marker, format, arguments);
}
@Override
public void error(Marker marker, String msg, Throwable t) {
this.delegate.error(marker, msg, t);
}
}
| 8,150 | 0.725545 | 0.719294 | 346 | 22.578035 | 23.94191 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615607 | false | false |
12
|
c4ab630b1f0b30086139a1e984e307bab8e684b4
| 31,851,477,491,279 |
dd45fca78862884c46f85233a894e26b2832a0ec
|
/src/Hipotenusa.java
|
dbdddfc33a737335bbcdd364f68b768a2f218f10
|
[] |
no_license
|
chasingtechnology/prueba-
|
https://github.com/chasingtechnology/prueba-
|
e4f3b565c025d63f421c3a3bc32dbae5886772c4
|
c6fdef35739c859786daa411570880a7038b8814
|
refs/heads/master
| 2021-01-16T19:14:15.911000 | 2014-03-08T15:56:46 | 2014-03-08T15:56:46 | null | 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.
*/
/**
*
* @author 33
*/
public class Hipotenusa
{
public double a=0.00;
public double b=0.00;
public double calhipo (double a, double b)
{
return (Math.sqrt((a*a) + (b*b)));
}
}
|
UTF-8
|
Java
| 433 |
java
|
Hipotenusa.java
|
Java
|
[
{
"context": "mplate in the editor.\r\n */\r\n\r\n/**\r\n *\r\n * @author 33\r\n */\r\npublic class Hipotenusa \r\n\r\n{\r\n \r\n pu",
"end": 214,
"score": 0.9991971254348755,
"start": 212,
"tag": "USERNAME",
"value": "33"
}
] | 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.
*/
/**
*
* @author 33
*/
public class Hipotenusa
{
public double a=0.00;
public double b=0.00;
public double calhipo (double a, double b)
{
return (Math.sqrt((a*a) + (b*b)));
}
}
| 433 | 0.575058 | 0.556582 | 23 | 16.826086 | 21.375834 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false |
12
|
7b17d12263f7611697abed269d86b70c25cf7c4c
| 17,978,733,132,601 |
7f20b1bddf9f48108a43a9922433b141fac66a6d
|
/cytoscape3/branches/mikes_new_model_branch/event/src/main/java/org/cytoscape/event/internal/CyEventHelperImpl.java
|
006b21f25a0b816933d43ab4e6c403f8a3c05dc2
|
[] |
no_license
|
ahdahddl/cytoscape
|
https://github.com/ahdahddl/cytoscape
|
bf783d44cddda313a5b3563ea746b07f38173022
|
a3df8f63dba4ec49942027c91ecac6efa920c195
|
refs/heads/master
| 2020-06-26T16:48:19.791000 | 2013-08-28T04:08:31 | 2013-08-28T04:08:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.cytoscape.event.internal;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.List;
import java.util.LinkedList;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.event.CyEvent;
import org.cytoscape.event.CyEventListener;
/**
* Some static utility methods that help you fire events.
*/
public class CyEventHelperImpl implements CyEventHelper {
private static final Executor exec = Executors.newCachedThreadPool();
private final BundleContext bc;
public CyEventHelperImpl( BundleContext bc ) {
this.bc = bc;
}
/**
* Calls each listener found in the Service Registry identified by
* the listenerClass and filter with the supplied event.
*/
public <E extends CyEvent, L extends CyEventListener> void fireSynchronousEvent( final E event, final Class<L> listenerClass ) {
List<L> listeners = getListeners(listenerClass);
try {
Method method = listenerClass.getMethod("handleEvent", event.getClass().getInterfaces()[0]);
for ( L listener : listeners )
method.invoke(listener,event);
} catch (NoSuchMethodException e) {
System.err.println("Listener doesn't implement \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
} catch (InvocationTargetException e) {
System.err.println("Listener can't invoke \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
} catch (IllegalAccessException e) {
System.err.println("Listener can't exectue \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
}
}
/**
* Calls each listener found in the Service Registry identified by
* the listenerClass and filter with the supplied event in a new
* thread.
* <p>
* This method should <b>ONLY</b> ever be called with a thread safe event object!
*/
public <E extends CyEvent, L extends CyEventListener> void fireAsynchronousEvent( final E event, final Class<L> listenerClass ) {
final List<L> listeners = getListeners(listenerClass);
try {
final Method method = listenerClass.getMethod("handleEvent", event.getClass().getInterfaces()[0]);
for ( final L listener : listeners ) {
Runnable task = new Runnable() {
public void run() {
try {
method.invoke(listener,event);
} catch (IllegalAccessException e) {
System.err.println("Listener can't exectue \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
} catch (InvocationTargetException e) {
System.err.println("Listener can't invoke \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
}
}
};
exec.execute(task);
}
} catch (NoSuchMethodException e) {
System.err.println("Listener doesn't implement \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
}
}
@SuppressWarnings("unchecked") // needed because of ServiceReference cast.
private <L extends CyEventListener> List<L> getListeners(Class<L> listenerClass) {
List<L> ret = new LinkedList<L>();
if ( bc == null )
return ret;
try {
ServiceReference[] sr = bc.getServiceReferences(listenerClass.getName(), null);
if ( sr != null )
for (ServiceReference r : sr ) {
L listener = (L)bc.getService(r);
if ( listener != null )
ret.add(listener);
}
} catch (Exception e) { e.printStackTrace(); }
return ret;
}
}
|
UTF-8
|
Java
| 3,561 |
java
|
CyEventHelperImpl.java
|
Java
|
[] | null |
[] |
package org.cytoscape.event.internal;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.List;
import java.util.LinkedList;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.event.CyEvent;
import org.cytoscape.event.CyEventListener;
/**
* Some static utility methods that help you fire events.
*/
public class CyEventHelperImpl implements CyEventHelper {
private static final Executor exec = Executors.newCachedThreadPool();
private final BundleContext bc;
public CyEventHelperImpl( BundleContext bc ) {
this.bc = bc;
}
/**
* Calls each listener found in the Service Registry identified by
* the listenerClass and filter with the supplied event.
*/
public <E extends CyEvent, L extends CyEventListener> void fireSynchronousEvent( final E event, final Class<L> listenerClass ) {
List<L> listeners = getListeners(listenerClass);
try {
Method method = listenerClass.getMethod("handleEvent", event.getClass().getInterfaces()[0]);
for ( L listener : listeners )
method.invoke(listener,event);
} catch (NoSuchMethodException e) {
System.err.println("Listener doesn't implement \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
} catch (InvocationTargetException e) {
System.err.println("Listener can't invoke \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
} catch (IllegalAccessException e) {
System.err.println("Listener can't exectue \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
}
}
/**
* Calls each listener found in the Service Registry identified by
* the listenerClass and filter with the supplied event in a new
* thread.
* <p>
* This method should <b>ONLY</b> ever be called with a thread safe event object!
*/
public <E extends CyEvent, L extends CyEventListener> void fireAsynchronousEvent( final E event, final Class<L> listenerClass ) {
final List<L> listeners = getListeners(listenerClass);
try {
final Method method = listenerClass.getMethod("handleEvent", event.getClass().getInterfaces()[0]);
for ( final L listener : listeners ) {
Runnable task = new Runnable() {
public void run() {
try {
method.invoke(listener,event);
} catch (IllegalAccessException e) {
System.err.println("Listener can't exectue \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
} catch (InvocationTargetException e) {
System.err.println("Listener can't invoke \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
}
}
};
exec.execute(task);
}
} catch (NoSuchMethodException e) {
System.err.println("Listener doesn't implement \"handleEvent\" method: "+listenerClass.getName());
e.printStackTrace();
}
}
@SuppressWarnings("unchecked") // needed because of ServiceReference cast.
private <L extends CyEventListener> List<L> getListeners(Class<L> listenerClass) {
List<L> ret = new LinkedList<L>();
if ( bc == null )
return ret;
try {
ServiceReference[] sr = bc.getServiceReferences(listenerClass.getName(), null);
if ( sr != null )
for (ServiceReference r : sr ) {
L listener = (L)bc.getService(r);
if ( listener != null )
ret.add(listener);
}
} catch (Exception e) { e.printStackTrace(); }
return ret;
}
}
| 3,561 | 0.713844 | 0.713283 | 108 | 31.944445 | 32.101353 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.277778 | false | false |
12
|
66242b4f68f523da7867f973d4ed94920b3844b6
| 18,983,755,515,916 |
77bc8ea875c2fc269c7db2258d5ebf7234f94829
|
/Arquitetura de SW/Apostila Caelum/Caelum-4.14/src/Porta.java
|
636646f571e1f9451c39996c5200f875dedbb3dd
|
[] |
no_license
|
flpmanso/facul
|
https://github.com/flpmanso/facul
|
a30639d667fb1563a494e49b56f70f862315beee
|
b678fdf9f8e18085447b4072067e479dc2d7f798
|
refs/heads/master
| 2020-05-02T06:03:08.630000 | 2019-03-26T12:40:57 | 2019-03-26T12:40:57 | 177,785,763 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Porta {
String aberta;
String cor;
double dimensaox;
double dimensaoy;
double dimensaoz;
void abre() {
this.aberta = "s";
}
void fecha() {
this.aberta = "n";
}
void pinta(String c) {
this.cor = c;
}
boolean estaAberta() {
if(aberta == "s") {
return true;
}else {
return false;
}
}
void mostra() {
System.out.println("a cor atual é "+ this.cor);
System.out.println("a porta está aberta? "+ estaAberta());
}
}
|
WINDOWS-1250
|
Java
| 474 |
java
|
Porta.java
|
Java
|
[] | null |
[] |
public class Porta {
String aberta;
String cor;
double dimensaox;
double dimensaoy;
double dimensaoz;
void abre() {
this.aberta = "s";
}
void fecha() {
this.aberta = "n";
}
void pinta(String c) {
this.cor = c;
}
boolean estaAberta() {
if(aberta == "s") {
return true;
}else {
return false;
}
}
void mostra() {
System.out.println("a cor atual é "+ this.cor);
System.out.println("a porta está aberta? "+ estaAberta());
}
}
| 474 | 0.595339 | 0.595339 | 33 | 13.272727 | 13.177742 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.69697 | false | false |
12
|
99f77c5bab41e7c2d43d6939afa96aecf418978d
| 1,073,741,825,692 |
d7f1113307afe8cac14d273e7fa9194f2d61a16a
|
/JwtSpringSecurity/src/main/java/com/example/JwtSpringSecurity/service/imlp/TempUsernameImpl.java
|
833ad60f979d6b5526035bedbad1840f9ea550af
|
[] |
no_license
|
eshaanmangal/Spring-jwt
|
https://github.com/eshaanmangal/Spring-jwt
|
6a2a30b2b6b63b5e858b41120a36585061990f6d
|
c505c36167db9b04ff206fff8a7d7f026b869ed2
|
refs/heads/master
| 2022-11-17T13:10:25.543000 | 2020-07-05T13:00:48 | 2020-07-05T13:00:48 | 277,551,604 | 2 | 0 | null | true | 2020-07-06T13:37:57 | 2020-07-06T13:37:56 | 2020-07-05T13:01:02 | 2020-07-05T13:01:00 | 65 | 0 | 0 | 0 | null | false | false |
package com.example.JwtSpringSecurity.service.imlp;
import com.example.JwtSpringSecurity.service.TempUsername;
import org.springframework.stereotype.Service;
@Service
public class TempUsernameImpl implements TempUsername {
private String username;
public TempUsernameImpl() {
}
public TempUsernameImpl(String username) {
this.username = username;
}
@Override
public String getUsername() {
return username;
}
@Override
public void setUsername(String username) {
this.username = username;
}
}
|
UTF-8
|
Java
| 565 |
java
|
TempUsernameImpl.java
|
Java
|
[] | null |
[] |
package com.example.JwtSpringSecurity.service.imlp;
import com.example.JwtSpringSecurity.service.TempUsername;
import org.springframework.stereotype.Service;
@Service
public class TempUsernameImpl implements TempUsername {
private String username;
public TempUsernameImpl() {
}
public TempUsernameImpl(String username) {
this.username = username;
}
@Override
public String getUsername() {
return username;
}
@Override
public void setUsername(String username) {
this.username = username;
}
}
| 565 | 0.709734 | 0.709734 | 26 | 20.73077 | 19.860199 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false |
12
|
9964844c6e8b5635e7999bf2e48e264956b78ec6
| 9,655,086,488,823 |
d947f2a52245291c9eb784935a68da60f508f2db
|
/Practice_Chap33(컬렉션 프레임워크)/src/sec05/exam04_treemap_method/TreeMapExample.java
|
1b3e9d2a92b89c01e9a680bf3f51934951805979
|
[] |
no_license
|
ColossusCMS/Eclipse_Prac
|
https://github.com/ColossusCMS/Eclipse_Prac
|
064755afa996a063aeeb9aeb9b093c62de4685a0
|
e40e189c201ce80d9c218467ea29accf6049a67e
|
refs/heads/master
| 2020-05-17T22:23:27.175000 | 2020-01-07T15:44:37 | 2020-01-07T15:44:37 | 183,992,653 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sec05.exam04_treemap_method;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> scores = new TreeMap<Integer, String>();
scores.put(new Integer(87), "홍길동");
scores.put(new Integer(98), "신은혁");
scores.put(new Integer(75), "김연아");
scores.put(new Integer(95), "손연재");
scores.put(new Integer(80), "최문석");
Map.Entry<Integer, String> entry = null;
entry = scores.firstEntry();
System.out.println("가장 낮은 점수 : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.lastEntry();
System.out.println("가장 높은 점수 : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.lowerEntry(new Integer(95));
System.out.println("95점 바로 아래 점수(미포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.higherEntry(new Integer(95));
System.out.println("95점 바로 위 점수(미포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.floorEntry(new Integer(95));
System.out.println("95점이거나 바로 아래 점수(포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.ceilingEntry(new Integer(80));
System.out.println("80점 바로 위 점수(포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
// while(!scores.isEmpty()) {
// entry = scores.pollFirstEntry();
// System.out.println(entry.getKey() + " - " + entry.getValue());
// System.out.println("남아있는 객체 수 : " + scores.size());
// }
// while(!scores.isEmpty()) {
// entry = scores.pollLastEntry();
// System.out.println(entry.getKey() + " - " + entry.getValue());
// System.out.println("남아있는 객체 수 : " + scores.size());
// }
// Set<Integer> keySet = scores.keySet();
// Iterator<Integer> it = keySet.iterator();
// while(it.hasNext()) {
// int key = it.next();
// String value = scores.get(key);
// System.out.println(key + " - " + value);
// //it.remove();
// System.out.println("남아있는 객체 수 : " + scores.size());
// }
Set<Map.Entry<Integer, String>> entrySet = scores.entrySet();
Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
while(it.hasNext()) {
Map.Entry<Integer, String> mapEntry = it.next();
int key = mapEntry.getKey();
String value = mapEntry.getValue();
System.out.println(key + " - " + value);
//it.remove();
System.out.println("남아있는 객체 수 : " + scores.size());
}
}
}
|
UHC
|
Java
| 2,751 |
java
|
TreeMapExample.java
|
Java
|
[
{
"context": "er, String>();\n\t\t\n\t\tscores.put(new Integer(87), \"홍길동\");\n\t\tscores.put(new Integer(98), \"신은혁\");\n\t\tscore",
"end": 312,
"score": 0.5059734582901001,
"start": 311,
"tag": "NAME",
"value": "길"
},
{
"context": "teger(87), \"홍길동\");\n\t\tscores.put(new Integer(98), \"신은혁\");\n\t\tscores.put(new Integer(75), \"김연아\");\n\t\tscores",
"end": 351,
"score": 0.7562116384506226,
"start": 348,
"tag": "NAME",
"value": "신은혁"
},
{
"context": "teger(98), \"신은혁\");\n\t\tscores.put(new Integer(75), \"김연아\");\n\t\tscores.put(new Integer(95), \"손연재\");\n\t\tscores",
"end": 389,
"score": 0.5786803960800171,
"start": 386,
"tag": "NAME",
"value": "김연아"
},
{
"context": "teger(75), \"김연아\");\n\t\tscores.put(new Integer(95), \"손연재\");\n\t\tscores.put(new Integer(80), \"최문석\");\n\t\t\n\t\tMap",
"end": 427,
"score": 0.6946786642074585,
"start": 424,
"tag": "NAME",
"value": "손연재"
}
] | null |
[] |
package sec05.exam04_treemap_method;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> scores = new TreeMap<Integer, String>();
scores.put(new Integer(87), "홍길동");
scores.put(new Integer(98), "신은혁");
scores.put(new Integer(75), "김연아");
scores.put(new Integer(95), "손연재");
scores.put(new Integer(80), "최문석");
Map.Entry<Integer, String> entry = null;
entry = scores.firstEntry();
System.out.println("가장 낮은 점수 : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.lastEntry();
System.out.println("가장 높은 점수 : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.lowerEntry(new Integer(95));
System.out.println("95점 바로 아래 점수(미포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.higherEntry(new Integer(95));
System.out.println("95점 바로 위 점수(미포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.floorEntry(new Integer(95));
System.out.println("95점이거나 바로 아래 점수(포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
entry = scores.ceilingEntry(new Integer(80));
System.out.println("80점 바로 위 점수(포함) : " + entry.getKey() + " - " + entry.getValue());
System.out.println();
// while(!scores.isEmpty()) {
// entry = scores.pollFirstEntry();
// System.out.println(entry.getKey() + " - " + entry.getValue());
// System.out.println("남아있는 객체 수 : " + scores.size());
// }
// while(!scores.isEmpty()) {
// entry = scores.pollLastEntry();
// System.out.println(entry.getKey() + " - " + entry.getValue());
// System.out.println("남아있는 객체 수 : " + scores.size());
// }
// Set<Integer> keySet = scores.keySet();
// Iterator<Integer> it = keySet.iterator();
// while(it.hasNext()) {
// int key = it.next();
// String value = scores.get(key);
// System.out.println(key + " - " + value);
// //it.remove();
// System.out.println("남아있는 객체 수 : " + scores.size());
// }
Set<Map.Entry<Integer, String>> entrySet = scores.entrySet();
Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
while(it.hasNext()) {
Map.Entry<Integer, String> mapEntry = it.next();
int key = mapEntry.getKey();
String value = mapEntry.getValue();
System.out.println(key + " - " + value);
//it.remove();
System.out.println("남아있는 객체 수 : " + scores.size());
}
}
}
| 2,751 | 0.620757 | 0.609052 | 76 | 32.723682 | 24.516159 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.776316 | false | false |
12
|
79919a695bb65aa10b2868b3edb8e189cf8f726e
| 3,676,492,059,803 |
f7df46177c4555094e0fe0426a719a870b5be4e6
|
/Jestures/src/main/java/jestures/core/view/enums/DialogsType.java
|
ccfbcb608aa23a36cfd58a750b7bf93dc00a0f1e
|
[
"Apache-2.0"
] |
permissive
|
Abd-Elrazek/Jestures
|
https://github.com/Abd-Elrazek/Jestures
|
247cd5c2d8679e670ee2aa07f4d21377521d5be4
|
9ad6c66867346545db32c16239a4c645e8bd9bd1
|
refs/heads/master
| 2020-04-15T13:41:44.069000 | 2019-01-07T20:10:47 | 2019-01-07T20:10:47 | 164,725,578 | 1 | 0 |
Apache-2.0
| true | 2019-05-25T17:11:50 | 2019-01-08T20:16:27 | 2019-04-16T08:12:50 | 2019-05-25T17:11:42 | 26,859 | 1 | 0 | 1 |
Java
| false | false |
/*******************************************************************************
* Copyright (c) 2018 Giulianini Luca
*
* 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 jestures.core.view.enums;
import com.jfoenix.controls.JFXDialog;
/**
* Enumeration of predefined descriptions and titles for {@link JFXDialog}.
*/
public enum DialogsType {
/**
* Help {@link DialogsType}for help button.
*/
HELP("DON'T WORRY WE CAN HELP YOU",
"1) Click on the menu and select theory.\n" + "2) Click on practice and start exercice.\n"
+ "3) Click on statistics and see your stats.\n" + "4) Only one player at time.\n" + "ENJOY!!!",
DimDialogs.SMALL);
private final String titolo;
private final String descrizione;
private final DimDialogs dim;
DialogsType(final String title, final String description, final DimDialogs size) {
this.titolo = title;
this.descrizione = description;
this.dim = size;
}
/**
* Get the title {@link DialogsType}.
*
* @return the String title.
*/
public String getTitle() {
return this.titolo;
}
/**
* Get the description {@link DialogsType}.
*
* @return the String description
*/
public String getDescription() {
return this.descrizione;
}
/**
* Get the DimDialogs.
*
* @return the {@link DimDialogs}
*/
public DimDialogs getDim() {
return this.dim;
}
/**
* Enum for text {@link DimDialogs}. You can set all the dimensions.
*
*/
public enum DimDialogs {
/**
* Dims.
*/
BIG(3), MEDIUM(2), SMALL(1);
private int dim;
DimDialogs(final int size) {
this.dim = size;
}
/**
* Get the dim.
*
* @return the dim
*/
public int getDim() {
return this.dim;
}
}
}
|
UTF-8
|
Java
| 2,567 |
java
|
DialogsType.java
|
Java
|
[
{
"context": "****************************\n * Copyright (c) 2018 Giulianini Luca\n *\n * Licensed under the Apache License, Version ",
"end": 118,
"score": 0.9998374581336975,
"start": 103,
"tag": "NAME",
"value": "Giulianini Luca"
}
] | null |
[] |
/*******************************************************************************
* Copyright (c) 2018 <NAME>
*
* 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 jestures.core.view.enums;
import com.jfoenix.controls.JFXDialog;
/**
* Enumeration of predefined descriptions and titles for {@link JFXDialog}.
*/
public enum DialogsType {
/**
* Help {@link DialogsType}for help button.
*/
HELP("DON'T WORRY WE CAN HELP YOU",
"1) Click on the menu and select theory.\n" + "2) Click on practice and start exercice.\n"
+ "3) Click on statistics and see your stats.\n" + "4) Only one player at time.\n" + "ENJOY!!!",
DimDialogs.SMALL);
private final String titolo;
private final String descrizione;
private final DimDialogs dim;
DialogsType(final String title, final String description, final DimDialogs size) {
this.titolo = title;
this.descrizione = description;
this.dim = size;
}
/**
* Get the title {@link DialogsType}.
*
* @return the String title.
*/
public String getTitle() {
return this.titolo;
}
/**
* Get the description {@link DialogsType}.
*
* @return the String description
*/
public String getDescription() {
return this.descrizione;
}
/**
* Get the DimDialogs.
*
* @return the {@link DimDialogs}
*/
public DimDialogs getDim() {
return this.dim;
}
/**
* Enum for text {@link DimDialogs}. You can set all the dimensions.
*
*/
public enum DimDialogs {
/**
* Dims.
*/
BIG(3), MEDIUM(2), SMALL(1);
private int dim;
DimDialogs(final int size) {
this.dim = size;
}
/**
* Get the dim.
*
* @return the dim
*/
public int getDim() {
return this.dim;
}
}
}
| 2,558 | 0.555902 | 0.550058 | 94 | 26.30851 | 25.861343 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.287234 | false | false |
12
|
57803b21d6ff5321315496e28df482a06f50a829
| 8,632,884,318,838 |
9acba32ddafac7d029f75d59e373730c6575fa3d
|
/checklistbank-ws/src/main/java/org/gbif/checklistbank/ws/mixins/ExtensionSerializers.java
|
a124706245f8bf8289f7da77da6ca2a2750e0d38
|
[
"Apache-2.0"
] |
permissive
|
gbif/checklistbank
|
https://github.com/gbif/checklistbank
|
381f7e7aedc23179483bc9b4ca63ca1ce0d0eea9
|
77a36861819f21e0b9098e211413a0abb3478a56
|
refs/heads/master
| 2023-08-18T09:08:00.119000 | 2023-08-17T12:50:40 | 2023-08-17T12:50:40 | 15,137,325 | 26 | 14 |
Apache-2.0
| false | 2023-08-08T11:57:47 | 2013-12-12T13:57:17 | 2023-08-01T09:10:00 | 2023-08-08T11:57:46 | 41,569 | 25 | 14 | 139 |
Java
| false | false |
/*
* 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.gbif.checklistbank.ws.mixins;
import org.gbif.api.vocabulary.Extension;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class ExtensionSerializers {
private ExtensionSerializers() {}
public static class ExtensionKeySerializer extends JsonSerializer<Extension> {
public ExtensionKeySerializer() {}
@Override
public void serialize(Extension value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeFieldName(value.name());
}
}
public static class ExtensionKeyDeserializer extends KeyDeserializer {
public ExtensionKeyDeserializer() {}
@Override
public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException {
return Extension.valueOf(key);
}
}
}
|
UTF-8
|
Java
| 1,611 |
java
|
ExtensionSerializers.java
|
Java
|
[] | null |
[] |
/*
* 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.gbif.checklistbank.ws.mixins;
import org.gbif.api.vocabulary.Extension;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class ExtensionSerializers {
private ExtensionSerializers() {}
public static class ExtensionKeySerializer extends JsonSerializer<Extension> {
public ExtensionKeySerializer() {}
@Override
public void serialize(Extension value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeFieldName(value.name());
}
}
public static class ExtensionKeyDeserializer extends KeyDeserializer {
public ExtensionKeyDeserializer() {}
@Override
public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException {
return Extension.valueOf(key);
}
}
}
| 1,611 | 0.769088 | 0.766605 | 48 | 32.5625 | 29.099617 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
12
|
e7eb4813812e0ff5781754163c1bbaabcdbc241d
| 2,611,340,159,075 |
13902a1c782399ffe7bdf002caf0ed27aeeac8c2
|
/security8013/src/main/java/com/tigerff/springcloud/security8013/controller/OrderController.java
|
07ae61a130d3263a0c8a3004cd9bb887c8045cb1
|
[] |
no_license
|
TIGER-FF/mscloud
|
https://github.com/TIGER-FF/mscloud
|
12859145edad3a1895a0f125a5f8ea1d40fbe853
|
3ce4b1c33431f2e16f79501f7d0c931d290c4607
|
refs/heads/master
| 2022-12-24T11:11:20.845000 | 2020-09-27T12:55:57 | 2020-09-27T12:55:57 | 298,949,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tigerff.springcloud.security8013.controller;
import com.alibaba.fastjson.JSONObject;
import com.tigerff.springcloud.security8013.entities.*;
import com.tigerff.springcloud.security8013.service.UserService;
import com.tigerff.springcloud.security8013.service.OrderFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author tigerff
* @version 1.0
* @date 2020/9/26 22:34
*/
@Controller
@Slf4j
public class OrderController {
@Autowired
OrderFeignService orderFeignService;
@Autowired
UserService userService;
@PostMapping("/log/order/goods")
public String addGoodsToOrder(@RequestBody OrderItem orderItem, HttpServletResponse response) throws IOException {
log.info("*********"+orderItem);
//求出价格
Double price=orderItem.getGoodsPrice()*orderItem.getGoodsNum();
//这是创建了一个新的订单
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
MyUser myUser = userService.getUserByName(user.getUsername());
Order order=new Order();
order.setUserId(myUser.getUserId());
order.setOrderPrice(price);
Long orderId = JSONObject.parseObject(JSONObject.toJSONString(orderFeignService.creatOrder(order).getData()), Long.class);
orderItem.setOrderId(orderId);
orderItem.setOrderItemPrice(price);
//将商品加入到新的订单中
CommonResult commonResult = orderFeignService.insertOrder(orderItem);
String data="{\"data\":\"order success\"}";
response.getWriter().write(data);
return null;
}
}
|
UTF-8
|
Java
| 2,062 |
java
|
OrderController.java
|
Java
|
[
{
"context": "ponse;\nimport java.io.IOException;\n\n/**\n * @author tigerff\n * @version 1.0\n * @date 2020/9/26 22:34\n */\n@Con",
"end": 787,
"score": 0.9996421933174133,
"start": 780,
"tag": "USERNAME",
"value": "tigerff"
}
] | null |
[] |
package com.tigerff.springcloud.security8013.controller;
import com.alibaba.fastjson.JSONObject;
import com.tigerff.springcloud.security8013.entities.*;
import com.tigerff.springcloud.security8013.service.UserService;
import com.tigerff.springcloud.security8013.service.OrderFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author tigerff
* @version 1.0
* @date 2020/9/26 22:34
*/
@Controller
@Slf4j
public class OrderController {
@Autowired
OrderFeignService orderFeignService;
@Autowired
UserService userService;
@PostMapping("/log/order/goods")
public String addGoodsToOrder(@RequestBody OrderItem orderItem, HttpServletResponse response) throws IOException {
log.info("*********"+orderItem);
//求出价格
Double price=orderItem.getGoodsPrice()*orderItem.getGoodsNum();
//这是创建了一个新的订单
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
MyUser myUser = userService.getUserByName(user.getUsername());
Order order=new Order();
order.setUserId(myUser.getUserId());
order.setOrderPrice(price);
Long orderId = JSONObject.parseObject(JSONObject.toJSONString(orderFeignService.creatOrder(order).getData()), Long.class);
orderItem.setOrderId(orderId);
orderItem.setOrderItemPrice(price);
//将商品加入到新的订单中
CommonResult commonResult = orderFeignService.insertOrder(orderItem);
String data="{\"data\":\"order success\"}";
response.getWriter().write(data);
return null;
}
}
| 2,062 | 0.749751 | 0.733831 | 50 | 39.200001 | 29.28071 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64 | false | false |
12
|
2a29ef1e26188230fa163928af77d67473e5b8e3
| 5,514,738,017,482 |
3f3c63924d24114b5683a25fa99b5ae1a9af2e79
|
/bjl-server/src/main/java/com/dmg/bjlserver/business/handler/room/ReqEnterRoomHandler.java
|
2e6ef3f9f3a7e0bb4e7df37ba8a8da36a0a00829
|
[] |
no_license
|
bellmit/v68_2.0
|
https://github.com/bellmit/v68_2.0
|
1f33c97a4a91406baedc30adf8f4a551c0666ad3
|
82c92d3ccc19a6fe5c251c00e82742e8f01e64b7
|
refs/heads/master
| 2022-06-22T04:05:00.969000 | 2020-05-06T09:09:20 | 2020-05-06T09:09:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dmg.bjlserver.business.handler.room;
import com.dmg.bjlserver.business.logic.BjlMsgMgr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dmg.bjlserver.business.logic.BjlMgr;
import com.dmg.bjlserver.core.msg.ReqPbMessageHandler;
import com.dmg.common.pb.java.Bjl;
import com.google.protobuf.Message;
/**
* 请求进入房间
*/
@Component("" + Bjl.BjlMessageId.ReqEnterRoom_ID_VALUE)
public final class ReqEnterRoomHandler implements ReqPbMessageHandler {
@Autowired
private BjlMgr bjlMgr;
@Autowired
private BjlMsgMgr msgMgr;
@Override
public void action(Object player, Message message) {
if(bjlMgr.getStopService()) {
this.msgMgr.sendExitRoomMsg((Long) player, Bjl.BjlCode.STOP_SERVER);
return;
}
Bjl.ReqEnterRoom msg = (Bjl.ReqEnterRoom) message;
this.bjlMgr.enterRoom(player, msg.getRoomId());
}
}
|
UTF-8
|
Java
| 981 |
java
|
ReqEnterRoomHandler.java
|
Java
|
[] | null |
[] |
package com.dmg.bjlserver.business.handler.room;
import com.dmg.bjlserver.business.logic.BjlMsgMgr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dmg.bjlserver.business.logic.BjlMgr;
import com.dmg.bjlserver.core.msg.ReqPbMessageHandler;
import com.dmg.common.pb.java.Bjl;
import com.google.protobuf.Message;
/**
* 请求进入房间
*/
@Component("" + Bjl.BjlMessageId.ReqEnterRoom_ID_VALUE)
public final class ReqEnterRoomHandler implements ReqPbMessageHandler {
@Autowired
private BjlMgr bjlMgr;
@Autowired
private BjlMsgMgr msgMgr;
@Override
public void action(Object player, Message message) {
if(bjlMgr.getStopService()) {
this.msgMgr.sendExitRoomMsg((Long) player, Bjl.BjlCode.STOP_SERVER);
return;
}
Bjl.ReqEnterRoom msg = (Bjl.ReqEnterRoom) message;
this.bjlMgr.enterRoom(player, msg.getRoomId());
}
}
| 981 | 0.73065 | 0.73065 | 34 | 27.5 | 24.70443 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
a012d4c50a996e82bffdbb4cbc5b6428acdf7772
| 12,111,807,829,163 |
1408e09cab0f017d96a608f1a53ef136925ab6c9
|
/common-modules/framework-logger/src/main/java/com/springframework/log/util/RequestUtils.java
|
d2ae9f719e8ba25cf5774fd3e9fc9106fef0cf41
|
[] |
no_license
|
xie-summer/cloud
|
https://github.com/xie-summer/cloud
|
c26ebe3682860d235656d674c8c1d86c123a7129
|
d316ac438d03deeaf630f5d8d273120f9484e578
|
refs/heads/master
| 2018-10-16T05:23:53.507000 | 2018-09-28T16:10:45 | 2018-09-28T16:10:54 | 138,995,518 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.springframework.log.util;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* Http请求工具类
*
* @author summer
* @date 2015-06-11
*/
public class RequestUtils {
/**
* 获取请求的IP地址
*
* @param request
* @return
*/
public static String getRemoteIP(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("Proxy-Client-IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getRemoteAddr();
}
if (StringUtils.isNotBlank(ip)) {
int index = ip.indexOf(',');
if (index > 0) {
ip = ip.substring(0, index);
}
}
return ip;
}
public static String getUserAgent(HttpServletRequest request) {
return request.getHeader("user-agent");
}
/**
* 验证请求的合法性,防止跨域攻击
*
* @param request
* @return
*/
public static boolean validateRequest(HttpServletRequest request) {
String referer = "";
boolean refererSign = true; // true 站内提交,验证通过 //false 站外提交,验证失败
Enumeration<?> headerValues = request.getHeaders("referer");
while (headerValues.hasMoreElements()) {
referer = (String) headerValues.nextElement();
}
// 判断是否存在请求页面
if (StringUtils.isBlank(referer)) {
refererSign = false;
} else {
// 判断请求页面和getRequestURI是否相同
String servernameStr = request.getServerName();
if (StringUtils.isNotBlank(servernameStr)) {
int index = 0;
if (StringUtils.indexOf(referer, "https://") == 0) {
index = 8;
} else if (StringUtils.indexOf(referer, "http://") == 0) {
index = 7;
}
if (referer.length() - index < servernameStr.length()) {// 长度不够
refererSign = false;
} else { // 比较字符串(主机名称)是否相同
String refererStr = referer.substring(index, index + servernameStr.length());
if (!servernameStr.equalsIgnoreCase(refererStr)) {
refererSign = false;
}
}
} else {
refererSign = false;
}
}
return refererSign;
}
public static String getFullURL(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
if (request.getQueryString() != null) {
url.append('?');
url.append(request.getQueryString());
}
return url.toString();
}
public static String getFullRelativeUrl(HttpServletRequest request) {
String requestURI = request.getRequestURI();
if (request.getQueryString() != null) {
requestURI += "?" + request.getQueryString();
}
return requestURI;
}
public static String getHeadersAndBody(HttpServletRequest request) {
StringBuilder requestStr = new StringBuilder();
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = request.getHeader(name);
requestStr.append(name + "=" + value + ";");
}
// the request may already be read. so return empty for now. Fix it later. TODO : Kai
// try {
// requestStr.append(CharStreams.toString(request.getReader()));
// }catch (IOException ioEx){} //ignore the io exception
return requestStr.toString();
}
}
|
UTF-8
|
Java
| 4,471 |
java
|
RequestUtils.java
|
Java
|
[
{
"context": "util.Enumeration;\n\n\n/**\n * Http请求工具类\n *\n * @author summer\n * @date 2015-06-11\n */\npublic class RequestUtils",
"end": 200,
"score": 0.9977741837501526,
"start": 194,
"tag": "USERNAME",
"value": "summer"
}
] | null |
[] |
package com.springframework.log.util;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* Http请求工具类
*
* @author summer
* @date 2015-06-11
*/
public class RequestUtils {
/**
* 获取请求的IP地址
*
* @param request
* @return
*/
public static String getRemoteIP(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("Proxy-Client-IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getRemoteAddr();
}
if (StringUtils.isNotBlank(ip)) {
int index = ip.indexOf(',');
if (index > 0) {
ip = ip.substring(0, index);
}
}
return ip;
}
public static String getUserAgent(HttpServletRequest request) {
return request.getHeader("user-agent");
}
/**
* 验证请求的合法性,防止跨域攻击
*
* @param request
* @return
*/
public static boolean validateRequest(HttpServletRequest request) {
String referer = "";
boolean refererSign = true; // true 站内提交,验证通过 //false 站外提交,验证失败
Enumeration<?> headerValues = request.getHeaders("referer");
while (headerValues.hasMoreElements()) {
referer = (String) headerValues.nextElement();
}
// 判断是否存在请求页面
if (StringUtils.isBlank(referer)) {
refererSign = false;
} else {
// 判断请求页面和getRequestURI是否相同
String servernameStr = request.getServerName();
if (StringUtils.isNotBlank(servernameStr)) {
int index = 0;
if (StringUtils.indexOf(referer, "https://") == 0) {
index = 8;
} else if (StringUtils.indexOf(referer, "http://") == 0) {
index = 7;
}
if (referer.length() - index < servernameStr.length()) {// 长度不够
refererSign = false;
} else { // 比较字符串(主机名称)是否相同
String refererStr = referer.substring(index, index + servernameStr.length());
if (!servernameStr.equalsIgnoreCase(refererStr)) {
refererSign = false;
}
}
} else {
refererSign = false;
}
}
return refererSign;
}
public static String getFullURL(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
if (request.getQueryString() != null) {
url.append('?');
url.append(request.getQueryString());
}
return url.toString();
}
public static String getFullRelativeUrl(HttpServletRequest request) {
String requestURI = request.getRequestURI();
if (request.getQueryString() != null) {
requestURI += "?" + request.getQueryString();
}
return requestURI;
}
public static String getHeadersAndBody(HttpServletRequest request) {
StringBuilder requestStr = new StringBuilder();
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = request.getHeader(name);
requestStr.append(name + "=" + value + ";");
}
// the request may already be read. so return empty for now. Fix it later. TODO : Kai
// try {
// requestStr.append(CharStreams.toString(request.getReader()));
// }catch (IOException ioEx){} //ignore the io exception
return requestStr.toString();
}
}
| 4,471 | 0.542897 | 0.538014 | 130 | 32.084614 | 26.447054 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.523077 | false | false |
12
|
d37fbec2b8a96594a4a8aa192bc845b0ef74fdb2
| 7,155,415,577,447 |
876beb3d3c8c532b86841132a0ac2d12a6c2e997
|
/src/main/Player.java
|
d8c12a185468a662d81eade1a43014e80163d90e
|
[] |
no_license
|
zizdarren/FlappyBox
|
https://github.com/zizdarren/FlappyBox
|
8ee294e37971e3fece1cf22772a86845f9903caf
|
3980cd4d716d7f99213703689ea08ec7504d0075
|
refs/heads/master
| 2021-01-25T09:14:28.990000 | 2017-06-08T23:56:55 | 2017-06-08T23:56:55 | 93,607,871 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package main;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Graphics2D;
public class Player {
private int width;
private int height;
private Rectangle bound;
private int midX;
private int midY;
private double posX;
private double posY;
private double momentum = 0;
private double fallSpeed = 0.20;
private double maxfallSpeed = 10;
private double jumpStart = -4;
private boolean isJump = false;
public Player(int width, int height, int posX, int posY){
this.width = width;
this.height = height;
this.posX = posX;
this.posY = posY;
this.bound = new Rectangle((int)this.posX, (int)this.posY, this.width, this.height);
this.midX = posX + width/2;
this.midY = posY + height/2;
}
public void update(){
if( momentum <= maxfallSpeed){
momentum += fallSpeed;
}
if(isJump && momentum >=0){
momentum = jumpStart;
}
if(posY >= GamePanel.HEIGHT * 3/4){
posY = GamePanel.HEIGHT * 3/4;
if(momentum > 0){
momentum = 0;
}
}
if(posY < 0){
posY = 0;
}
posY += momentum;
midY = (int)posY + height/2;
bound.setLocation((int)posX, (int)posY);
}
public void draw(Graphics2D g){
g.setColor(Color.RED);
g.fillRect((int)posX, (int)posY, width, height);
//draw the player bound
g.setColor(Color.WHITE);
g.drawRect(bound.x, bound.y, bound.width, bound.height);
}
public boolean isJump(){
return isJump;
}
public void setJump(boolean jump){
isJump = jump;
}
public int getMidX(){
return midX;
}
public int getMidY(){
return midY;
}
public Rectangle getBound(){
return bound;
}
}
|
UTF-8
|
Java
| 1,622 |
java
|
Player.java
|
Java
|
[] | null |
[] |
package main;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.Graphics2D;
public class Player {
private int width;
private int height;
private Rectangle bound;
private int midX;
private int midY;
private double posX;
private double posY;
private double momentum = 0;
private double fallSpeed = 0.20;
private double maxfallSpeed = 10;
private double jumpStart = -4;
private boolean isJump = false;
public Player(int width, int height, int posX, int posY){
this.width = width;
this.height = height;
this.posX = posX;
this.posY = posY;
this.bound = new Rectangle((int)this.posX, (int)this.posY, this.width, this.height);
this.midX = posX + width/2;
this.midY = posY + height/2;
}
public void update(){
if( momentum <= maxfallSpeed){
momentum += fallSpeed;
}
if(isJump && momentum >=0){
momentum = jumpStart;
}
if(posY >= GamePanel.HEIGHT * 3/4){
posY = GamePanel.HEIGHT * 3/4;
if(momentum > 0){
momentum = 0;
}
}
if(posY < 0){
posY = 0;
}
posY += momentum;
midY = (int)posY + height/2;
bound.setLocation((int)posX, (int)posY);
}
public void draw(Graphics2D g){
g.setColor(Color.RED);
g.fillRect((int)posX, (int)posY, width, height);
//draw the player bound
g.setColor(Color.WHITE);
g.drawRect(bound.x, bound.y, bound.width, bound.height);
}
public boolean isJump(){
return isJump;
}
public void setJump(boolean jump){
isJump = jump;
}
public int getMidX(){
return midX;
}
public int getMidY(){
return midY;
}
public Rectangle getBound(){
return bound;
}
}
| 1,622 | 0.652281 | 0.639334 | 88 | 17.431818 | 15.73054 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.090909 | false | false |
12
|
8da5be8410a4966edbb4fec2098c1022c88d01da
| 27,049,704,047,264 |
09ab0d4d4cba51279b111338d283130c1fb64cae
|
/src/main/java/com/sayiamfun/springboot2mybatisdemo/service/impl/TTeacherServiceImpl.java
|
3110f3c16a7660c4a827dc80f7f0fe50da9f34d9
|
[] |
no_license
|
sayiamfun/springboot2-mybatis-demo
|
https://github.com/sayiamfun/springboot2-mybatis-demo
|
37cadb756e922dccb7ed7f755ca38af4658afd91
|
0a1b10e18d27d1bbb8a10a9c3522a463608c94f7
|
refs/heads/master
| 2021-07-10T00:39:17.672000 | 2019-06-24T02:45:04 | 2019-06-24T02:45:04 | 192,281,214 | 0 | 0 | null | false | 2020-09-09T19:16:41 | 2019-06-17T05:35:59 | 2019-06-24T02:46:25 | 2020-09-09T19:16:39 | 582 | 0 | 0 | 2 |
Java
| false | false |
package com.sayiamfun.springboot2mybatisdemo.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sayiamfun.springboot2mybatisdemo.common.requestentity.QueryTeacher;
import com.sayiamfun.springboot2mybatisdemo.common.sql.SqlParam;
import com.sayiamfun.springboot2mybatisdemo.entity.TTeacher;
import com.sayiamfun.springboot2mybatisdemo.mapper.TTeacherMapper;
import com.sayiamfun.springboot2mybatisdemo.service.TTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author sayiamfun
* @since 2019-06-10
*/
@Service
public class TTeacherServiceImpl implements TTeacherService {
@Autowired
private TTeacherMapper teacherMapper;
/**
* 添加教师信息
*
* @param teacher
* @return
*/
@Transactional(rollbackFor = Exception.class)
@Override
public boolean addUser(TTeacher teacher) {
return teacherMapper.insert(teacher)>0;
}
/**
* 更新教师信息
*
* @param teacher
* @return
*/
@Override
public boolean updateUser(TTeacher teacher) {
return teacherMapper.updateTeacher(teacher)>0;
}
/**
* 分页条件查询教师信息
*
* @param pageNum
* @param pageSize
* @param queryTeacher
* @return
*/
@Override
public PageInfo<TTeacher> findAllUser(int pageNum, int pageSize, QueryTeacher queryTeacher) {
PageHelper.startPage(pageNum, pageSize);
List<TTeacher> userList = teacherMapper.selectTeachers(queryTeacher);
PageInfo result = new PageInfo(userList);
return result;
}
/**
* 根据id查询
* @param id
* @return
*/
@Override
public TTeacher selectById(Integer id) {
return teacherMapper.selectById(id);
}
/**
* 根据id删除
* @param sqlParam
* @return
*/
@Override
public boolean deleteByIds(SqlParam sqlParam) {
return teacherMapper.deleteById(sqlParam)>0;
}
}
|
UTF-8
|
Java
| 2,213 |
java
|
TTeacherServiceImpl.java
|
Java
|
[
{
"context": "l.List;\n\n/**\n * <p>\n * 服务实现类\n * </p>\n *\n * @author sayiamfun\n * @since 2019-06-10\n */\n@Service\npublic class TT",
"end": 732,
"score": 0.9996190071105957,
"start": 723,
"tag": "USERNAME",
"value": "sayiamfun"
}
] | null |
[] |
package com.sayiamfun.springboot2mybatisdemo.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sayiamfun.springboot2mybatisdemo.common.requestentity.QueryTeacher;
import com.sayiamfun.springboot2mybatisdemo.common.sql.SqlParam;
import com.sayiamfun.springboot2mybatisdemo.entity.TTeacher;
import com.sayiamfun.springboot2mybatisdemo.mapper.TTeacherMapper;
import com.sayiamfun.springboot2mybatisdemo.service.TTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author sayiamfun
* @since 2019-06-10
*/
@Service
public class TTeacherServiceImpl implements TTeacherService {
@Autowired
private TTeacherMapper teacherMapper;
/**
* 添加教师信息
*
* @param teacher
* @return
*/
@Transactional(rollbackFor = Exception.class)
@Override
public boolean addUser(TTeacher teacher) {
return teacherMapper.insert(teacher)>0;
}
/**
* 更新教师信息
*
* @param teacher
* @return
*/
@Override
public boolean updateUser(TTeacher teacher) {
return teacherMapper.updateTeacher(teacher)>0;
}
/**
* 分页条件查询教师信息
*
* @param pageNum
* @param pageSize
* @param queryTeacher
* @return
*/
@Override
public PageInfo<TTeacher> findAllUser(int pageNum, int pageSize, QueryTeacher queryTeacher) {
PageHelper.startPage(pageNum, pageSize);
List<TTeacher> userList = teacherMapper.selectTeachers(queryTeacher);
PageInfo result = new PageInfo(userList);
return result;
}
/**
* 根据id查询
* @param id
* @return
*/
@Override
public TTeacher selectById(Integer id) {
return teacherMapper.selectById(id);
}
/**
* 根据id删除
* @param sqlParam
* @return
*/
@Override
public boolean deleteByIds(SqlParam sqlParam) {
return teacherMapper.deleteById(sqlParam)>0;
}
}
| 2,213 | 0.685021 | 0.677088 | 88 | 23.352272 | 23.07007 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false |
12
|
6a0e0c1c81d76197a4edf84280172796f8927201
| 28,406,913,736,128 |
824fd88b9461dafb4fe4f7235055f168ed15f7bb
|
/app/src/main/java/com/example/test/Euro.java
|
047b599d9dacc37b98076146add281d50822ece2
|
[] |
no_license
|
DunnRiley/Wallet_Problem_Set
|
https://github.com/DunnRiley/Wallet_Problem_Set
|
26c8b761c57f9dd3a395d41825f92032626168ff
|
63fbf8c904bfc164971f803f32cb3d57ccfcee38
|
refs/heads/master
| 2020-06-18T09:40:03.661000 | 2019-07-10T18:58:08 | 2019-07-10T18:58:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.test;
public class Euro extends Currency {
private int euro;
private int cents;
private int total = euro*100+cents;
public int getEuro(){
return euro;
}
public int getCents(){
return cents;
}
String getCode() {
return "EUR";
}
int getAmount() {
return total;
}
Euro(int euro, int cents) {
this.cents = cents;
this.euro = euro;
}
public void add(Euro other) {
int total = (euro * 100) + (other.getEuro() * 100) + cents + other.getCents();
euro = total / 100;
cents = total % 100;
}
public void subtract(Euro other) {
int total = (euro * 100) - (other.getEuro() * 100) + cents - other.getCents();
euro = total / 100;
cents = total % 100;
}
public void printFormatted(){
System.out.println("$"+ euro+"." + cents);
}
public void change() {
int total = euro * 100 + cents;
int qurters = total / 25;
total -= 25 * qurters;
int dimes = total / 10;
total -= 10 * dimes;
int nickles = total / 5;
total -= nickles * 5;
int pennies = total;
System.out.println(Integer.toString(qurters) + " Qurters " + Integer.toString(dimes) + " Dimes " + Integer.toString(nickles) + " Nickles " + Integer.toString(pennies) + " Pennies ");
}
}
|
UTF-8
|
Java
| 1,410 |
java
|
Euro.java
|
Java
|
[] | null |
[] |
package com.example.test;
public class Euro extends Currency {
private int euro;
private int cents;
private int total = euro*100+cents;
public int getEuro(){
return euro;
}
public int getCents(){
return cents;
}
String getCode() {
return "EUR";
}
int getAmount() {
return total;
}
Euro(int euro, int cents) {
this.cents = cents;
this.euro = euro;
}
public void add(Euro other) {
int total = (euro * 100) + (other.getEuro() * 100) + cents + other.getCents();
euro = total / 100;
cents = total % 100;
}
public void subtract(Euro other) {
int total = (euro * 100) - (other.getEuro() * 100) + cents - other.getCents();
euro = total / 100;
cents = total % 100;
}
public void printFormatted(){
System.out.println("$"+ euro+"." + cents);
}
public void change() {
int total = euro * 100 + cents;
int qurters = total / 25;
total -= 25 * qurters;
int dimes = total / 10;
total -= 10 * dimes;
int nickles = total / 5;
total -= nickles * 5;
int pennies = total;
System.out.println(Integer.toString(qurters) + " Qurters " + Integer.toString(dimes) + " Dimes " + Integer.toString(nickles) + " Nickles " + Integer.toString(pennies) + " Pennies ");
}
}
| 1,410 | 0.539716 | 0.511348 | 59 | 22.898306 | 28.683365 | 190 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.457627 | false | false |
12
|
f9de30f894b1573bda376741333d029c94eba5f3
| 27,633,819,591,537 |
18f90487de2e3351f6ba17b2b69e4e939d77dc43
|
/app/src/main/java/it/giotino/btsensor/SenderThread.java
|
78840b7d98bce9fb52b0cdf22504c436ee745f0c
|
[] |
no_license
|
Giotino/BTSensor
|
https://github.com/Giotino/BTSensor
|
8ab223207d6cdf2632aba457e600742ba515ff6d
|
ee81b7420ce7f66511244a184928a954874b0b4e
|
refs/heads/master
| 2017-05-24T07:06:18.717000 | 2015-01-24T12:53:48 | 2015-01-24T12:53:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package it.giotino.btsensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
/**
* Created by Giotino on 23/01/2015.
*/
public class SenderThread {
public Context context;
public OutputStream streamo;
public Protocol builder = new Protocol();
public SenderThread(Context thisc, OutputStream thiss)
{
context = thisc;
streamo = thiss;
}
public void run()
{
SensorManager mgr = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
if (sensor != null)
{
mgr.registerListener(lightSensorEventListener,
sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
}
SensorEventListener lightSensorEventListener
= new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
String data = "";
if(event.values.length == 1)
{
data = builder.build(event.sensor.getType(), event.values[0]);
}
else if(event.values.length == 3)
{
data = builder.build(event.sensor.getType(), event.values[0], event.values[1], event.values[2]);
}
try
{
streamo.write(data.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
}
};
}
|
UTF-8
|
Java
| 1,939 |
java
|
SenderThread.java
|
Java
|
[
{
"context": "tStream;\nimport java.util.List;\n\n/**\n * Created by Giotino on 23/01/2015.\n */\n\npublic class SenderThread {\n\n",
"end": 322,
"score": 0.9627968668937683,
"start": 315,
"tag": "NAME",
"value": "Giotino"
}
] | null |
[] |
package it.giotino.btsensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
/**
* Created by Giotino on 23/01/2015.
*/
public class SenderThread {
public Context context;
public OutputStream streamo;
public Protocol builder = new Protocol();
public SenderThread(Context thisc, OutputStream thiss)
{
context = thisc;
streamo = thiss;
}
public void run()
{
SensorManager mgr = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
if (sensor != null)
{
mgr.registerListener(lightSensorEventListener,
sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
}
SensorEventListener lightSensorEventListener
= new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
String data = "";
if(event.values.length == 1)
{
data = builder.build(event.sensor.getType(), event.values[0]);
}
else if(event.values.length == 3)
{
data = builder.build(event.sensor.getType(), event.values[0], event.values[1], event.values[2]);
}
try
{
streamo.write(data.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
}
};
}
| 1,939 | 0.577102 | 0.569881 | 73 | 25.561644 | 23.565697 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424658 | false | false |
12
|
e43467cfdf4f1ffd9859bea1557b191fb1c7d943
| 23,132,693,893,063 |
9e48dcb5a3f34f0ff0a1bf9546a1a6b192bbb666
|
/coblood-back-master/src/main/java/com/project/coblood/dao/UserDaoImpl.java
|
f968116978be36d43cb4e572dff8fd1e93615411
|
[] |
no_license
|
geopand/AFDEMP_CB6_TeamProject
|
https://github.com/geopand/AFDEMP_CB6_TeamProject
|
3159bcccf436814e83d80da6a9f10b7de5c54465
|
21ef84a6d5d6c54b60985f074725cd29fa8bd911
|
refs/heads/master
| 2023-03-06T02:06:01.240000 | 2022-04-19T16:02:37 | 2022-04-19T16:02:37 | 192,613,139 | 0 | 0 | null | false | 2023-03-01T04:07:14 | 2019-06-18T21:10:54 | 2022-04-19T16:00:14 | 2023-03-01T04:07:12 | 8,129 | 0 | 0 | 11 |
JavaScript
| false | false |
/*
* 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.project.coblood.dao;
import com.project.coblood.models.Login;
import com.project.coblood.models.Register;
import com.project.coblood.models.Role;
import com.project.coblood.models.User;
import com.project.coblood.models.UserApi;
import com.project.coblood.security.SaltController;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
/**
*
* @author admin
*/
@Component
public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager manager;
@Autowired
DataSource datasource;
@Autowired
JdbcTemplate jdbcTemplate;
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(UserDaoImpl.class);
@Override
public int registerUser(Register user) {
int row;
try {
SaltController util = new SaltController();
String salt = "XQAUgAvlP6ed6JoVBsXQVOMUq79f6M" + user.getUsername().trim();
String password = util.encrypt(user.getPassword(), salt); //TODO
String sql = "insert into users(username, password, email) values(?,?,?)";
row = jdbcTemplate.update(sql, new Object[]{user.getUsername(), password, user.getEmail()});
} catch (DataAccessException e) {
//TODO
row = 0;
LOG.info("SQL error in registerUser");
}
return row;
}
@Override
public User validateUser(Login login) {
List<User> users = new ArrayList<>();
try {
SaltController util = new SaltController();
String salt = "XQAUgAvlP6ed6JoVBsXQVOMUq79f6M" + login.getUsername().trim();
String password = util.encrypt(login.getPassword(), salt); //TODO
String sql = "select * from users where users.username=? and users.password=? and users.deleted=0 and users.banned=0";
users = jdbcTemplate.query(sql, new Object[]{login.getUsername(), password}, new TokenMapper());
} catch (DataAccessException e) {
//TODO
LOG.info("SQL error in validateUser");
}
return users.size() == 1 ? users.get(0) : null;
}
@Override
public UserApi responseUser(User user) {
//TODO exception
UserApi userApi = new UserApi();
try {
userApi.setUserId(user.getUserId());
userApi.setUsername(user.getUsername());
userApi.setRole(user.getRole());
} catch (Exception e) {
//TODO
LOG.info("SQL error in responseUser");
}
return userApi;
}
@Override
public int getUserIdByUsername(String username) {
try {
User user = getUserByUsername(username);
int userId = user.getUserId();
return userId;
} catch (Exception e) {
//TODO
LOG.info("SQL error in getUserIdByUsername");
return 0;
}
}
@Override
public ArrayList<User> getAllUsers() {
//TODO exception
List<User> userList = new ArrayList<>();
try {
String sql = "SELECT * FROM users where users.deleted=0 and users.banned=0";
userList = jdbcTemplate.query(sql, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return (ArrayList<User>) userList;
}
@Override
public int createUser(String username, String password) {
Register user = new Register();
user.setUsername(username);
user.setPassword(password);
int created = registerUser(user);
return created;
}
@Override
public int deleteUser(int userId) {
int row;
try {
String sql = "update users set users.deleted = 1 where users.userId = ?";
row = jdbcTemplate.update(sql, new Object[]{userId});
} catch (DataAccessException e) {
//TODO
row = 0;
LOG.info("SQL error in deleteUser");
}
return row;
}
@Override
public int assignRole(int userId, int roleId) {
int row;
try {
String sql = "update users set users.roleId = ? where users.userId = ?";
row = jdbcTemplate.update(sql, new Object[]{roleId, userId});
} catch (DataAccessException e) {
//TODO
row = 0;
LOG.info("SQL error in deleteUser");
}
return row;
}
@Override
public int authorizedUser(String token) {
List<User> users = new ArrayList<>();
try {
String sql = "select * from tokens, users where tokens.token=?";
users = jdbcTemplate.query(sql, new Object[]{token}, new TokenMapper());
if (users.size() == 1) {
User user = users.get(0);
return user.getRole().getRoleInt();
}
} catch (DataAccessException e) {
//TODO
LOG.info("SQL error in authorizedUser");
}
return 0;
}
@Override
public User getUserByUsername(String username) {
//TODO exception
List<User> usersList = new ArrayList<>();
try {
String sql = "SELECT * FROM users WHERE users.username = ?";
usersList = jdbcTemplate.query(sql, new Object[]{username}, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return usersList.size() == 1 ? usersList.get(0) : null;
}
@Override
public User getUserByEmail(String email) {
//TODO exception
List<User> usersList = new ArrayList<>();
try {
String sql = "SELECT * FROM users WHERE users.email = ?";
usersList = jdbcTemplate.query(sql, new Object[]{email}, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return usersList.size() == 1 ? usersList.get(0) : null;
}
public User getUserById(int userId) {
//TODO exception
List<User> usersList = new ArrayList<>();
try {
String sql = "SELECT * FROM users WHERE users.userId = ?";
usersList = jdbcTemplate.query(sql, new Object[]{userId}, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return usersList.size() == 1 ? usersList.get(0) : null;
}
}
class UserMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUserId(Integer.parseInt(rs.getString("userId")));
user.setFirstname(rs.getString("firstName"));
user.setLastname(rs.getString("lastname"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setPhoneNumber(Integer.parseInt(rs.getString("phoneNumber")));
user.setBloodType(rs.getString("bloodType"));
int roleInt = Integer.parseInt(rs.getString("roleId"));
Role role = new Role(roleInt);
user.setRole(role);
user.setEmail(rs.getString("email"));
return user;
}
}
class TokenMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUserId(Integer.parseInt(rs.getString("userId")));
user.setUsername(rs.getString("username"));
int roleInt = Integer.parseInt(rs.getString("roleId"));
Role role = new Role(roleInt);
user.setRole(role);
return user;
}
}
|
UTF-8
|
Java
| 8,242 |
java
|
UserDaoImpl.java
|
Java
|
[
{
"context": "framework.stereotype.Component;\n\n/**\n *\n * @author admin\n */\n@Component\npublic class UserDaoImpl implement",
"end": 1020,
"score": 0.9972584843635559,
"start": 1015,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "r user = new Register();\n user.setUsername(username);\n user.setPassword(password);\n int",
"end": 4131,
"score": 0.9903013706207275,
"start": 4123,
"tag": "USERNAME",
"value": "username"
},
{
"context": "r.setUsername(username);\n user.setPassword(password);\n int created = registerUser(user);\n\n ",
"end": 4167,
"score": 0.9989063739776611,
"start": 4159,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "stname\"));\n user.setUsername(rs.getString(\"username\"));\n user.setPassword(rs.getString(\"passwo",
"end": 7401,
"score": 0.9979714751243591,
"start": 7393,
"tag": "USERNAME",
"value": "username"
},
{
"context": ".getString(\"username\"));\n user.setPassword(rs.getString(\"password\"));\n user.setPhoneNumber(Integer",
"end": 7443,
"score": 0.9946559071540833,
"start": 7431,
"tag": "PASSWORD",
"value": "rs.getString"
},
{
"context": "ername\"));\n user.setPassword(rs.getString(\"password\"));\n user.setPhoneNumber(Integer.parseInt(",
"end": 7453,
"score": 0.9928800463676453,
"start": 7445,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "serId\")));\n user.setUsername(rs.getString(\"username\"));\n int roleInt = Integer.parseInt(rs.get",
"end": 8075,
"score": 0.9984825253486633,
"start": 8067,
"tag": "USERNAME",
"value": "username"
}
] | 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.project.coblood.dao;
import com.project.coblood.models.Login;
import com.project.coblood.models.Register;
import com.project.coblood.models.Role;
import com.project.coblood.models.User;
import com.project.coblood.models.UserApi;
import com.project.coblood.security.SaltController;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
/**
*
* @author admin
*/
@Component
public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager manager;
@Autowired
DataSource datasource;
@Autowired
JdbcTemplate jdbcTemplate;
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(UserDaoImpl.class);
@Override
public int registerUser(Register user) {
int row;
try {
SaltController util = new SaltController();
String salt = "XQAUgAvlP6ed6JoVBsXQVOMUq79f6M" + user.getUsername().trim();
String password = util.encrypt(user.getPassword(), salt); //TODO
String sql = "insert into users(username, password, email) values(?,?,?)";
row = jdbcTemplate.update(sql, new Object[]{user.getUsername(), password, user.getEmail()});
} catch (DataAccessException e) {
//TODO
row = 0;
LOG.info("SQL error in registerUser");
}
return row;
}
@Override
public User validateUser(Login login) {
List<User> users = new ArrayList<>();
try {
SaltController util = new SaltController();
String salt = "XQAUgAvlP6ed6JoVBsXQVOMUq79f6M" + login.getUsername().trim();
String password = util.encrypt(login.getPassword(), salt); //TODO
String sql = "select * from users where users.username=? and users.password=? and users.deleted=0 and users.banned=0";
users = jdbcTemplate.query(sql, new Object[]{login.getUsername(), password}, new TokenMapper());
} catch (DataAccessException e) {
//TODO
LOG.info("SQL error in validateUser");
}
return users.size() == 1 ? users.get(0) : null;
}
@Override
public UserApi responseUser(User user) {
//TODO exception
UserApi userApi = new UserApi();
try {
userApi.setUserId(user.getUserId());
userApi.setUsername(user.getUsername());
userApi.setRole(user.getRole());
} catch (Exception e) {
//TODO
LOG.info("SQL error in responseUser");
}
return userApi;
}
@Override
public int getUserIdByUsername(String username) {
try {
User user = getUserByUsername(username);
int userId = user.getUserId();
return userId;
} catch (Exception e) {
//TODO
LOG.info("SQL error in getUserIdByUsername");
return 0;
}
}
@Override
public ArrayList<User> getAllUsers() {
//TODO exception
List<User> userList = new ArrayList<>();
try {
String sql = "SELECT * FROM users where users.deleted=0 and users.banned=0";
userList = jdbcTemplate.query(sql, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return (ArrayList<User>) userList;
}
@Override
public int createUser(String username, String password) {
Register user = new Register();
user.setUsername(username);
user.setPassword(<PASSWORD>);
int created = registerUser(user);
return created;
}
@Override
public int deleteUser(int userId) {
int row;
try {
String sql = "update users set users.deleted = 1 where users.userId = ?";
row = jdbcTemplate.update(sql, new Object[]{userId});
} catch (DataAccessException e) {
//TODO
row = 0;
LOG.info("SQL error in deleteUser");
}
return row;
}
@Override
public int assignRole(int userId, int roleId) {
int row;
try {
String sql = "update users set users.roleId = ? where users.userId = ?";
row = jdbcTemplate.update(sql, new Object[]{roleId, userId});
} catch (DataAccessException e) {
//TODO
row = 0;
LOG.info("SQL error in deleteUser");
}
return row;
}
@Override
public int authorizedUser(String token) {
List<User> users = new ArrayList<>();
try {
String sql = "select * from tokens, users where tokens.token=?";
users = jdbcTemplate.query(sql, new Object[]{token}, new TokenMapper());
if (users.size() == 1) {
User user = users.get(0);
return user.getRole().getRoleInt();
}
} catch (DataAccessException e) {
//TODO
LOG.info("SQL error in authorizedUser");
}
return 0;
}
@Override
public User getUserByUsername(String username) {
//TODO exception
List<User> usersList = new ArrayList<>();
try {
String sql = "SELECT * FROM users WHERE users.username = ?";
usersList = jdbcTemplate.query(sql, new Object[]{username}, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return usersList.size() == 1 ? usersList.get(0) : null;
}
@Override
public User getUserByEmail(String email) {
//TODO exception
List<User> usersList = new ArrayList<>();
try {
String sql = "SELECT * FROM users WHERE users.email = ?";
usersList = jdbcTemplate.query(sql, new Object[]{email}, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return usersList.size() == 1 ? usersList.get(0) : null;
}
public User getUserById(int userId) {
//TODO exception
List<User> usersList = new ArrayList<>();
try {
String sql = "SELECT * FROM users WHERE users.userId = ?";
usersList = jdbcTemplate.query(sql, new Object[]{userId}, new UserMapper());
} catch (DataAccessException e) {
//TODO
}
return usersList.size() == 1 ? usersList.get(0) : null;
}
}
class UserMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUserId(Integer.parseInt(rs.getString("userId")));
user.setFirstname(rs.getString("firstName"));
user.setLastname(rs.getString("lastname"));
user.setUsername(rs.getString("username"));
user.setPassword(<PASSWORD>("<PASSWORD>"));
user.setPhoneNumber(Integer.parseInt(rs.getString("phoneNumber")));
user.setBloodType(rs.getString("bloodType"));
int roleInt = Integer.parseInt(rs.getString("roleId"));
Role role = new Role(roleInt);
user.setRole(role);
user.setEmail(rs.getString("email"));
return user;
}
}
class TokenMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setUserId(Integer.parseInt(rs.getString("userId")));
user.setUsername(rs.getString("username"));
int roleInt = Integer.parseInt(rs.getString("roleId"));
Role role = new Role(roleInt);
user.setRole(role);
return user;
}
}
| 8,244 | 0.602402 | 0.598277 | 290 | 27.420691 | 26.361851 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.496552 | false | false |
12
|
c998cbb39be87321bf4971149af9700575e4d8f6
| 1,666,447,319,004 |
03dc79ff965d35c6b288c3931e97590e536e872a
|
/src/main/java/by/belohvostik/innovationpak/services/DefProtocolService.java
|
cfd13c7dbfd87f630b6e613003bbd64dd0c6ed06
|
[] |
no_license
|
batget/InnovationPak
|
https://github.com/batget/InnovationPak
|
601a48275bfe4e132ef9302ca5f3ef571ea0a11c
|
76a3a89d53eef6aacba50680a1bf2f7e1c44bfa6
|
refs/heads/master
| 2023-08-28T07:21:49.874000 | 2021-11-07T13:04:51 | 2021-11-07T13:04:51 | 415,901,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package by.belohvostik.innovationpak.services;
import by.belohvostik.innovationpak.models.Protocol;
import by.belohvostik.innovationpak.repository.ProtocolRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class DefProtocolService implements ProtocolService{
private final ProtocolRepository protocolRepository;
@Override
public Protocol getProtocolFindById(Integer id) {
return protocolRepository.getById(id);
}
@Override
public List<Protocol> readAll() {
return protocolRepository.findAll();
}
@Override
public Protocol save(Protocol protocol) {
return protocolRepository.save(protocol);
}
@Override
public Protocol update(Protocol protocol) {
return protocolRepository.saveAndFlush(protocol);
}
@Override
public void deleteById(int id) {
protocolRepository.deleteById(id);
}
}
|
UTF-8
|
Java
| 1,006 |
java
|
DefProtocolService.java
|
Java
|
[] | null |
[] |
package by.belohvostik.innovationpak.services;
import by.belohvostik.innovationpak.models.Protocol;
import by.belohvostik.innovationpak.repository.ProtocolRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class DefProtocolService implements ProtocolService{
private final ProtocolRepository protocolRepository;
@Override
public Protocol getProtocolFindById(Integer id) {
return protocolRepository.getById(id);
}
@Override
public List<Protocol> readAll() {
return protocolRepository.findAll();
}
@Override
public Protocol save(Protocol protocol) {
return protocolRepository.save(protocol);
}
@Override
public Protocol update(Protocol protocol) {
return protocolRepository.saveAndFlush(protocol);
}
@Override
public void deleteById(int id) {
protocolRepository.deleteById(id);
}
}
| 1,006 | 0.744533 | 0.744533 | 41 | 23.536585 | 22.101868 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.292683 | false | false |
12
|
03968d3b30c9e89e7077f78864c8acffe10f1ddd
| 31,456,340,487,035 |
8331bb3bfdd2926801f437a94a6fd8094b1593b3
|
/src/com/zhqh/sort/merge/RecursionMergeSort.java
|
8f4d82d6d73bbaadc438a2a741a4574e60a46673
|
[] |
no_license
|
zhqh9016/Algorithm
|
https://github.com/zhqh9016/Algorithm
|
bac2c46c3ccde30356e8bc542f0d4bef412dfc1c
|
aab655ba9ca995a284859fc696feb976d59b8069
|
refs/heads/master
| 2021-01-20T05:36:56.802000 | 2017-03-04T09:50:02 | 2017-03-04T09:50:02 | 83,859,972 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhqh.sort.merge;
import java.util.Random;
import org.junit.Test;
/**
* 使用递归方式实现归并排序
*
* @author zhqh
*
*/
public class RecursionMergeSort {
public static void main(String[] args) {
int seed = 2000000;
// int[] source = {8,9,37,40,8,12,83,6,48,7,26,34,72,3,48,7};
int[] source = new int[seed];
Random random = new Random();
for (int i = 0; i < seed; i++) {
int nextInt = random.nextInt(seed);
source[i] = nextInt;
}
long start = System.currentTimeMillis();
int[] mergeSort = mergeSort(source);
long end = System.currentTimeMillis();
for (int j = 1; j < mergeSort.length; j++) {
if (mergeSort[j - 1] > mergeSort[j]) {
System.out.println("排序结果不正确");
return;
}
}
System.out.println("对" + seed + "个数进行排序用时" + (end - start) + "ms");
}
/**
* 归并排序实现
*
* @param source
* @return
*/
public static int[] mergeSort(int[] source) {
// 如果当前数组只有一个元素,那么不需要进行排序直接将数组返回
int sourceLen = source.length;
if (sourceLen <= 1) {
return source;
}
// 将源数组从中间拆分成两个数组
int mid = sourceLen / 2;
int[] sourceA = new int[mid];
int[] sourceB = new int[sourceLen - mid];
for (int i = 0; i < mid; i++) {
sourceA[i] = source[i];
}
for (int j = 0; j < sourceLen - mid; j++) {
sourceB[j] = source[mid + j];
}
// 递归调用对拆分后的两个数组进行归并排序
int[] mergeSortLeft = mergeSort(sourceA);
int[] mergeSortRigth = mergeSort(sourceB);
// 拆分后的数组排序完成后合并为一个有序数组
int[] merge = MergeTwoSortedArray.merge(mergeSortLeft, mergeSortRigth);
return merge;
}
@Test
public void testMergeSortCopyFromInternet() {
int seed = 20000000;
int[] source = new int[seed];
Random random = new Random();
for (int i = 0; i < seed; i++) {
int nextInt = random.nextInt(seed);
source[i] = nextInt;
}
long start = System.currentTimeMillis();
mergeSortCopyFromInternet(source, 0, seed - 1);
long end = System.currentTimeMillis();
for (int j = 1; j < source.length; j++) {
if (source[j - 1] > source[j]) {
System.out.println("排序结果不正确");
return;
}
}
System.out.println("对" + seed + "个数进行排序用时" + (end - start) + "ms");
}
/**
* 从网上查找的递归归并实现
*
* @param source
* @param begin
* @param end
*/
public static void mergeSortCopyFromInternet(int[] source, int begin, int end) {
int middle = (end + begin) / 2;
if (begin < end) {
mergeSortCopyFromInternet(source, begin, middle);
mergeSortCopyFromInternet(source, middle + 1, end);
MergeTwoSortedArray.mergeCopyFromInternet(source, begin, middle, end);
}
}
}
|
UTF-8
|
Java
| 2,817 |
java
|
RecursionMergeSort.java
|
Java
|
[
{
"context": "rg.junit.Test;\n\n/**\n * 使用递归方式实现归并排序\n * \n * @author zhqh\n *\n */\npublic class RecursionMergeSort {\n\n\tpublic",
"end": 119,
"score": 0.9996285438537598,
"start": 115,
"tag": "USERNAME",
"value": "zhqh"
}
] | null |
[] |
package com.zhqh.sort.merge;
import java.util.Random;
import org.junit.Test;
/**
* 使用递归方式实现归并排序
*
* @author zhqh
*
*/
public class RecursionMergeSort {
public static void main(String[] args) {
int seed = 2000000;
// int[] source = {8,9,37,40,8,12,83,6,48,7,26,34,72,3,48,7};
int[] source = new int[seed];
Random random = new Random();
for (int i = 0; i < seed; i++) {
int nextInt = random.nextInt(seed);
source[i] = nextInt;
}
long start = System.currentTimeMillis();
int[] mergeSort = mergeSort(source);
long end = System.currentTimeMillis();
for (int j = 1; j < mergeSort.length; j++) {
if (mergeSort[j - 1] > mergeSort[j]) {
System.out.println("排序结果不正确");
return;
}
}
System.out.println("对" + seed + "个数进行排序用时" + (end - start) + "ms");
}
/**
* 归并排序实现
*
* @param source
* @return
*/
public static int[] mergeSort(int[] source) {
// 如果当前数组只有一个元素,那么不需要进行排序直接将数组返回
int sourceLen = source.length;
if (sourceLen <= 1) {
return source;
}
// 将源数组从中间拆分成两个数组
int mid = sourceLen / 2;
int[] sourceA = new int[mid];
int[] sourceB = new int[sourceLen - mid];
for (int i = 0; i < mid; i++) {
sourceA[i] = source[i];
}
for (int j = 0; j < sourceLen - mid; j++) {
sourceB[j] = source[mid + j];
}
// 递归调用对拆分后的两个数组进行归并排序
int[] mergeSortLeft = mergeSort(sourceA);
int[] mergeSortRigth = mergeSort(sourceB);
// 拆分后的数组排序完成后合并为一个有序数组
int[] merge = MergeTwoSortedArray.merge(mergeSortLeft, mergeSortRigth);
return merge;
}
@Test
public void testMergeSortCopyFromInternet() {
int seed = 20000000;
int[] source = new int[seed];
Random random = new Random();
for (int i = 0; i < seed; i++) {
int nextInt = random.nextInt(seed);
source[i] = nextInt;
}
long start = System.currentTimeMillis();
mergeSortCopyFromInternet(source, 0, seed - 1);
long end = System.currentTimeMillis();
for (int j = 1; j < source.length; j++) {
if (source[j - 1] > source[j]) {
System.out.println("排序结果不正确");
return;
}
}
System.out.println("对" + seed + "个数进行排序用时" + (end - start) + "ms");
}
/**
* 从网上查找的递归归并实现
*
* @param source
* @param begin
* @param end
*/
public static void mergeSortCopyFromInternet(int[] source, int begin, int end) {
int middle = (end + begin) / 2;
if (begin < end) {
mergeSortCopyFromInternet(source, begin, middle);
mergeSortCopyFromInternet(source, middle + 1, end);
MergeTwoSortedArray.mergeCopyFromInternet(source, begin, middle, end);
}
}
}
| 2,817 | 0.622679 | 0.601343 | 116 | 20.818966 | 20.026533 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.146552 | false | false |
12
|
5aba1a878b3cf23b1e09b5b05eda87164374f5a6
| 31,456,340,488,644 |
abeced0b8f4c54142546436d03c91e58cd0453d4
|
/src/java/com/ctc/onlineshoping/dao/GetOrderDetailDAO.java
|
ec14d9936a6fdb754a82f64d4be7aa79be4b5dd5
|
[] |
no_license
|
singhgulshan/onlineshoping
|
https://github.com/singhgulshan/onlineshoping
|
f75ed73d32af709ced55b7358521236f36c38a55
|
17a48324a639138d606d59f29b381c241ec4182e
|
refs/heads/master
| 2020-03-25T23:21:43.193000 | 2018-08-10T10:24:50 | 2018-08-10T10:24:50 | 144,271,117 | 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.ctc.onlineshoping.dao;
import com.ctc.onlineshoping.util.DBUtil;
import com.ctc.onlineshoping.vo.OrderStatusVO;
import com.ctc.onlineshoping.vo.ProductDetailsVO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author Gulshan
*/
public class GetOrderDetailDAO {
public ArrayList<OrderStatusVO> customerOrderStatus(String username){
ArrayList<OrderStatusVO> list = new ArrayList<>();
try{
DBUtil util = new DBUtil();
Connection con = util.getDBConnection();
Statement stmt = con.createStatement();
String query = "select * from orderstatus where customerid='"+username+"';";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
rs.beforeFirst();
while(rs.next()){
OrderStatusVO status = new OrderStatusVO();
status.setCustomerid(rs.getString(4));
status.setMerchantid(rs.getString(3));
status.setOrderid(rs.getString(2));
status.setOrderstatus(rs.getString(5));
status.setTotalamount(rs.getDouble(6));
status.setShopname(rs.getString(7));
list.add(status);
}
}
}
catch(SQLException e){
e.printStackTrace();
}
return list;
}
public ArrayList<ProductDetailsVO> orderProductDetail(String orderid){
ArrayList<ProductDetailsVO> products = new ArrayList<>();
try{
DBUtil util = new DBUtil();
Connection con = util.getDBConnection();
Statement stmt = con.createStatement();
String query = "select * from orderdetail where orderid='"+orderid+"';";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
ProductDetailsVO detail = new ProductDetailsVO();
detail.setProductname(rs.getString(3));
detail.setQuantity(rs.getInt(4));
detail.setPrice(rs.getDouble(5));
detail.setTotal(rs.getDouble(6));
products.add(detail);
}
}
catch(SQLException e){
e.printStackTrace();
}
return products;
}
public ArrayList<OrderStatusVO> merchantOrderStatus(String username){
ArrayList<OrderStatusVO> list = new ArrayList<>();
try{
DBUtil util = new DBUtil();
Connection con = util.getDBConnection();
Statement stmt = con.createStatement();
String query = "select * from orderstatus where merchantid='"+username+"';";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
rs.beforeFirst();
while(rs.next()){
OrderStatusVO status = new OrderStatusVO();
status.setCustomerid(rs.getString(4));
status.setMerchantid(rs.getString(3));
status.setOrderid(rs.getString(2));
status.setOrderstatus(rs.getString(5));
status.setTotalamount(rs.getDouble(6));
status.setShopname(rs.getString(7));
status.setCustomername(rs.getString(8));
list.add(status);
}
}
}
catch(SQLException e){
e.printStackTrace();
}
return list;
}
}
|
UTF-8
|
Java
| 4,126 |
java
|
GetOrderDetailDAO.java
|
Java
|
[
{
"context": "nt;\nimport java.util.ArrayList;\n\n/**\n *\n * @author Gulshan\n */\npublic class GetOrderDetailDAO {\n \n pub",
"end": 527,
"score": 0.998837947845459,
"start": 520,
"tag": "NAME",
"value": "Gulshan"
}
] | 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.ctc.onlineshoping.dao;
import com.ctc.onlineshoping.util.DBUtil;
import com.ctc.onlineshoping.vo.OrderStatusVO;
import com.ctc.onlineshoping.vo.ProductDetailsVO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author Gulshan
*/
public class GetOrderDetailDAO {
public ArrayList<OrderStatusVO> customerOrderStatus(String username){
ArrayList<OrderStatusVO> list = new ArrayList<>();
try{
DBUtil util = new DBUtil();
Connection con = util.getDBConnection();
Statement stmt = con.createStatement();
String query = "select * from orderstatus where customerid='"+username+"';";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
rs.beforeFirst();
while(rs.next()){
OrderStatusVO status = new OrderStatusVO();
status.setCustomerid(rs.getString(4));
status.setMerchantid(rs.getString(3));
status.setOrderid(rs.getString(2));
status.setOrderstatus(rs.getString(5));
status.setTotalamount(rs.getDouble(6));
status.setShopname(rs.getString(7));
list.add(status);
}
}
}
catch(SQLException e){
e.printStackTrace();
}
return list;
}
public ArrayList<ProductDetailsVO> orderProductDetail(String orderid){
ArrayList<ProductDetailsVO> products = new ArrayList<>();
try{
DBUtil util = new DBUtil();
Connection con = util.getDBConnection();
Statement stmt = con.createStatement();
String query = "select * from orderdetail where orderid='"+orderid+"';";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
ProductDetailsVO detail = new ProductDetailsVO();
detail.setProductname(rs.getString(3));
detail.setQuantity(rs.getInt(4));
detail.setPrice(rs.getDouble(5));
detail.setTotal(rs.getDouble(6));
products.add(detail);
}
}
catch(SQLException e){
e.printStackTrace();
}
return products;
}
public ArrayList<OrderStatusVO> merchantOrderStatus(String username){
ArrayList<OrderStatusVO> list = new ArrayList<>();
try{
DBUtil util = new DBUtil();
Connection con = util.getDBConnection();
Statement stmt = con.createStatement();
String query = "select * from orderstatus where merchantid='"+username+"';";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
rs.beforeFirst();
while(rs.next()){
OrderStatusVO status = new OrderStatusVO();
status.setCustomerid(rs.getString(4));
status.setMerchantid(rs.getString(3));
status.setOrderid(rs.getString(2));
status.setOrderstatus(rs.getString(5));
status.setTotalamount(rs.getDouble(6));
status.setShopname(rs.getString(7));
status.setCustomername(rs.getString(8));
list.add(status);
}
}
}
catch(SQLException e){
e.printStackTrace();
}
return list;
}
}
| 4,126 | 0.516481 | 0.512361 | 130 | 30.738462 | 22.927496 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492308 | false | false |
12
|
5d70a185e3d2957cad3beff8ea318280af25a763
| 4,260,607,615,493 |
a08ccfa4ec911692088f4c9e0c3cc88b30e8305c
|
/api/microservice-job/job-commons/src/main/java/com/neptune/voyeur/job/dao/JobDAO.java
|
8f733b5b7a01d7047fde11310614049e4ae94e5e
|
[] |
no_license
|
rafaelrabeloit/voyeur
|
https://github.com/rafaelrabeloit/voyeur
|
694a5d292929a56df821a49b884830e611dc44fd
|
2d65d10a8c5adeaf1ba17c57b317e443de556c0e
|
refs/heads/master
| 2020-04-27T08:15:43.228000 | 2015-11-15T21:01:03 | 2015-11-15T21:01:03 | 174,163,970 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.neptune.voyeur.job.dao;
import com.neptune.templates.microservice.dao.DAOTemplate;
import com.neptune.voyeur.job.domain.Job;
public interface JobDAO extends DAOTemplate<Job> {
public Job free(Job job);
public void run(Job job);
}
|
UTF-8
|
Java
| 256 |
java
|
JobDAO.java
|
Java
|
[] | null |
[] |
package com.neptune.voyeur.job.dao;
import com.neptune.templates.microservice.dao.DAOTemplate;
import com.neptune.voyeur.job.domain.Job;
public interface JobDAO extends DAOTemplate<Job> {
public Job free(Job job);
public void run(Job job);
}
| 256 | 0.757813 | 0.757813 | 10 | 23.799999 | 21.117765 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false |
12
|
cf3fc1a8eaab430ca8d658e6a991b99c86c575a4
| 360,777,314,556 |
3d0555b1a5c2bcfee6d8dd68de4b9cf949146bf8
|
/word-of-mouth/src/main/java/com/koubei/request/CardRequest.java
|
3885c10a86fce847d9846a499b7d6415edf78c33
|
[] |
no_license
|
lianzhirong/word-of-mouth
|
https://github.com/lianzhirong/word-of-mouth
|
b8c1b689329fcb63032768dffc24ffe5f106612e
|
57c115a846cce2da2c42288c2580ccda64a576cf
|
refs/heads/master
| 2020-03-23T06:42:01.994000 | 2018-08-06T03:22:34 | 2018-08-06T03:22:34 | 141,224,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.koubei.request;
import com.koubei.entity.Card;
public class CardRequest extends Card{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer currentPage;
private Integer pageSize = 10;
private String templateId;
private String marketId;
private String mobile;
private String requestId;
private String accessToken;
private String out_String;
/***************渠道************************/
private Integer qu_id;
private String type;
private String name;
/*********************************/
private String requiredstr;
private String optionalstr;
private String tenantId;
private String tenantType;
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getQu_id() {
return qu_id;
}
public void setQu_id(Integer qu_id) {
this.qu_id = qu_id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getMarketId() {
return marketId;
}
public void setMarketId(String marketId) {
this.marketId = marketId;
}
public String getRequiredstr() {
return requiredstr;
}
public void setRequiredstr(String requiredstr) {
this.requiredstr = requiredstr;
}
public String getOptionalstr() {
return optionalstr;
}
public void setOptionalstr(String optionalstr) {
this.optionalstr = optionalstr;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getOut_String() {
return out_String;
}
public void setOut_String(String out_String) {
this.out_String = out_String;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantType() {
return tenantType;
}
public void setTenantType(String tenantType) {
this.tenantType = tenantType;
}
}
|
UTF-8
|
Java
| 2,823 |
java
|
CardRequest.java
|
Java
|
[] | null |
[] |
package com.koubei.request;
import com.koubei.entity.Card;
public class CardRequest extends Card{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer currentPage;
private Integer pageSize = 10;
private String templateId;
private String marketId;
private String mobile;
private String requestId;
private String accessToken;
private String out_String;
/***************渠道************************/
private Integer qu_id;
private String type;
private String name;
/*********************************/
private String requiredstr;
private String optionalstr;
private String tenantId;
private String tenantType;
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getQu_id() {
return qu_id;
}
public void setQu_id(Integer qu_id) {
this.qu_id = qu_id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getMarketId() {
return marketId;
}
public void setMarketId(String marketId) {
this.marketId = marketId;
}
public String getRequiredstr() {
return requiredstr;
}
public void setRequiredstr(String requiredstr) {
this.requiredstr = requiredstr;
}
public String getOptionalstr() {
return optionalstr;
}
public void setOptionalstr(String optionalstr) {
this.optionalstr = optionalstr;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getOut_String() {
return out_String;
}
public void setOut_String(String out_String) {
this.out_String = out_String;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantType() {
return tenantType;
}
public void setTenantType(String tenantType) {
this.tenantType = tenantType;
}
}
| 2,823 | 0.658744 | 0.65768 | 135 | 18.881481 | 15.760265 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.422222 | false | false |
12
|
d0fa1f6b32be9d0b8b7f166ea3e7769b1c3b116e
| 31,980,326,510,042 |
3b63938ca4b3d0afea127b1105a862405ed3305e
|
/src/main/java/behavioral/state/StateStarST.java
|
e59e71273c6bc9f270fa2ecb1e7ce27faf80819c
|
[] |
no_license
|
experqs/DesignPattern
|
https://github.com/experqs/DesignPattern
|
51c9b935206675c3370a94be24d5eb3aa6496c62
|
a48a4e70c53cd43eb28b860fd47ba23b016efffc
|
refs/heads/master
| 2020-03-22T05:16:33.669000 | 2018-08-29T08:04:49 | 2018-08-29T08:04:49 | 139,425,721 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package behavioral.state;
/**
* 股票状态为:*ST
* 状态转换条件:为了简化处理,这里约定:当*ST股票扭亏为盈时,其状态即转为正常;当*ST股票继续亏损时,其状态保持为*ST
*/
public class StateStarST implements State {
@Override
public void handle(Stock stock) {
System.out.print("此前股票状态为【*ST 】...");
if (stock.getLossYears() == 0) {
stock.setState(new StateNormal());
System.out.println("这次扭亏为盈,因此下一状态转为【正常】...");
} else {
stock.setState(new StateStarST());
System.out.println("这次继续亏损,因此下一状态继续为【*ST】...");
}
}
}
|
UTF-8
|
Java
| 753 |
java
|
StateStarST.java
|
Java
|
[] | null |
[] |
package behavioral.state;
/**
* 股票状态为:*ST
* 状态转换条件:为了简化处理,这里约定:当*ST股票扭亏为盈时,其状态即转为正常;当*ST股票继续亏损时,其状态保持为*ST
*/
public class StateStarST implements State {
@Override
public void handle(Stock stock) {
System.out.print("此前股票状态为【*ST 】...");
if (stock.getLossYears() == 0) {
stock.setState(new StateNormal());
System.out.println("这次扭亏为盈,因此下一状态转为【正常】...");
} else {
stock.setState(new StateStarST());
System.out.println("这次继续亏损,因此下一状态继续为【*ST】...");
}
}
}
| 753 | 0.583486 | 0.581651 | 21 | 24.952381 | 21.979376 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
12
|
f4d15845b9120d938dffd1c86f095f4b08d4f2ab
| 1,314,259,994,642 |
4251a7fbf953863270878ab39dfa6239086e78eb
|
/Object Oriented Design/TweetClassification/TweetClassification.java
|
b6daac7423dc1f639260254a37ca3eb50a357dfd
|
[] |
no_license
|
JonKasper/Portfolio
|
https://github.com/JonKasper/Portfolio
|
9ff63b0ac8215d0609ddf37f7fd9946b473af96e
|
2ebe0db2f4ae8e6a37b6ff2815ce40f372819f5a
|
refs/heads/master
| 2021-01-02T00:37:21.831000 | 2020-02-10T03:30:32 | 2020-02-10T03:30:32 | 239,413,584 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.lang.String;
/**
* Write a description of class TweetClassification here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TweetClassification
{
public static void main(String[] args) throws IOException{
int wordCount = 0, posCount = 0, negCount = 0;
int neg = 0, pos = 4, neutral = 2;
int correctClass = 0, wrongClass = 0, tweetNum = 0;
double accuracy = 0;
boolean correct = true;
Scanner kbInput = new Scanner(System.in);
System.out.println("Provide the file path and extension for the positive word file.");
String fName = kbInput.nextLine();
File file = new File(fName);
System.out.println();
while (!file.exists()) {
System.out.println("Current pathway does not lead to a file.");
System.out.println("Please check and re-enter the pathway.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
}
Scanner positiveFile = new Scanner(new FileReader(file));
HashSet<String> positive = new HashSet<String>();
while (positiveFile.hasNextLine()) {
String word = positiveFile.nextLine();
if (word.length() > 0) {
if (!word.startsWith(";")) {
positive.add(word);
wordCount++;
}
}
}
System.out.println("Positive word file has been read.");
System.out.println("Number of words read: " + wordCount + "\n");
wordCount = 0;
System.out.println("Provide the file path and extension for the negative word file.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
while (!file.exists()) {
System.out.println("Current pathway does not lead to a file.");
System.out.println("Please check and re-enter the pathway.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
}
Scanner negativeFile = new Scanner(new FileReader(file));
HashSet<String> negative = new HashSet<String>();
while (negativeFile.hasNextLine()) {
String word = negativeFile.nextLine();
if (word.length() > 0) {
if(!word.startsWith(";")) {
negative.add(word);
wordCount++;
}
}
}
System.out.println("Negative word file has been read.");
System.out.println("Number of words read: " + wordCount + "\n");
wordCount = 0;
System.out.println("Provide the file path and extension for the Twitter file.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
while (!file.exists()) {
System.out.println("Current pathway does not lead to a file.");
System.out.println("Please check and re-enter the pathway.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
}
Scanner tweetFile = new Scanner(new FileReader(file));
String line = null;
ArrayList<Integer> csvClassification = new ArrayList<Integer>();
ArrayList<Integer> progClassification = new ArrayList<Integer>();
while (tweetFile.hasNextLine()) {
line = tweetFile.nextLine();
String[] temp = line.split("\",\"");
String tweet = temp[5];
if (temp.length > 6) {
for (int i = 6; i < temp.length; i++) {
tweet += " " + temp[i];
}
}
temp[0] = temp[0].replaceAll("\"", "");
temp[5] = temp[5].replaceAll("\"", "");
csvClassification.add(Integer.parseInt(temp[0]));
tweet = tweet.replaceAll("\\p{Punct}","").toLowerCase();
String[] tweetComp = tweet.split("\\s");
for (int i = 0; i < tweetComp.length; i++) {
if (positive.contains(tweetComp[i]))
posCount++;
else if (negative.contains(tweetComp[i]))
negCount++;
}
if (posCount == 0 && negCount == 0)
progClassification.add(neutral);
else if (posCount > negCount)
progClassification.add(pos);
else if (negCount > posCount)
progClassification.add(neg);
else if (negCount == posCount)
progClassification.add(neg);
posCount = 0;
negCount = 0;
System.out.println("Tweet: \n" + temp[5]);
System.out.println("Real label: " + csvClassification.get(tweetNum));
System.out.println("Predicted label: " + progClassification.get(tweetNum));
if (csvClassification.get(tweetNum).equals(progClassification.get(tweetNum))) {
correctClass++;
correct = true;
System.out.println("Correctly classified: " + correct + "\n");
}
else {
wrongClass++;
correct = false;
System.out.println("Correctly classified: " + correct + "\n");
}
tweetNum++;
}
System.out.println("Correctly Classified Tweets: " + correctClass);
System.out.println("Incorrectly Classified Tweets: " + wrongClass + "\n");
accuracy = ((float)correctClass / tweetNum) * 100;
if (wrongClass == 0) {
accuracy = 100.00;
}
System.out.print("Accuracy: ");
System.out.printf("%.2f", accuracy);
System.out.println("%");
}
}
|
UTF-8
|
Java
| 6,250 |
java
|
TweetClassification.java
|
Java
|
[] | null |
[] |
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.lang.String;
/**
* Write a description of class TweetClassification here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TweetClassification
{
public static void main(String[] args) throws IOException{
int wordCount = 0, posCount = 0, negCount = 0;
int neg = 0, pos = 4, neutral = 2;
int correctClass = 0, wrongClass = 0, tweetNum = 0;
double accuracy = 0;
boolean correct = true;
Scanner kbInput = new Scanner(System.in);
System.out.println("Provide the file path and extension for the positive word file.");
String fName = kbInput.nextLine();
File file = new File(fName);
System.out.println();
while (!file.exists()) {
System.out.println("Current pathway does not lead to a file.");
System.out.println("Please check and re-enter the pathway.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
}
Scanner positiveFile = new Scanner(new FileReader(file));
HashSet<String> positive = new HashSet<String>();
while (positiveFile.hasNextLine()) {
String word = positiveFile.nextLine();
if (word.length() > 0) {
if (!word.startsWith(";")) {
positive.add(word);
wordCount++;
}
}
}
System.out.println("Positive word file has been read.");
System.out.println("Number of words read: " + wordCount + "\n");
wordCount = 0;
System.out.println("Provide the file path and extension for the negative word file.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
while (!file.exists()) {
System.out.println("Current pathway does not lead to a file.");
System.out.println("Please check and re-enter the pathway.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
}
Scanner negativeFile = new Scanner(new FileReader(file));
HashSet<String> negative = new HashSet<String>();
while (negativeFile.hasNextLine()) {
String word = negativeFile.nextLine();
if (word.length() > 0) {
if(!word.startsWith(";")) {
negative.add(word);
wordCount++;
}
}
}
System.out.println("Negative word file has been read.");
System.out.println("Number of words read: " + wordCount + "\n");
wordCount = 0;
System.out.println("Provide the file path and extension for the Twitter file.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
while (!file.exists()) {
System.out.println("Current pathway does not lead to a file.");
System.out.println("Please check and re-enter the pathway.");
fName = kbInput.nextLine();
file = new File(fName);
System.out.println();
}
Scanner tweetFile = new Scanner(new FileReader(file));
String line = null;
ArrayList<Integer> csvClassification = new ArrayList<Integer>();
ArrayList<Integer> progClassification = new ArrayList<Integer>();
while (tweetFile.hasNextLine()) {
line = tweetFile.nextLine();
String[] temp = line.split("\",\"");
String tweet = temp[5];
if (temp.length > 6) {
for (int i = 6; i < temp.length; i++) {
tweet += " " + temp[i];
}
}
temp[0] = temp[0].replaceAll("\"", "");
temp[5] = temp[5].replaceAll("\"", "");
csvClassification.add(Integer.parseInt(temp[0]));
tweet = tweet.replaceAll("\\p{Punct}","").toLowerCase();
String[] tweetComp = tweet.split("\\s");
for (int i = 0; i < tweetComp.length; i++) {
if (positive.contains(tweetComp[i]))
posCount++;
else if (negative.contains(tweetComp[i]))
negCount++;
}
if (posCount == 0 && negCount == 0)
progClassification.add(neutral);
else if (posCount > negCount)
progClassification.add(pos);
else if (negCount > posCount)
progClassification.add(neg);
else if (negCount == posCount)
progClassification.add(neg);
posCount = 0;
negCount = 0;
System.out.println("Tweet: \n" + temp[5]);
System.out.println("Real label: " + csvClassification.get(tweetNum));
System.out.println("Predicted label: " + progClassification.get(tweetNum));
if (csvClassification.get(tweetNum).equals(progClassification.get(tweetNum))) {
correctClass++;
correct = true;
System.out.println("Correctly classified: " + correct + "\n");
}
else {
wrongClass++;
correct = false;
System.out.println("Correctly classified: " + correct + "\n");
}
tweetNum++;
}
System.out.println("Correctly Classified Tweets: " + correctClass);
System.out.println("Incorrectly Classified Tweets: " + wrongClass + "\n");
accuracy = ((float)correctClass / tweetNum) * 100;
if (wrongClass == 0) {
accuracy = 100.00;
}
System.out.print("Accuracy: ");
System.out.printf("%.2f", accuracy);
System.out.println("%");
}
}
| 6,250 | 0.50496 | 0.49888 | 176 | 34.511364 | 23.276741 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619318 | false | false |
12
|
c5afcab395a2280efca35131026a5c04798e9d18
| 19,499,151,556,414 |
09b67e13e300ae24593cf195d77e65e230c63f28
|
/common/src/main/java/com/xxc/dev/common/callback/CallBack2.java
|
b292825082f4cd5557e0e254ad89850294a869c7
|
[] |
no_license
|
SevenNight2012/DevLibrary
|
https://github.com/SevenNight2012/DevLibrary
|
2c4cd425965df3c2cb56cf03ce0d578f0841f008
|
4bc44efde819bfee04ab7828863d6794cfce9d4a
|
refs/heads/master
| 2020-05-31T15:22:58.966000 | 2020-01-03T12:29:44 | 2020-01-03T12:29:44 | 190,355,414 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.xxc.dev.common.callback;
/**
* 含有两个参数的回调
*/
public interface CallBack2<P1, P2> {
void onCallBack(P1 p1, P2 p2);
}
|
UTF-8
|
Java
| 153 |
java
|
CallBack2.java
|
Java
|
[] | null |
[] |
package com.xxc.dev.common.callback;
/**
* 含有两个参数的回调
*/
public interface CallBack2<P1, P2> {
void onCallBack(P1 p1, P2 p2);
}
| 153 | 0.659259 | 0.607407 | 10 | 12.5 | 15.324817 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
12
|
335cf4fb1905d9c146be195ad7681e95d3bb7b2e
| 32,555,852,142,854 |
4d9cbbf43b66e53968ffc453bb55d0c440136f79
|
/src/main/java/com/authine/cloudpivot/web/api/service/SystemManageService.java
|
dfc705a886318fc6f977010ac3ca87e845d74c5e
|
[] |
no_license
|
sengeiou/bjwq_webapi
|
https://github.com/sengeiou/bjwq_webapi
|
b519515a775ab161cbe01dbbb80062ed5f5db0e6
|
24e6b6228b8db38349b4d13cc0991d5b2b25e866
|
refs/heads/master
| 2023-03-19T14:57:13.173000 | 2020-06-28T07:45:25 | 2020-06-28T07:45:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.authine.cloudpivot.web.api.service;
import com.authine.cloudpivot.web.api.entity.OrgUser;
import com.authine.cloudpivot.web.api.entity.SmsHistory;
import com.authine.cloudpivot.web.api.entity.WelfareSet;
import java.util.List;
import java.util.Map;
/**
* @Author: wangyong
* @Date: 2020-02-07 15:59
* @Description: 系统管理service接口
*/
public interface SystemManageService {
/**
* 根据城市名称获取时间节点
*
* @param cityName
* @return 时间节点
*/
public Integer getTimeNodeByCity(String cityName);
/**
* 根据手机号码获取用户
*
* @param mobile 手机号码
* @return 用户实体类
*/
List<OrgUser> getOrgUserByMobile(String mobile);
/**
* 根据id获取手机历史验证码
*
* @param id id
* @return 手机历史验证码数据
*/
SmsHistory getSmsHistoryById(String id);
/**
* 根据获取名称和用户名
*
* @param mobile 手机号码
* @return
*/
List<Map<String, String>> getNameAndUserNameByMobile(String mobile);
/**
* 方法说明:根据城市获取省份名称
* @param city
* @return com.authine.cloudpivot.web.api.entity.WelfareSet
* @author liulei
* @Date 2020/5/6 15:04
*/
WelfareSet getWelfareSet(String city);
List<String> getAllCity() throws Exception;
}
|
UTF-8
|
Java
| 1,412 |
java
|
SystemManageService.java
|
Java
|
[
{
"context": ".util.List;\nimport java.util.Map;\n\n/**\n * @Author: wangyong\n * @Date: 2020-02-07 15:59\n * @Description: 系统管理s",
"end": 288,
"score": 0.9996431469917297,
"start": 280,
"tag": "USERNAME",
"value": "wangyong"
},
{
"context": "loudpivot.web.api.entity.WelfareSet\n * @author liulei\n * @Date 2020/5/6 15:04\n */\n WelfareSe",
"end": 1101,
"score": 0.9968958497047424,
"start": 1095,
"tag": "USERNAME",
"value": "liulei"
}
] | null |
[] |
package com.authine.cloudpivot.web.api.service;
import com.authine.cloudpivot.web.api.entity.OrgUser;
import com.authine.cloudpivot.web.api.entity.SmsHistory;
import com.authine.cloudpivot.web.api.entity.WelfareSet;
import java.util.List;
import java.util.Map;
/**
* @Author: wangyong
* @Date: 2020-02-07 15:59
* @Description: 系统管理service接口
*/
public interface SystemManageService {
/**
* 根据城市名称获取时间节点
*
* @param cityName
* @return 时间节点
*/
public Integer getTimeNodeByCity(String cityName);
/**
* 根据手机号码获取用户
*
* @param mobile 手机号码
* @return 用户实体类
*/
List<OrgUser> getOrgUserByMobile(String mobile);
/**
* 根据id获取手机历史验证码
*
* @param id id
* @return 手机历史验证码数据
*/
SmsHistory getSmsHistoryById(String id);
/**
* 根据获取名称和用户名
*
* @param mobile 手机号码
* @return
*/
List<Map<String, String>> getNameAndUserNameByMobile(String mobile);
/**
* 方法说明:根据城市获取省份名称
* @param city
* @return com.authine.cloudpivot.web.api.entity.WelfareSet
* @author liulei
* @Date 2020/5/6 15:04
*/
WelfareSet getWelfareSet(String city);
List<String> getAllCity() throws Exception;
}
| 1,412 | 0.637175 | 0.619318 | 59 | 19.881355 | 18.68298 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.220339 | false | false |
12
|
5a44b17501bea15da1a6f510166ec71d8fb43f2b
| 20,280,835,576,156 |
8430850ddc232b3c2b580ed6f4a6fe0686127599
|
/CafeIn/src/cafein/reply/ReplyDAO.java
|
61a0a7d79780f8b6f282828bd5d14a6243513f29
|
[] |
no_license
|
Kiboom/DayPalette
|
https://github.com/Kiboom/DayPalette
|
257710f840b293edb36069e4ab75f3ffad4bc8ce
|
967557c53360312c7ca4cf60328161a6d9b97f73
|
refs/heads/master
| 2016-08-12T19:24:52.460000 | 2015-10-04T08:36:09 | 2015-10-04T08:36:09 | 43,629,697 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cafein.reply;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cafein.post.Post;
public class ReplyDAO {
private static final Logger logger = LoggerFactory.getLogger(ReplyDAO.class);
public Connection getConnection() {
String url = "jdbc:mysql://localhost:3307/cafein";
String id = "root";
String pw = "db1004";
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(url, id, pw);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public void addReply(Reply re, int pid) throws SQLException {
String sql = "INSERT INTO reply (pid,content) VALUES(?,?)";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
System.out.println("connection:" + conn);
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pid);
pstmt.setString(2, re.getReplyContent());
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
public ArrayList<Reply> getReplys(int pid) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "SELECT * FROM reply WHERE pid=? ORDER BY postingtime DESC";
ArrayList<Reply> result = new ArrayList<Reply>();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pid);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int reid = rs.getInt("reid");
String content = rs.getString("content");
String postingtime = rs.getString("postingtime");
int liked = rs.getInt("liked");
result.add(new Reply(reid, content, postingtime, liked));
}
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void plusLike(int replyId) throws SQLException {
String sql = "UPDATE reply SET liked = liked+1 WHERE reid = ?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
logger.debug("connection:" + conn);
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, replyId);
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
public void minusLike(int replyId) throws SQLException {
String sql = "UPDATE reply SET liked = liked-1 WHERE reid = ?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
logger.debug("connection:" + conn);
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, replyId);
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
public int getLikedOnReply(int replyId) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "SELECT * FROM reply WHERE reid=?";
int liked = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, replyId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
liked = rs.getInt("liked");
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return liked;
}
}
|
UTF-8
|
Java
| 3,456 |
java
|
ReplyDAO.java
|
Java
|
[
{
"context": "307/cafein\";\n\t\tString id = \"root\";\n\t\tString pw = \"db1004\";\n\t\ttry {\n\t\t\tClass.forName(\"com.mysql.jdbc.Driver",
"end": 524,
"score": 0.996706485748291,
"start": 518,
"tag": "PASSWORD",
"value": "db1004"
}
] | null |
[] |
package cafein.reply;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cafein.post.Post;
public class ReplyDAO {
private static final Logger logger = LoggerFactory.getLogger(ReplyDAO.class);
public Connection getConnection() {
String url = "jdbc:mysql://localhost:3307/cafein";
String id = "root";
String pw = "<PASSWORD>";
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(url, id, pw);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public void addReply(Reply re, int pid) throws SQLException {
String sql = "INSERT INTO reply (pid,content) VALUES(?,?)";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
System.out.println("connection:" + conn);
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pid);
pstmt.setString(2, re.getReplyContent());
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
public ArrayList<Reply> getReplys(int pid) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "SELECT * FROM reply WHERE pid=? ORDER BY postingtime DESC";
ArrayList<Reply> result = new ArrayList<Reply>();
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pid);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int reid = rs.getInt("reid");
String content = rs.getString("content");
String postingtime = rs.getString("postingtime");
int liked = rs.getInt("liked");
result.add(new Reply(reid, content, postingtime, liked));
}
pstmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void plusLike(int replyId) throws SQLException {
String sql = "UPDATE reply SET liked = liked+1 WHERE reid = ?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
logger.debug("connection:" + conn);
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, replyId);
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
public void minusLike(int replyId) throws SQLException {
String sql = "UPDATE reply SET liked = liked-1 WHERE reid = ?";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
logger.debug("connection:" + conn);
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, replyId);
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
public int getLikedOnReply(int replyId) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "SELECT * FROM reply WHERE reid=?";
int liked = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, replyId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
liked = rs.getInt("liked");
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return liked;
}
}
| 3,460 | 0.655093 | 0.649595 | 150 | 22.040001 | 18.025864 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.6 | false | false |
12
|
59df2ece99b9fffa6a902b1e91b2147b33f23643
| 23,931,557,827,601 |
4bd8a29f74e9092722013fedab674fa14b08a260
|
/src/ch04/responsi6_nomor2d.java
|
99af9a990bb6f2cd029c175cc7a01cb873cd1e76
|
[] |
no_license
|
AchmadYaminHarahap/AppMob-3
|
https://github.com/AchmadYaminHarahap/AppMob-3
|
98fea8d30faae5e588256a3ec6fc5788d43a57ed
|
f2e562d2f4a02eb80abd40d64a86a1c02639c445
|
refs/heads/master
| 2023-04-05T10:01:21.015000 | 2021-04-03T17:42:28 | 2021-04-03T17:42:28 | 354,352,371 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ch04;
public class responsi6_nomor2d {
public static void main(String[] args) {
System.out.println("tentukan angka-angka kelipatan 3 di dalam array dibawah ini");
int nilai[] = {82, 12, 41, 38, 19, 26, 9, 48, 20, 55, 8, 32, 3};
for (int x = 0; x<nilai.length; x++) {
System.out.print(nilai[x] +", ");
}
System.out.println("\n");
System.out.println("Menampilkan angka-angka kelipatan 3 di dalam array");
for (int x = 0; x < nilai.length; x++){
if (nilai [x] % 3 == 0){
System.out.print(nilai[x]+", ");
}
}
}
}
|
UTF-8
|
Java
| 665 |
java
|
responsi6_nomor2d.java
|
Java
|
[] | null |
[] |
package ch04;
public class responsi6_nomor2d {
public static void main(String[] args) {
System.out.println("tentukan angka-angka kelipatan 3 di dalam array dibawah ini");
int nilai[] = {82, 12, 41, 38, 19, 26, 9, 48, 20, 55, 8, 32, 3};
for (int x = 0; x<nilai.length; x++) {
System.out.print(nilai[x] +", ");
}
System.out.println("\n");
System.out.println("Menampilkan angka-angka kelipatan 3 di dalam array");
for (int x = 0; x < nilai.length; x++){
if (nilai [x] % 3 == 0){
System.out.print(nilai[x]+", ");
}
}
}
}
| 665 | 0.500752 | 0.451128 | 24 | 26.708334 | 27.37925 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.25 | false | false |
12
|
883b9dadf372d97741b168f8941fc9df436b5d5b
| 30,958,124,305,521 |
c07e8f525e9106ea47d0e2e5a9b0d92f90ea3eb6
|
/core/src/quitru/gnosticchemist/com/github/Model/User.java
|
a218aef5d4a2775c279355c1536b1aeb62a5cfa1
|
[] |
no_license
|
gnosticChemist/QuiTru
|
https://github.com/gnosticChemist/QuiTru
|
7338d3e56d076f91912b5a9d6355f8b833cc52e0
|
9d2eae5b3d28b15418201629dc337dba94700071
|
refs/heads/master
| 2020-04-10T11:40:03.711000 | 2018-12-09T03:21:55 | 2018-12-09T03:21:55 | 135,725,257 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package quitru.gnosticchemist.com.github.Model;
import java.io.Serializable;
import java.net.InetAddress;
public class User implements Serializable {
private InetAddress endereco;
private String username;
final private UserID userID;
public User(String username) {
this.username = username;
userID = new UserID(username);
}
public InetAddress getEndereco() {
return endereco;
}
public void setEndereco(InetAddress endereco) {
if(endereco != null)this.endereco = endereco;
}
public String getUsername() {
return username;
}
public UserID getUserID(){
return userID;
}
@Override
public String toString(){
return username;
}
@Override
public boolean equals(Object object){
if(!(object instanceof User)) return false;
User user = (User)object;
return user.userID.equals(userID);
}
static final long serialVersionUID = 5L;
}
class UserID implements Serializable{
private final long time;
private final char first;
public UserID(String username){
first=username.charAt(0);
time = System.currentTimeMillis();
}
@Override
public boolean equals(Object object){
if(object instanceof UserID){
UserID usr = (UserID)object;
return (usr.time == time) && (first == usr.first);
}else return false;
}
static final long serialVersionUID = 6L;
}
|
UTF-8
|
Java
| 1,499 |
java
|
User.java
|
Java
|
[
{
"context": "ic User(String username) {\n this.username = username;\n userID = new UserID(username);\n }\n\n ",
"end": 316,
"score": 0.9822572469711304,
"start": 308,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package quitru.gnosticchemist.com.github.Model;
import java.io.Serializable;
import java.net.InetAddress;
public class User implements Serializable {
private InetAddress endereco;
private String username;
final private UserID userID;
public User(String username) {
this.username = username;
userID = new UserID(username);
}
public InetAddress getEndereco() {
return endereco;
}
public void setEndereco(InetAddress endereco) {
if(endereco != null)this.endereco = endereco;
}
public String getUsername() {
return username;
}
public UserID getUserID(){
return userID;
}
@Override
public String toString(){
return username;
}
@Override
public boolean equals(Object object){
if(!(object instanceof User)) return false;
User user = (User)object;
return user.userID.equals(userID);
}
static final long serialVersionUID = 5L;
}
class UserID implements Serializable{
private final long time;
private final char first;
public UserID(String username){
first=username.charAt(0);
time = System.currentTimeMillis();
}
@Override
public boolean equals(Object object){
if(object instanceof UserID){
UserID usr = (UserID)object;
return (usr.time == time) && (first == usr.first);
}else return false;
}
static final long serialVersionUID = 6L;
}
| 1,499 | 0.63509 | 0.633089 | 63 | 22.793652 | 17.575378 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396825 | false | false |
12
|
ddf3771f958fb9a4adfd92236ed197a3e5e19dd0
| 17,703,855,213,116 |
4d065ede9518613d4f62794afc9fc80ebc91d86f
|
/src/main/java/domain/AntwoordLeerling.java
|
301d9a2faf10040f7e604afbc42548aa5678bd1e
|
[] |
no_license
|
mateiclaudiu/stemtest-domain
|
https://github.com/mateiclaudiu/stemtest-domain
|
507c0e43afc6e205be7ed07e96ee0f2cb3cafae6
|
e1fa45af8e61fd7d39678fbe928dd73fffda0569
|
refs/heads/master
| 2021-01-07T10:51:24.991000 | 2020-02-28T20:34:58 | 2020-02-28T20:34:58 | 241,668,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package domain;
public class AntwoordLeerling {
private String user;
private AntwoordOptie antwoordOptie;
public AntwoordLeerling(String user, AntwoordOptie antwoordOptie) {
this.user = user;
this.antwoordOptie = antwoordOptie;
}
}
|
UTF-8
|
Java
| 267 |
java
|
AntwoordLeerling.java
|
Java
|
[] | null |
[] |
package domain;
public class AntwoordLeerling {
private String user;
private AntwoordOptie antwoordOptie;
public AntwoordLeerling(String user, AntwoordOptie antwoordOptie) {
this.user = user;
this.antwoordOptie = antwoordOptie;
}
}
| 267 | 0.71161 | 0.71161 | 12 | 21.25 | 21.378046 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
f3026a3d80483a247c1eca0823603fb52d01b1e8
| 9,655,086,518,733 |
3742ea64b2ba3459da1efc38091428193be50e52
|
/src/com/octest/TestBdd.java
|
bce5ca31881d4fe3a6cf1e072de2ac92f8481fab
|
[] |
no_license
|
aribghilas/JavaEE
|
https://github.com/aribghilas/JavaEE
|
14f335905f78cf2e44e927f2e0633a1653cff154
|
2bfad83de0b5ca177fa67c79cd54069651da5243
|
refs/heads/master
| 2021-04-08T16:38:47.207000 | 2020-03-20T15:49:59 | 2020-03-20T15:49:59 | 248,790,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.octest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 com.octest.bdd.*;
import com.octest.beans.*;
/**
* Servlet implementation class TestBdd
*/
@WebServlet("/TestBdd")
public class TestBdd extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestBdd() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//afficher les nom de la table nom
Nom tableNom= new Nom();
Utilisateurs user=new Utilisateurs();
request.setAttribute("users", tableNom.getUsers());
this.getServletContext().getRequestDispatcher("/WEB-INF/testbdd.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//créer un nv tuple dans la bdd
String nom = request.getParameter("nom");
String prenom= request.getParameter("prenom");
Utilisateurs user= new Utilisateurs(nom, prenom);
Nom ajout= new Nom();
ajout.insertUser(user);
request.setAttribute("users", ajout.getUsers());
request.setAttribute("ajout", ajout.erreur(user));
String supNom= request.getParameter("supNom");
String supPrenom=request.getParameter("supPrenom");
Utilisateurs user2= new Utilisateurs(supNom,supPrenom);
Nom suprimer = new Nom();
suprimer.supligne(user2);
request.setAttribute("users", suprimer.getUsers());
request.setAttribute("suprime", suprimer.erreur(user2));
this.getServletContext().getRequestDispatcher("/WEB-INF/testbdd.jsp").forward(request, response);
}
}
|
ISO-8859-1
|
Java
| 2,192 |
java
|
TestBdd.java
|
Java
|
[] | null |
[] |
package com.octest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 com.octest.bdd.*;
import com.octest.beans.*;
/**
* Servlet implementation class TestBdd
*/
@WebServlet("/TestBdd")
public class TestBdd extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestBdd() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//afficher les nom de la table nom
Nom tableNom= new Nom();
Utilisateurs user=new Utilisateurs();
request.setAttribute("users", tableNom.getUsers());
this.getServletContext().getRequestDispatcher("/WEB-INF/testbdd.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//créer un nv tuple dans la bdd
String nom = request.getParameter("nom");
String prenom= request.getParameter("prenom");
Utilisateurs user= new Utilisateurs(nom, prenom);
Nom ajout= new Nom();
ajout.insertUser(user);
request.setAttribute("users", ajout.getUsers());
request.setAttribute("ajout", ajout.erreur(user));
String supNom= request.getParameter("supNom");
String supPrenom=request.getParameter("supPrenom");
Utilisateurs user2= new Utilisateurs(supNom,supPrenom);
Nom suprimer = new Nom();
suprimer.supligne(user2);
request.setAttribute("users", suprimer.getUsers());
request.setAttribute("suprime", suprimer.erreur(user2));
this.getServletContext().getRequestDispatcher("/WEB-INF/testbdd.jsp").forward(request, response);
}
}
| 2,192 | 0.706527 | 0.704701 | 70 | 30.299999 | 28.886156 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.157143 | false | false |
12
|
8d73b894853a70ea116b3fc43dc1460dd469cc22
| 17,729,625,066,300 |
d929dbbaa5bbd553ec527f74fab57e5cf91cfb7e
|
/dropwizard-microservices/moneys-transactions/src/main/java/no/domain/moneys/transactions/service/TransactionService.java
|
2d3ea5e85d3f041c8fa44b4b2120534b885ccbd8
|
[] |
no_license
|
forsak3n/dropwizard-microservices
|
https://github.com/forsak3n/dropwizard-microservices
|
bb64d047f94993b6cda517c40ff6c0c23103bad5
|
794977558f04e35e8bf409eba7b00febbdeb79d0
|
refs/heads/master
| 2016-07-31T21:31:15.531000 | 2015-09-18T12:31:38 | 2015-09-18T12:31:38 | 42,123,039 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package no.domain.moneys.transactions.service;
import java.util.List;
public interface TransactionService<ITransaction> {
ITransaction get(Long id);
void update(ITransaction transaction);
void delete(Long id);
void create(ITransaction transaction);
List<ITransaction> getUserTransactions(Long userId);
List<ITransaction> getCategoryTransactions(Long categoryId);
}
|
UTF-8
|
Java
| 391 |
java
|
TransactionService.java
|
Java
|
[] | null |
[] |
package no.domain.moneys.transactions.service;
import java.util.List;
public interface TransactionService<ITransaction> {
ITransaction get(Long id);
void update(ITransaction transaction);
void delete(Long id);
void create(ITransaction transaction);
List<ITransaction> getUserTransactions(Long userId);
List<ITransaction> getCategoryTransactions(Long categoryId);
}
| 391 | 0.777494 | 0.777494 | 12 | 31.583334 | 21.44162 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
12
|
417cea4521ba319a3018700296adc786083a3a47
| 34,308,198,763,183 |
6b6ae2446884db04afdcd25bce4e04db00b6a42f
|
/app/src/main/java/com/teamturing/dreamteam/EditProfileActivity.java
|
98ac4c5ef9607a1259149e9eecc1dcfa720247b0
|
[] |
no_license
|
jitunayak/Dream-Team
|
https://github.com/jitunayak/Dream-Team
|
46107fda7cfa265cbcb2ef3209ff84913c5925a9
|
1fd0b53c8577bfe2a859f692de59de6957398477
|
refs/heads/master
| 2022-12-13T05:29:26.430000 | 2018-12-22T15:43:20 | 2018-12-22T15:43:20 | 184,582,544 | 0 | 0 | null | true | 2022-11-29T21:01:36 | 2019-05-02T13:05:37 | 2019-05-02T13:05:40 | 2022-11-29T21:01:27 | 490 | 0 | 0 | 1 |
Java
| false | false |
package com.teamturing.dreamteam;
import android.*;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.chip.Chip;
import android.support.design.chip.ChipGroup;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.makeramen.roundedimageview.RoundedImageView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EditProfileActivity extends AppCompatActivity {
RoundedImageView roundedImageView ;
private static final int RESULT_LOAD_IMAGE = 100;
Button submitButton;
String email, namestr,githublinkstr,aboutmestr;
EditText name,contact,org,githublink,aboutme;
Uri selectImage;
List<String> choices;
ChipGroup interests;
String [] skills = {
"Java",
"Python",
"C++",
"JavaScript",
"Angular",
"R",
"ML",
"IoT",
"NodeJS",
"SQL",
"MongoDB",
"Android",
"Kotlin",
"Flutter",
"Full stack",
"HTML",
"CSS"
};
String[] proffesion = {"Select your profession","Student","Professional","Freelancer"};
Spinner proffessionSpin;
StorageReference storageReference;
FirebaseAuth mAuth;
ProgressDialog mProgressDialog;
AuthCredential authCredential;
String accIdToken;
String loginType;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
roundedImageView = findViewById(R.id.profileImage);
submitButton = findViewById(R.id.submitBtn);
// frameworks = findViewById(R.id.frameworks);
interests = findViewById(R.id.interests);
name = findViewById(R.id.enterName);
proffessionSpin = findViewById(R.id.proffession);
aboutme=findViewById(R.id.aboutme);
mProgressDialog = new ProgressDialog(this);
contact = findViewById(R.id.enterContact);
org = findViewById(R.id.enterOrg);
githublink=findViewById(R.id.enterGithub);
choices = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>( getApplicationContext(),
android.R.layout.simple_list_item_1,proffesion);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
proffessionSpin.setAdapter(adapter);
mAuth = FirebaseAuth.getInstance();
roundedImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(isReadStoragePermissionGranted())
{
uploadImage();
}
}
});
Intent intent = getIntent();
loginType = intent.getExtras().getString("loginType");
// Log.e("accIDToken",accIdToken);
Log.e("LoginType",loginType);
databaseReference=FirebaseDatabase.getInstance().getReference().child("Techie").child(mAuth.getCurrentUser().getUid());
storageReference= FirebaseStorage.getInstance().getReference().child("ProfileImages/").child(mAuth.getCurrentUser().getUid());
getData();
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(TextUtils.isEmpty(name.getText()))
{
name.setError("Enter your name");
name.requestFocus();
return;
}
if(TextUtils.isEmpty(contact.getText()))
{
contact.setError("Enter your contact");
contact.requestFocus();
return;
}
if(TextUtils.isEmpty(githublink.getText()))
{
githublink.setError("Enter your github link");
githublink.requestFocus();
return;
}
if(TextUtils.isEmpty(aboutme.getText()))
{
aboutme.setError("Enter about you");
aboutme.requestFocus();
return;
}
if(TextUtils.isEmpty(org.getText()))
{
org.setError("Enter your organisation");
org.requestFocus();
return;
}
if(proffessionSpin.getSelectedItem().toString().equals("Select your profession")){
Toast.makeText(getApplicationContext(),"Please select a profession",Toast.LENGTH_SHORT).show();
return;
}
if(selectImage==null)
{
Toast.makeText(getApplicationContext(), "Please Select a profile image", Toast.LENGTH_SHORT).show();
return;
}
for(int i = 0;i<interests.getChildCount();i++)
{
Chip chip = (Chip)interests.getChildAt(i);
if(chip.isChecked())
{
Log.e("Chips are",":"+chip.getChipText());
choices.add(chip.getChipText().toString());
}
}
updateDatabases();
}
});
//For dynamically inflating chips
for(int i=0;i<skills.length;i++)
{
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.chip_view,interests,false);
Chip chip = view.findViewById(R.id.dynamicChips);
chip.setChipText(skills[i]);
interests.addView(chip);
}
}
// public void checkUser(){
// DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Techie");
// databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
// @Override
// public void onDataChange(DataSnapshot dataSnapshot) {
// for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
// {
// Log.e("USER is",dataSnapshot1.child("name").getValue().toString());
// Log.e("Token is",dataSnapshot1.child("idToken").getValue().toString());
// }
// }
//
// @Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
// });
// }
public void registerUser(){
mProgressDialog.setMessage("Registering user...");
mProgressDialog.show();
// authCredential = GoogleAuthProvider.getCredential(accIdToken,null);
mAuth.signInWithCredential(authCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
updateDatabases();
} else {
Log.w("Error:", "signInWithCredential:failure", task.getException());
Toast.makeText(getApplicationContext(), "signInWith Cretdential failure", Toast.LENGTH_SHORT).show();
}
}
});
}
public void updateDatabases(){
FirebaseUser currentUser = mAuth.getCurrentUser();
email = currentUser.getEmail();
namestr = name.getText().toString();
githublinkstr = githublink.getText().toString();
String contactStr = contact.getText().toString();
String orgStr = org.getText().toString();
aboutmestr=aboutme.getText().toString();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().
child("Techie").
child(currentUser.getUid());
databaseReference.child("name").setValue(namestr);
databaseReference.child("githublink").setValue(githublinkstr);
databaseReference.child("aboutme").setValue(aboutmestr);
databaseReference.child("email").setValue(email);
databaseReference.child("contact").setValue(contactStr);
databaseReference.child("organisation").setValue(orgStr);
//databaseReference.child("idToken").setValue(accIdToken);
databaseReference.child("profession").setValue(proffessionSpin.getSelectedItem().toString());
for(int i=0;i<choices.size();i++)
{
databaseReference.child("skills").child(String.valueOf(i)).setValue(choices.get(i));
}
StorageReference ref = FirebaseStorage.getInstance().getReference().child("ProfileImages/"+currentUser.getUid());
ref.putFile(selectImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
mProgressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
});
}
public void uploadImage(){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,RESULT_LOAD_IMAGE);
}
public boolean isReadStoragePermissionGranted(){
if(Build.VERSION.SDK_INT>=23)
{
if(checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
return true;
}else{
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}
,3);
return false;
}
}else{
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==3&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
uploadImage();
}
}
public void getData(){
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Glide.with(getApplicationContext()).load(uri.toString()).into(roundedImageView);
selectImage=uri;
Log.e("imageuriString",uri.toString());
}
});
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot1) {
String stremail,strorganisation,strprofession,namestr;
ArrayList<String> skillsList=new ArrayList<String>();
// DataSnapshot dataSnapshot1
String aboutmestr=dataSnapshot1.child("aboutme").getValue().toString();
String strcontact=dataSnapshot1.child("contact").getValue().toString();
stremail=dataSnapshot1.child("email").getValue().toString();
strorganisation=dataSnapshot1.child("organisation").getValue().toString();
strprofession=dataSnapshot1.child("profession").getValue().toString();
namestr=dataSnapshot1.child("name").getValue().toString();
String githubstr=dataSnapshot1.child("githublink").getValue().toString();
//for(DataSnapshot skills:dataSnapshot1.child("skills").getChildren()){
aboutme.setText(aboutmestr);
contact.setText(strcontact);
name.setText(namestr);
org.setText(strorganisation);
// proffesion.setText(strprofession);
githublink.setText(githubstr);
int i= Arrays.asList(proffesion).indexOf(strprofession);
proffessionSpin.setSelection(i);
//registerUser();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = findViewById(R.id.profile_pic);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
//List view expander
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
|
UTF-8
|
Java
| 16,810 |
java
|
EditProfileActivity.java
|
Java
|
[] | null |
[] |
package com.teamturing.dreamteam;
import android.*;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.chip.Chip;
import android.support.design.chip.ChipGroup;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.makeramen.roundedimageview.RoundedImageView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EditProfileActivity extends AppCompatActivity {
RoundedImageView roundedImageView ;
private static final int RESULT_LOAD_IMAGE = 100;
Button submitButton;
String email, namestr,githublinkstr,aboutmestr;
EditText name,contact,org,githublink,aboutme;
Uri selectImage;
List<String> choices;
ChipGroup interests;
String [] skills = {
"Java",
"Python",
"C++",
"JavaScript",
"Angular",
"R",
"ML",
"IoT",
"NodeJS",
"SQL",
"MongoDB",
"Android",
"Kotlin",
"Flutter",
"Full stack",
"HTML",
"CSS"
};
String[] proffesion = {"Select your profession","Student","Professional","Freelancer"};
Spinner proffessionSpin;
StorageReference storageReference;
FirebaseAuth mAuth;
ProgressDialog mProgressDialog;
AuthCredential authCredential;
String accIdToken;
String loginType;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
roundedImageView = findViewById(R.id.profileImage);
submitButton = findViewById(R.id.submitBtn);
// frameworks = findViewById(R.id.frameworks);
interests = findViewById(R.id.interests);
name = findViewById(R.id.enterName);
proffessionSpin = findViewById(R.id.proffession);
aboutme=findViewById(R.id.aboutme);
mProgressDialog = new ProgressDialog(this);
contact = findViewById(R.id.enterContact);
org = findViewById(R.id.enterOrg);
githublink=findViewById(R.id.enterGithub);
choices = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>( getApplicationContext(),
android.R.layout.simple_list_item_1,proffesion);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
proffessionSpin.setAdapter(adapter);
mAuth = FirebaseAuth.getInstance();
roundedImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(isReadStoragePermissionGranted())
{
uploadImage();
}
}
});
Intent intent = getIntent();
loginType = intent.getExtras().getString("loginType");
// Log.e("accIDToken",accIdToken);
Log.e("LoginType",loginType);
databaseReference=FirebaseDatabase.getInstance().getReference().child("Techie").child(mAuth.getCurrentUser().getUid());
storageReference= FirebaseStorage.getInstance().getReference().child("ProfileImages/").child(mAuth.getCurrentUser().getUid());
getData();
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(TextUtils.isEmpty(name.getText()))
{
name.setError("Enter your name");
name.requestFocus();
return;
}
if(TextUtils.isEmpty(contact.getText()))
{
contact.setError("Enter your contact");
contact.requestFocus();
return;
}
if(TextUtils.isEmpty(githublink.getText()))
{
githublink.setError("Enter your github link");
githublink.requestFocus();
return;
}
if(TextUtils.isEmpty(aboutme.getText()))
{
aboutme.setError("Enter about you");
aboutme.requestFocus();
return;
}
if(TextUtils.isEmpty(org.getText()))
{
org.setError("Enter your organisation");
org.requestFocus();
return;
}
if(proffessionSpin.getSelectedItem().toString().equals("Select your profession")){
Toast.makeText(getApplicationContext(),"Please select a profession",Toast.LENGTH_SHORT).show();
return;
}
if(selectImage==null)
{
Toast.makeText(getApplicationContext(), "Please Select a profile image", Toast.LENGTH_SHORT).show();
return;
}
for(int i = 0;i<interests.getChildCount();i++)
{
Chip chip = (Chip)interests.getChildAt(i);
if(chip.isChecked())
{
Log.e("Chips are",":"+chip.getChipText());
choices.add(chip.getChipText().toString());
}
}
updateDatabases();
}
});
//For dynamically inflating chips
for(int i=0;i<skills.length;i++)
{
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.chip_view,interests,false);
Chip chip = view.findViewById(R.id.dynamicChips);
chip.setChipText(skills[i]);
interests.addView(chip);
}
}
// public void checkUser(){
// DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Techie");
// databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
// @Override
// public void onDataChange(DataSnapshot dataSnapshot) {
// for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
// {
// Log.e("USER is",dataSnapshot1.child("name").getValue().toString());
// Log.e("Token is",dataSnapshot1.child("idToken").getValue().toString());
// }
// }
//
// @Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
// });
// }
public void registerUser(){
mProgressDialog.setMessage("Registering user...");
mProgressDialog.show();
// authCredential = GoogleAuthProvider.getCredential(accIdToken,null);
mAuth.signInWithCredential(authCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
updateDatabases();
} else {
Log.w("Error:", "signInWithCredential:failure", task.getException());
Toast.makeText(getApplicationContext(), "signInWith Cretdential failure", Toast.LENGTH_SHORT).show();
}
}
});
}
public void updateDatabases(){
FirebaseUser currentUser = mAuth.getCurrentUser();
email = currentUser.getEmail();
namestr = name.getText().toString();
githublinkstr = githublink.getText().toString();
String contactStr = contact.getText().toString();
String orgStr = org.getText().toString();
aboutmestr=aboutme.getText().toString();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().
child("Techie").
child(currentUser.getUid());
databaseReference.child("name").setValue(namestr);
databaseReference.child("githublink").setValue(githublinkstr);
databaseReference.child("aboutme").setValue(aboutmestr);
databaseReference.child("email").setValue(email);
databaseReference.child("contact").setValue(contactStr);
databaseReference.child("organisation").setValue(orgStr);
//databaseReference.child("idToken").setValue(accIdToken);
databaseReference.child("profession").setValue(proffessionSpin.getSelectedItem().toString());
for(int i=0;i<choices.size();i++)
{
databaseReference.child("skills").child(String.valueOf(i)).setValue(choices.get(i));
}
StorageReference ref = FirebaseStorage.getInstance().getReference().child("ProfileImages/"+currentUser.getUid());
ref.putFile(selectImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
mProgressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
});
}
public void uploadImage(){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,RESULT_LOAD_IMAGE);
}
public boolean isReadStoragePermissionGranted(){
if(Build.VERSION.SDK_INT>=23)
{
if(checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
return true;
}else{
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}
,3);
return false;
}
}else{
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==3&&grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
uploadImage();
}
}
public void getData(){
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Glide.with(getApplicationContext()).load(uri.toString()).into(roundedImageView);
selectImage=uri;
Log.e("imageuriString",uri.toString());
}
});
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot1) {
String stremail,strorganisation,strprofession,namestr;
ArrayList<String> skillsList=new ArrayList<String>();
// DataSnapshot dataSnapshot1
String aboutmestr=dataSnapshot1.child("aboutme").getValue().toString();
String strcontact=dataSnapshot1.child("contact").getValue().toString();
stremail=dataSnapshot1.child("email").getValue().toString();
strorganisation=dataSnapshot1.child("organisation").getValue().toString();
strprofession=dataSnapshot1.child("profession").getValue().toString();
namestr=dataSnapshot1.child("name").getValue().toString();
String githubstr=dataSnapshot1.child("githublink").getValue().toString();
//for(DataSnapshot skills:dataSnapshot1.child("skills").getChildren()){
aboutme.setText(aboutmestr);
contact.setText(strcontact);
name.setText(namestr);
org.setText(strorganisation);
// proffesion.setText(strprofession);
githublink.setText(githubstr);
int i= Arrays.asList(proffesion).indexOf(strprofession);
proffessionSpin.setSelection(i);
//registerUser();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = findViewById(R.id.profile_pic);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
//List view expander
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
| 16,810 | 0.591315 | 0.589411 | 452 | 36.190266 | 30.596779 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652655 | false | false |
12
|
22aea6f894ac711349cadf50fcb48365324f1acf
| 8,452,495,648,555 |
974ebf35c78733562edf57d71c80b5f2f85d1408
|
/Collections/src/com/gbn/iterator/IteratorEx.java
|
47ec868ff1875d880ae62baa3faea317cd8528b4
|
[] |
no_license
|
Ramesh7214/Core-Java
|
https://github.com/Ramesh7214/Core-Java
|
99c51bcb1d0a0d56fe921e0478b659f3c6b20006
|
5a44d817c70f35e1919c8bd7317ff91922edf423
|
refs/heads/master
| 2020-04-29T07:45:41.381000 | 2019-03-16T11:52:21 | 2019-03-16T11:52:21 | 175,958,914 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.gbn.iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorEx {
public static void main(String[] args) {
List list = new ArrayList();
list.add("abc");
list.add(2);
list.add(2.2);
list.add("abc");
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
/*ListIterator lit = list.listIterator();
while()) {lit.hasNext(
System.out.println(lit.next());
System.out.println(lit.previous());
}
*/
}
}
|
UTF-8
|
Java
| 589 |
java
|
IteratorEx.java
|
Java
|
[] | null |
[] |
package com.gbn.iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorEx {
public static void main(String[] args) {
List list = new ArrayList();
list.add("abc");
list.add(2);
list.add(2.2);
list.add("abc");
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
/*ListIterator lit = list.listIterator();
while()) {lit.hasNext(
System.out.println(lit.next());
System.out.println(lit.previous());
}
*/
}
}
| 589 | 0.636672 | 0.631579 | 36 | 15.361111 | 14.134577 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.861111 | false | false |
12
|
0a0b9862c86d50900ed6b6464739805a3b3dd37b
| 29,850,022,716,887 |
b2d97d1627517b662af40d408164327332d8a688
|
/Project SourceCode/src/main/java/com/kh/tworavel/model/service/GalleryService.java
|
d138b2b37a19c4fb72ccf9b829108221fdc939e1
|
[] |
no_license
|
JungCG/TworavelOfficial
|
https://github.com/JungCG/TworavelOfficial
|
9f6ec31598b2342a839c039fc984a4e52e901007
|
1f83d8e02738c710b37acda0301214b32ad1c306
|
refs/heads/main
| 2023-02-23T02:50:23.094000 | 2021-01-29T14:01:40 | 2021-01-29T14:01:40 | 323,506,614 | 0 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kh.tworavel.model.service;
import java.util.List;
import com.kh.tworavel.model.domain.GAdd;
import com.kh.tworavel.model.domain.GLike;
import com.kh.tworavel.model.domain.Gallery;
public interface GalleryService {
public int listCount();
public List<Gallery> selectList(int page, int LIMIT);
public int insertGallery(Gallery gallery);
public int insertGadd(GAdd gadd);
public GAdd selectGalleryAdd(int gallery_num);
public Gallery selectGallery(int gallery_num);
void updateGallery(Gallery g,GAdd gadd);
void deleteGallery(int gallery_num);
void likeGallery(int gallery_num);
void unlikeGallery(int gallery_num);
int deleteGLike(GLike glike);
int insertGLike(GLike glike);
int selectGLike(GLike glike);
}
|
UTF-8
|
Java
| 737 |
java
|
GalleryService.java
|
Java
|
[] | null |
[] |
package com.kh.tworavel.model.service;
import java.util.List;
import com.kh.tworavel.model.domain.GAdd;
import com.kh.tworavel.model.domain.GLike;
import com.kh.tworavel.model.domain.Gallery;
public interface GalleryService {
public int listCount();
public List<Gallery> selectList(int page, int LIMIT);
public int insertGallery(Gallery gallery);
public int insertGadd(GAdd gadd);
public GAdd selectGalleryAdd(int gallery_num);
public Gallery selectGallery(int gallery_num);
void updateGallery(Gallery g,GAdd gadd);
void deleteGallery(int gallery_num);
void likeGallery(int gallery_num);
void unlikeGallery(int gallery_num);
int deleteGLike(GLike glike);
int insertGLike(GLike glike);
int selectGLike(GLike glike);
}
| 737 | 0.785617 | 0.785617 | 27 | 26.296297 | 18.244867 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false |
12
|
349499347f44240926af53dbdc56d110cfa7a057
| 10,539,849,759,626 |
65cf3725fde70c7e056a715e97ed8bd5a26486c7
|
/app/src/main/java/com/basement720/odoo/exception/Exception.java
|
087294f15ba41a3019d60bae060ccf51c6595e33
|
[] |
no_license
|
eslammohamed13/3d2nworld-android
|
https://github.com/eslammohamed13/3d2nworld-android
|
e322166d2a441ea694e8724d0b11bfde34d6cbde
|
421a01205ef3c2423a66960538b4e08b28337ee9
|
refs/heads/master
| 2020-05-07T21:30:32.575000 | 2017-12-16T23:45:11 | 2017-12-16T23:45:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Created by Mong Ramos Jr. on 12/17/17 7:45 AM
*
* Copyright (c) 2017 Brainbox Inc. All rights reserved.
*
* Last modified 12/17/17 7:40 AM
*/
package com.basement720.odoo.exception;
/**
* Created by mong on 10/6/17.
*/
public class Exception extends RuntimeException {
}
|
UTF-8
|
Java
| 288 |
java
|
Exception.java
|
Java
|
[
{
"context": "/*\n * Created by Mong Ramos Jr. on 12/17/17 7:45 AM\n *\n * Copyright (c) 2017 Brai",
"end": 30,
"score": 0.9993628859519958,
"start": 17,
"tag": "NAME",
"value": "Mong Ramos Jr"
},
{
"context": "com.basement720.odoo.exception;\n\n/**\n * Created by mong on 10/6/17.\n */\n\npublic class Exception extends R",
"end": 217,
"score": 0.7755220532417297,
"start": 213,
"tag": "USERNAME",
"value": "mong"
}
] | null |
[] |
/*
* Created by <NAME>. on 12/17/17 7:45 AM
*
* Copyright (c) 2017 Brainbox Inc. All rights reserved.
*
* Last modified 12/17/17 7:40 AM
*/
package com.basement720.odoo.exception;
/**
* Created by mong on 10/6/17.
*/
public class Exception extends RuntimeException {
}
| 281 | 0.677083 | 0.572917 | 17 | 15.941176 | 20.39455 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.058824 | false | false |
12
|
c58cf25cb368ca968d4d0ed33d02d5797d193ee4
| 9,844,065,060,273 |
6252c165657baa6aa605337ebc38dd44b3f694e2
|
/org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-900-Files/boiler-To-Generate-900-Files/syncregions-900Files/BoilerActuator5951.java
|
1297fb4a6ca80472120d0b64a86d924dec06e6a5
|
[] |
no_license
|
soha500/EglSync
|
https://github.com/soha500/EglSync
|
00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638
|
55101bc781349bb14fefc178bf3486e2b778aed6
|
refs/heads/master
| 2021-06-23T02:55:13.464000 | 2020-12-11T19:10:01 | 2020-12-11T19:10:01 | 139,832,721 | 0 | 1 | null | false | 2019-05-31T11:34:02 | 2018-07-05T10:20:00 | 2019-04-15T09:03:54 | 2019-05-31T11:34:01 | 87 | 0 | 0 | 0 |
Java
| false | false |
package syncregions;
public class BoilerActuator5951 {
public execute(int temperatureDifference5951, boolean boilerStatus5951) {
//sync _bfpnGUbFEeqXnfGWlV5951, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
|
UTF-8
|
Java
| 263 |
java
|
BoilerActuator5951.java
|
Java
|
[] | null |
[] |
package syncregions;
public class BoilerActuator5951 {
public execute(int temperatureDifference5951, boolean boilerStatus5951) {
//sync _bfpnGUbFEeqXnfGWlV5951, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| 263 | 0.749049 | 0.688213 | 13 | 19.23077 | 24.729782 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.230769 | false | false |
12
|
cc81b687ed452cca5d00d01d360ab5bb8c27f9d7
| 9,844,065,060,416 |
234fdd07a2f0c897457884acda957d7242d6f698
|
/app/src/main/java/myrr/auto1/myreadingrecord1/ShelfFragment.java
|
106925e6055a837b2858c6921a79196ebc3caa4f
|
[] |
no_license
|
auto94/myRR
|
https://github.com/auto94/myRR
|
414a18448e8d323e6e13b9cd69f5838c66f0234b
|
224b5eea0e3e2ece79f43c5c473ca2ab043fdfc3
|
refs/heads/master
| 2018-12-21T05:55:44.636000 | 2018-11-04T19:01:40 | 2018-11-04T19:01:40 | 130,453,901 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package myrr.auto1.myreadingrecord1;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class ShelfFragment extends Fragment {
private boolean isCRExpandedShelf = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_shelf,container, false);
final Context contextShelf = getContext();
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) view.findViewById(R.id.result_tabs);
tabs.setupWithViewPager(viewPager);
final Context context = getActivity().getApplicationContext();
final Resources res = getResources();
Typeface infoFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Heebo-Light.ttf");
TextView currently = view.findViewById(R.id.currently_tv);
TextView lastReadTV = view.findViewById(R.id.lastread_tv);
ImageView curCover = view.findViewById(R.id.curBook_cover_shelf);
TextView curTitle = view.findViewById(R.id.curBook_title_shelf);
TextView curAuthor = view.findViewById(R.id.curBook_Author_shelf);
TextView curPages = view.findViewById(R.id.curBook_pages_shelf);
TextView infoOnlyTV = view.findViewById(R.id.only_info_tv);
infoOnlyTV.setVisibility(View.GONE);
final RelativeLayout rl_master = view.findViewById(R.id.rel_lay_all_book_shelf);
Typeface titleFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Oswald-Regular.ttf");
curTitle.setTypeface(titleFont);
currently.setTypeface(titleFont);
curTitle.setPaintFlags(curTitle.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Typeface authorFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Oswald-Light.ttf");
curAuthor.setTextSize(15);
curAuthor.setTypeface(authorFont);
curPages.setTextSize(13);
curPages.setTypeface(authorFont);
curCover.setScaleType(ImageView.ScaleType.FIT_XY);
// Ugly way of making sure title fits the box
if (sharedFunctions.hasCR(context)) {
final Book currentBook = sharedFunctions.loadCurrentlyReading(context);
lastReadTV.setVisibility(View.GONE);
Glide.with(contextShelf)
.load(currentBook.getImageURL())
.into(curCover);
if (currentBook.getTitle().length() > 130) {
curTitle.setTextSize(14);
} else if (currentBook.getTitle().length() > 75) {
curTitle.setTextSize(16);
} else if (currentBook.getTitle().length() > 60) {
curTitle.setTextSize(18);
} else {
curTitle.setTextSize(20);
}
TextView tvCategory = view.findViewById(R.id.categoryTV_shelf);
TextView tvLanguage = view.findViewById(R.id.languageTV_shelf);
tvCategory.setTypeface(infoFont);
tvCategory.setText(currentBook.getCategories());
tvLanguage.setTypeface(infoFont);
tvLanguage.setTextSize(15);
tvLanguage.setText(String.format(getResources().getString(R.string.languageString), currentBook.getLanguage().toUpperCase()));
Button moreInfoCRShelfButton = view.findViewById(R.id.more_info_out_button_shelf);
moreInfoCRShelfButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(contextShelf, bookDetail.class);
intent.putExtra("Book", currentBook);
contextShelf.startActivity(intent);
}
});
Button bookCRFinished = view.findViewById(R.id.mark_as_finished_button_shelf);
bookCRFinished.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sharedFunctions.addBookToArrayList(currentBook, context);
sharedFunctions.updateStreak(context);
sharedFunctions.removeCurrentlyReading(context);
if (getFragmentManager() != null) {
FragmentTransaction ftr1 = getFragmentManager().beginTransaction();
ftr1.detach(ShelfFragment.this).attach(ShelfFragment.this).commit();
}
}
});
final RelativeLayout relExpand = view.findViewById(R.id.rel_lay_more_info_shelf);
relExpand.measure(-2, -2);
relExpand.setVisibility(View.GONE);
rl_master.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isCRExpandedShelf) {
ExpandOrCollapse.collapse(relExpand, 250, 0);
isCRExpandedShelf = false;
} else {
ExpandOrCollapse.expand(relExpand, 250, 250);
isCRExpandedShelf = true;
}
}
});
curTitle.setText(currentBook.getTitle());
curAuthor.setText(currentBook.getAuthor());
curPages.setText(String.format(res.getString(R.string.cur_pages_string), goalFunctions.getProgress(context).toString(), currentBook.getPages()));
}
else if (sharedFunctions.loadArrayList(contextShelf).size() > 0) {
final Book lastReadBook = sharedFunctions.getLastReadBook(context);
currently.setVisibility(View.GONE);
lastReadTV.setVisibility(View.VISIBLE);
lastReadTV.setTypeface(titleFont);
Glide.with(contextShelf)
.load(lastReadBook.getImageURL())
.into(curCover);
if (lastReadBook.getTitle().length() > 130) {
curTitle.setTextSize(14);
} else if (lastReadBook.getTitle().length() > 75) {
curTitle.setTextSize(16);
} else if (lastReadBook.getTitle().length() > 60) {
curTitle.setTextSize(18);
} else {
curTitle.setTextSize(20);
}
rl_master.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(contextShelf, bookDetail.class);
intent.putExtra("Book", lastReadBook);
contextShelf.startActivity(intent);
}
});
curTitle.setText(lastReadBook.getTitle());
curAuthor.setText(lastReadBook.getAuthor());
curPages.setText(lastReadBook.getPages());
}
else {
rl_master.setVisibility(View.GONE);
currently.setVisibility(View.VISIBLE);
lastReadTV.setVisibility(View.GONE);
infoOnlyTV.setVisibility(View.VISIBLE);
}
return view;
}
// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new ShelfFinishedFragment(), "Finished Books");
adapter.addFragment(new ShelfToReadFragment(), "To-Read List");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
try {
InputMethodManager mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
UTF-8
|
Java
| 9,957 |
java
|
ShelfFragment.java
|
Java
|
[] | null |
[] |
package myrr.auto1.myreadingrecord1;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class ShelfFragment extends Fragment {
private boolean isCRExpandedShelf = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_shelf,container, false);
final Context contextShelf = getContext();
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) view.findViewById(R.id.result_tabs);
tabs.setupWithViewPager(viewPager);
final Context context = getActivity().getApplicationContext();
final Resources res = getResources();
Typeface infoFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Heebo-Light.ttf");
TextView currently = view.findViewById(R.id.currently_tv);
TextView lastReadTV = view.findViewById(R.id.lastread_tv);
ImageView curCover = view.findViewById(R.id.curBook_cover_shelf);
TextView curTitle = view.findViewById(R.id.curBook_title_shelf);
TextView curAuthor = view.findViewById(R.id.curBook_Author_shelf);
TextView curPages = view.findViewById(R.id.curBook_pages_shelf);
TextView infoOnlyTV = view.findViewById(R.id.only_info_tv);
infoOnlyTV.setVisibility(View.GONE);
final RelativeLayout rl_master = view.findViewById(R.id.rel_lay_all_book_shelf);
Typeface titleFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Oswald-Regular.ttf");
curTitle.setTypeface(titleFont);
currently.setTypeface(titleFont);
curTitle.setPaintFlags(curTitle.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Typeface authorFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Oswald-Light.ttf");
curAuthor.setTextSize(15);
curAuthor.setTypeface(authorFont);
curPages.setTextSize(13);
curPages.setTypeface(authorFont);
curCover.setScaleType(ImageView.ScaleType.FIT_XY);
// Ugly way of making sure title fits the box
if (sharedFunctions.hasCR(context)) {
final Book currentBook = sharedFunctions.loadCurrentlyReading(context);
lastReadTV.setVisibility(View.GONE);
Glide.with(contextShelf)
.load(currentBook.getImageURL())
.into(curCover);
if (currentBook.getTitle().length() > 130) {
curTitle.setTextSize(14);
} else if (currentBook.getTitle().length() > 75) {
curTitle.setTextSize(16);
} else if (currentBook.getTitle().length() > 60) {
curTitle.setTextSize(18);
} else {
curTitle.setTextSize(20);
}
TextView tvCategory = view.findViewById(R.id.categoryTV_shelf);
TextView tvLanguage = view.findViewById(R.id.languageTV_shelf);
tvCategory.setTypeface(infoFont);
tvCategory.setText(currentBook.getCategories());
tvLanguage.setTypeface(infoFont);
tvLanguage.setTextSize(15);
tvLanguage.setText(String.format(getResources().getString(R.string.languageString), currentBook.getLanguage().toUpperCase()));
Button moreInfoCRShelfButton = view.findViewById(R.id.more_info_out_button_shelf);
moreInfoCRShelfButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(contextShelf, bookDetail.class);
intent.putExtra("Book", currentBook);
contextShelf.startActivity(intent);
}
});
Button bookCRFinished = view.findViewById(R.id.mark_as_finished_button_shelf);
bookCRFinished.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sharedFunctions.addBookToArrayList(currentBook, context);
sharedFunctions.updateStreak(context);
sharedFunctions.removeCurrentlyReading(context);
if (getFragmentManager() != null) {
FragmentTransaction ftr1 = getFragmentManager().beginTransaction();
ftr1.detach(ShelfFragment.this).attach(ShelfFragment.this).commit();
}
}
});
final RelativeLayout relExpand = view.findViewById(R.id.rel_lay_more_info_shelf);
relExpand.measure(-2, -2);
relExpand.setVisibility(View.GONE);
rl_master.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isCRExpandedShelf) {
ExpandOrCollapse.collapse(relExpand, 250, 0);
isCRExpandedShelf = false;
} else {
ExpandOrCollapse.expand(relExpand, 250, 250);
isCRExpandedShelf = true;
}
}
});
curTitle.setText(currentBook.getTitle());
curAuthor.setText(currentBook.getAuthor());
curPages.setText(String.format(res.getString(R.string.cur_pages_string), goalFunctions.getProgress(context).toString(), currentBook.getPages()));
}
else if (sharedFunctions.loadArrayList(contextShelf).size() > 0) {
final Book lastReadBook = sharedFunctions.getLastReadBook(context);
currently.setVisibility(View.GONE);
lastReadTV.setVisibility(View.VISIBLE);
lastReadTV.setTypeface(titleFont);
Glide.with(contextShelf)
.load(lastReadBook.getImageURL())
.into(curCover);
if (lastReadBook.getTitle().length() > 130) {
curTitle.setTextSize(14);
} else if (lastReadBook.getTitle().length() > 75) {
curTitle.setTextSize(16);
} else if (lastReadBook.getTitle().length() > 60) {
curTitle.setTextSize(18);
} else {
curTitle.setTextSize(20);
}
rl_master.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(contextShelf, bookDetail.class);
intent.putExtra("Book", lastReadBook);
contextShelf.startActivity(intent);
}
});
curTitle.setText(lastReadBook.getTitle());
curAuthor.setText(lastReadBook.getAuthor());
curPages.setText(lastReadBook.getPages());
}
else {
rl_master.setVisibility(View.GONE);
currently.setVisibility(View.VISIBLE);
lastReadTV.setVisibility(View.GONE);
infoOnlyTV.setVisibility(View.VISIBLE);
}
return view;
}
// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new ShelfFinishedFragment(), "Finished Books");
adapter.addFragment(new ShelfToReadFragment(), "To-Read List");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
try {
InputMethodManager mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 9,957 | 0.626594 | 0.620568 | 255 | 38.05098 | 29.584066 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611765 | false | false |
12
|
80289bfb0bdec7d90795a9be86d1cbcb1ab4b790
| 17,042,430,247,031 |
8066ae31e02487a3a9b3124fa3d8ac26c6f3363b
|
/aviatorTest/src/main/java/Hello.java
|
8d1670caadd88f5767bb39a603c992fb07c6df50
|
[] |
no_license
|
zhunhuang/java-demos
|
https://github.com/zhunhuang/java-demos
|
5dc35cdad69550a4d3883b63e0e6ca3ab8e09f0f
|
ab2cd34065f7bd9f54c409eb9ccfca90ad8567a9
|
refs/heads/master
| 2022-12-21T03:24:23.734000 | 2021-02-24T10:15:48 | 2021-02-24T10:15:48 | 191,360,988 | 0 | 1 | null | false | 2022-12-16T08:51:59 | 2019-06-11T11:48:29 | 2021-02-24T10:16:00 | 2022-12-16T08:51:58 | 1,215 | 0 | 1 | 40 |
JavaScript
| false | false |
import com.googlecode.aviator.AviatorEvaluator;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* description:
*
* @author zhunhuang, 2019/11/6
*/
@RunWith(JUnit4.class)
public class Hello {
public static void main(String[] args) {
Long result = (Long) AviatorEvaluator.execute("1+2+3");
System.out.println(result);
}
}
|
UTF-8
|
Java
| 372 |
java
|
Hello.java
|
Java
|
[
{
"context": "runners.JUnit4;\n\n/**\n * description:\n *\n * @author zhunhuang, 2019/11/6\n */\n@RunWith(JUnit4.class)\npublic clas",
"end": 158,
"score": 0.9994175434112549,
"start": 149,
"tag": "USERNAME",
"value": "zhunhuang"
}
] | null |
[] |
import com.googlecode.aviator.AviatorEvaluator;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* description:
*
* @author zhunhuang, 2019/11/6
*/
@RunWith(JUnit4.class)
public class Hello {
public static void main(String[] args) {
Long result = (Long) AviatorEvaluator.execute("1+2+3");
System.out.println(result);
}
}
| 372 | 0.685484 | 0.653226 | 17 | 20.882353 | 18.929848 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false |
12
|
da65552e0763a728e189854913d671be524a4a0f
| 17,042,430,248,739 |
d186b5b32f4589a6bb3574fb49482913c038bad1
|
/src/com/herocraftonline/townships/api/Region.java
|
1460a68706588bc660ca01cc349ea429211c2c13
|
[] |
no_license
|
Trist95/Herotowns
|
https://github.com/Trist95/Herotowns
|
42117faf0af8f682818c322a678f32ffdefe3163
|
7a5bfbabb657ba9021852ee1bc64a421832b1fae
|
refs/heads/master
| 2020-05-21T11:57:15.826000 | 2014-03-11T05:54:55 | 2014-03-11T05:54:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.herocraftonline.townships.api;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* The Abstract Region wrapper for Townships, handling the basics of having an Owner, Manager and Member
* while handling the intermediary method calls to WorldGuard's ProtectedRegion.
*
* Author: gabizou
*/
public class Region {
protected ProtectedRegion region;
protected Set<String> owners = new HashSet<>();
protected Set<String> managers = new HashSet<>();
protected Set<String> guests = new HashSet<>();
public Region(ProtectedRegion region) {
this(region,region.getOwners().getPlayers());
}
public Region(ProtectedRegion region, String owner) {
this.region = region;
addOwner(owner);
}
public Region(ProtectedRegion region, Set<String> owners) {
this.region = region;
addOwners(owners);
}
public ProtectedRegion getWorldGuardRegion() {
return region;
}
public void addOwner(String player) {
region.getOwners().addPlayer(player.toLowerCase());
owners.add(player.toLowerCase());
}
public void addOwners(Collection<String> players) {
for (String player : players)
addOwner(player.toLowerCase());
}
public void addManager(String player) {
if (guests.contains(player.toLowerCase()))
guests.remove(player.toLowerCase());
managers.add(player.toLowerCase());
checkMembership(player);
}
public void addManagers(Collection<String> players) {
for (String name : players)
addManager(name);
}
public void addGuest(String player) {
checkMembership(player);
guests.add(player.toLowerCase());
}
public void addGuests(Collection<String> players) {
for (String name : players)
addGuest(name);
}
public boolean isOwner(String player) {
return owners.contains(player.toLowerCase());
}
public boolean isManager(String player) {
return managers.contains(player.toLowerCase());
}
public boolean isGuest(String player) {
return guests.contains(player.toLowerCase());
}
public void removeMember(String player) {
guests.remove(player);
guests.remove(player.toLowerCase());
managers.remove(player);
managers.remove(player.toLowerCase());
owners.remove(player);
owners.remove(player.toLowerCase());
region.getMembers().removePlayer(player);
region.getOwners().removePlayer(player);
}
public String getName() {
return region.getId();
}
public Set<String> getGuests() {
return Collections.unmodifiableSet(guests);
}
public Set<String> getManagers() {
return Collections.unmodifiableSet(managers);
}
public Set<String> getOwners() {
return Collections.unmodifiableSet(owners);
}
private void checkMembership(String player) {
if (!region.getMembers().contains(player.toLowerCase()))
region.getMembers().addPlayer(player.toLowerCase());
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Region))
return false;
return ((Region) obj).region.getId().equals(region.getId());
}
@Override
public int hashCode() {
return region.getId().hashCode();
}
@Override
public String toString() {
return region.getId();
}
}
|
UTF-8
|
Java
| 3,664 |
java
|
Region.java
|
Java
|
[
{
"context": "lls to WorldGuard's ProtectedRegion.\n *\n * Author: gabizou\n */\npublic class Region {\n\n protected Protecte",
"end": 428,
"score": 0.9996598362922668,
"start": 421,
"tag": "USERNAME",
"value": "gabizou"
}
] | null |
[] |
package com.herocraftonline.townships.api;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* The Abstract Region wrapper for Townships, handling the basics of having an Owner, Manager and Member
* while handling the intermediary method calls to WorldGuard's ProtectedRegion.
*
* Author: gabizou
*/
public class Region {
protected ProtectedRegion region;
protected Set<String> owners = new HashSet<>();
protected Set<String> managers = new HashSet<>();
protected Set<String> guests = new HashSet<>();
public Region(ProtectedRegion region) {
this(region,region.getOwners().getPlayers());
}
public Region(ProtectedRegion region, String owner) {
this.region = region;
addOwner(owner);
}
public Region(ProtectedRegion region, Set<String> owners) {
this.region = region;
addOwners(owners);
}
public ProtectedRegion getWorldGuardRegion() {
return region;
}
public void addOwner(String player) {
region.getOwners().addPlayer(player.toLowerCase());
owners.add(player.toLowerCase());
}
public void addOwners(Collection<String> players) {
for (String player : players)
addOwner(player.toLowerCase());
}
public void addManager(String player) {
if (guests.contains(player.toLowerCase()))
guests.remove(player.toLowerCase());
managers.add(player.toLowerCase());
checkMembership(player);
}
public void addManagers(Collection<String> players) {
for (String name : players)
addManager(name);
}
public void addGuest(String player) {
checkMembership(player);
guests.add(player.toLowerCase());
}
public void addGuests(Collection<String> players) {
for (String name : players)
addGuest(name);
}
public boolean isOwner(String player) {
return owners.contains(player.toLowerCase());
}
public boolean isManager(String player) {
return managers.contains(player.toLowerCase());
}
public boolean isGuest(String player) {
return guests.contains(player.toLowerCase());
}
public void removeMember(String player) {
guests.remove(player);
guests.remove(player.toLowerCase());
managers.remove(player);
managers.remove(player.toLowerCase());
owners.remove(player);
owners.remove(player.toLowerCase());
region.getMembers().removePlayer(player);
region.getOwners().removePlayer(player);
}
public String getName() {
return region.getId();
}
public Set<String> getGuests() {
return Collections.unmodifiableSet(guests);
}
public Set<String> getManagers() {
return Collections.unmodifiableSet(managers);
}
public Set<String> getOwners() {
return Collections.unmodifiableSet(owners);
}
private void checkMembership(String player) {
if (!region.getMembers().contains(player.toLowerCase()))
region.getMembers().addPlayer(player.toLowerCase());
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Region))
return false;
return ((Region) obj).region.getId().equals(region.getId());
}
@Override
public int hashCode() {
return region.getId().hashCode();
}
@Override
public String toString() {
return region.getId();
}
}
| 3,664 | 0.643013 | 0.642467 | 137 | 25.744526 | 22.43239 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.379562 | false | false |
12
|
1379d4cbdc4356d12c438f89592b1667aee9b55a
| 9,483,287,808,663 |
b1ea82ede5f3cce3fd1f839e5cdfc3ad827d64aa
|
/app/src/main/java/org/nuclearfog/twidda/backend/TrendListLoader.java
|
4fa84de29de808955f8d2a0fba09a834c79d1688
|
[
"Apache-2.0"
] |
permissive
|
zpcol/Shitter
|
https://github.com/zpcol/Shitter
|
4f45a98980c7ca0a907498756c384ae5f98c37f8
|
91b778ab92642b7cb3bf5bfdab743bfe96509eb8
|
refs/heads/master
| 2022-12-20T14:14:36.322000 | 2020-10-05T16:01:36 | 2020-10-05T16:01:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.nuclearfog.twidda.backend;
import android.os.AsyncTask;
import androidx.annotation.Nullable;
import org.nuclearfog.twidda.backend.engine.EngineException;
import org.nuclearfog.twidda.backend.engine.TwitterEngine;
import org.nuclearfog.twidda.backend.items.TwitterTrend;
import org.nuclearfog.twidda.database.AppDatabase;
import org.nuclearfog.twidda.fragment.TrendFragment;
import java.lang.ref.WeakReference;
import java.util.List;
/**
* Background task to load a list of location specific trends
*
* @see TrendFragment
*/
public class TrendListLoader extends AsyncTask<Integer, Void, List<TwitterTrend>> {
@Nullable
private EngineException twException;
private WeakReference<TrendFragment> callback;
private TwitterEngine mTwitter;
private AppDatabase db;
private boolean isEmpty;
public TrendListLoader(TrendFragment callback) {
this.callback = new WeakReference<>(callback);
db = new AppDatabase(callback.getContext());
mTwitter = TwitterEngine.getInstance(callback.getContext());
isEmpty = callback.isEmpty();
}
@Override
protected void onPreExecute() {
if (callback.get() != null)
callback.get().setRefresh(true);
}
@Override
protected List<TwitterTrend> doInBackground(Integer[] param) {
List<TwitterTrend> trends;
int woeId = param[0];
try {
if (isEmpty) {
trends = db.getTrends(woeId);
if (trends.isEmpty()) {
trends = mTwitter.getTrends(woeId);
db.storeTrends(trends, woeId);
}
} else {
trends = mTwitter.getTrends(woeId);
db.storeTrends(trends, woeId);
}
return trends;
} catch (EngineException twException) {
this.twException = twException;
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<TwitterTrend> trends) {
if (callback.get() != null) {
callback.get().setRefresh(false);
if (trends != null) {
callback.get().setData(trends);
}
if (twException != null) {
callback.get().onError(twException);
}
}
}
}
|
UTF-8
|
Java
| 2,397 |
java
|
TrendListLoader.java
|
Java
|
[] | null |
[] |
package org.nuclearfog.twidda.backend;
import android.os.AsyncTask;
import androidx.annotation.Nullable;
import org.nuclearfog.twidda.backend.engine.EngineException;
import org.nuclearfog.twidda.backend.engine.TwitterEngine;
import org.nuclearfog.twidda.backend.items.TwitterTrend;
import org.nuclearfog.twidda.database.AppDatabase;
import org.nuclearfog.twidda.fragment.TrendFragment;
import java.lang.ref.WeakReference;
import java.util.List;
/**
* Background task to load a list of location specific trends
*
* @see TrendFragment
*/
public class TrendListLoader extends AsyncTask<Integer, Void, List<TwitterTrend>> {
@Nullable
private EngineException twException;
private WeakReference<TrendFragment> callback;
private TwitterEngine mTwitter;
private AppDatabase db;
private boolean isEmpty;
public TrendListLoader(TrendFragment callback) {
this.callback = new WeakReference<>(callback);
db = new AppDatabase(callback.getContext());
mTwitter = TwitterEngine.getInstance(callback.getContext());
isEmpty = callback.isEmpty();
}
@Override
protected void onPreExecute() {
if (callback.get() != null)
callback.get().setRefresh(true);
}
@Override
protected List<TwitterTrend> doInBackground(Integer[] param) {
List<TwitterTrend> trends;
int woeId = param[0];
try {
if (isEmpty) {
trends = db.getTrends(woeId);
if (trends.isEmpty()) {
trends = mTwitter.getTrends(woeId);
db.storeTrends(trends, woeId);
}
} else {
trends = mTwitter.getTrends(woeId);
db.storeTrends(trends, woeId);
}
return trends;
} catch (EngineException twException) {
this.twException = twException;
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<TwitterTrend> trends) {
if (callback.get() != null) {
callback.get().setRefresh(false);
if (trends != null) {
callback.get().setData(trends);
}
if (twException != null) {
callback.get().onError(twException);
}
}
}
}
| 2,397 | 0.61869 | 0.618273 | 84 | 27.547619 | 21.641783 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452381 | false | false |
12
|
84993e78aa37b38d06e6dcaee8a11f321345431b
| 11,355,893,547,332 |
2703750c143b95da277a1340269f5ec6a7af654c
|
/student-information-circle-service/src/main/java/com/shenghesun/sic/cost/record/service/ExchangeRateService.java
|
de47010bd0cd27cfb3e4601d03b6632f6508b459
|
[] |
no_license
|
KevinDingFeng/sic-web
|
https://github.com/KevinDingFeng/sic-web
|
4aedbc38e576f5932182a7972ef6caba0a0eb3fa
|
4e3709cb0b53a2446fd02ee8adcfa2a25d9529a6
|
refs/heads/master
| 2020-04-12T14:55:29.807000 | 2019-01-02T04:42:33 | 2019-01-02T04:42:33 | 162,565,522 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.shenghesun.sic.cost.record.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.shenghesun.sic.cost.record.dao.ExchangeRateDao;
import com.shenghesun.sic.cost.record.entity.ExchangeRate;
/**
* @ClassName: ExchangeRateService
* @Description: 兑换比例和推荐提成比例控制
* @author: yangzp
* @date: 2018年11月26日 上午9:59:05
*/
@Transactional(readOnly = true)
@Service
public class ExchangeRateService {
@Autowired
private ExchangeRateDao exchangeRateDao;
/**
* @Title: getValidRate
* @Description: 获取 seqNum 最大的记录作为兑换标准
* @return ExchangeRate
* @author yangzp
* @date 2018年11月26日上午10:00:48
**/
public ExchangeRate getValidRate() {
return exchangeRateDao.getValidRate();
}
}
|
UTF-8
|
Java
| 926 |
java
|
ExchangeRateService.java
|
Java
|
[
{
"context": "vice \n * @Description: 兑换比例和推荐提成比例控制\n * @author: yangzp\n * @date: 2018年11月26日 上午9:59:05 \n */\n@Transact",
"end": 437,
"score": 0.9996615648269653,
"start": 431,
"tag": "USERNAME",
"value": "yangzp"
},
{
"context": "的记录作为兑换标准 \n\t * @return ExchangeRate \n\t * @author yangzp\n\t * @date 2018年11月26日上午10:00:48\n\t **/ \n\tpublic Ex",
"end": 729,
"score": 0.9996668100357056,
"start": 723,
"tag": "USERNAME",
"value": "yangzp"
}
] | null |
[] |
package com.shenghesun.sic.cost.record.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.shenghesun.sic.cost.record.dao.ExchangeRateDao;
import com.shenghesun.sic.cost.record.entity.ExchangeRate;
/**
* @ClassName: ExchangeRateService
* @Description: 兑换比例和推荐提成比例控制
* @author: yangzp
* @date: 2018年11月26日 上午9:59:05
*/
@Transactional(readOnly = true)
@Service
public class ExchangeRateService {
@Autowired
private ExchangeRateDao exchangeRateDao;
/**
* @Title: getValidRate
* @Description: 获取 seqNum 最大的记录作为兑换标准
* @return ExchangeRate
* @author yangzp
* @date 2018年11月26日上午10:00:48
**/
public ExchangeRate getValidRate() {
return exchangeRateDao.getValidRate();
}
}
| 926 | 0.762295 | 0.730679 | 34 | 24.117647 | 20.50791 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false |
12
|
5a8043b813c54ffb93dad0b6a5dc1c9a39618066
| 17,514,876,653,544 |
42494db6734ac6b3bde5d14438f6817f1caa456a
|
/phoenix-console/src/main/java/com/dianping/phoenix/service/DefaultProjectManager.java
|
24691268dc5e748cf40f2f14c59ff456b2fab3eb
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
sunryuan/phoenix
|
https://github.com/sunryuan/phoenix
|
cdb35bb1f46da8e7b83f6107c7bef7338e4ee9f7
|
c9451e249e50d60147efb3fc2f48466dc68f3cfe
|
refs/heads/master
| 2021-01-10T03:06:17.394000 | 2013-05-15T09:05:00 | 2013-05-15T09:05:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dianping.phoenix.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.dal.jdbc.DalNotFoundException;
import org.unidal.lookup.annotation.Inject;
import org.xml.sax.SAXException;
import com.dianping.phoenix.console.dal.deploy.Deployment;
import com.dianping.phoenix.console.dal.deploy.DeploymentDao;
import com.dianping.phoenix.console.dal.deploy.DeploymentDetails;
import com.dianping.phoenix.console.dal.deploy.DeploymentDetailsDao;
import com.dianping.phoenix.console.dal.deploy.DeploymentDetailsEntity;
import com.dianping.phoenix.console.dal.deploy.DeploymentEntity;
import com.dianping.phoenix.deploy.DeployPlan;
import com.dianping.phoenix.deploy.model.entity.DeployModel;
import com.dianping.phoenix.deploy.model.entity.HostModel;
import com.dianping.phoenix.project.entity.BussinessLine;
import com.dianping.phoenix.project.entity.Project;
import com.dianping.phoenix.project.entity.Root;
import com.dianping.phoenix.project.transform.DefaultSaxParser;
public class DefaultProjectManager implements ProjectManager, Initializable, LogEnabled{
@Inject
private DeploymentDao m_deploymentDao;
@Inject
private DeploymentDetailsDao m_deploymentDetailsDao;
@Inject
private DeviceManager m_deviceManager;
private Root m_root;
private Logger m_logger;
private Map<String, DeployModel> m_models = new HashMap<String, DeployModel>();
@Override
public void enableLogging(Logger logger) {
this.m_logger = logger;
}
@Override
public Deployment findActiveDeploy(String type, String name) {
try {
Deployment deploy = m_deploymentDao.findActiveByWarTypeAndDomain(type, name, DeploymentEntity.READSET_FULL);
return deploy;
} catch (DalNotFoundException e) {
return null;
} catch (Exception e) {
throw new RuntimeException(String.format("Error when finding active deployment by name(%s)!", name));
}
}
@Override
public DeployModel findModel(int deployId) {
for (DeployModel model : m_models.values()) {
if (model.getId() == deployId) {
return model;
}
}
try {
Deployment d = m_deploymentDao.findByPK(deployId, DeploymentEntity.READSET_FULL);
List<DeploymentDetails> detailsList = m_deploymentDetailsDao.findAllByDeployId(deployId,
DeploymentDetailsEntity.READSET_FULL);
DeployModel model = new DeployModel();
DeployPlan plan = new DeployPlan();
for (DeploymentDetails details : detailsList) {
String rawLog = details.getRawLog();
DeployModel deploy = com.dianping.phoenix.deploy.model.transform.DefaultSaxParser.parse(rawLog);
for (HostModel host : deploy.getHosts().values()) {
model.addHost(host);
}
}
model.setId(deployId);
model.setDomain(d.getDomain());
model.setPlan(plan);
plan.setAbortOnError(d.getErrorPolicy() == 1);
plan.setPolicy(d.getStrategy());
plan.setVersion(d.getWarVersion());
plan.setSkipTest(d.getSkipTest() == 1);
storeModel(model);
return model;
} catch (DalNotFoundException e) {
// ignore it
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void initialize() throws InitializationException {
try {
m_root = readConfigFromFile();
} catch (Exception e) {
throw new RuntimeException(
"Unable to load deploy model from resource(project.xml)!", e);
}
}
private Root readConfigFromFile() throws SAXException, IOException{
Root root = null;
File file = new File("/data/appdatas/phoenix/project.xml");
InputStream in = null;
if (file.exists()) {
in = new FileInputStream(file);
System.out.println("read project.xml from /data/appdatas/phoenix/project.xml");
}
if (in == null) {
// TODO test purpose
in = getClass().getResourceAsStream("/com/dianping/phoenix/deploy/project.xml");
System.out.println("read project.xml from classpath");
}
root = DefaultSaxParser.parse(in);
return root;
}
@Override
public List<BussinessLine> getBussinessLineList() throws Exception {
Root root;
try{
root = readConfigFromFile();
} catch(Exception e) {
m_logger.warn("Fail to read project.xml",e);
root = m_root;
}
List<BussinessLine> list = new ArrayList<BussinessLine>();
list.addAll(root.getBussinessLines().values());
return list;
}
@Override
public void storeModel(DeployModel model) {
m_models.put(model.getDomain(), model);
}
@Override
public Project findProjectBy(String name) throws Exception {
return m_deviceManager.findProjectBy(name);
}
}
|
UTF-8
|
Java
| 4,901 |
java
|
DefaultProjectManager.java
|
Java
|
[] | null |
[] |
package com.dianping.phoenix.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.dal.jdbc.DalNotFoundException;
import org.unidal.lookup.annotation.Inject;
import org.xml.sax.SAXException;
import com.dianping.phoenix.console.dal.deploy.Deployment;
import com.dianping.phoenix.console.dal.deploy.DeploymentDao;
import com.dianping.phoenix.console.dal.deploy.DeploymentDetails;
import com.dianping.phoenix.console.dal.deploy.DeploymentDetailsDao;
import com.dianping.phoenix.console.dal.deploy.DeploymentDetailsEntity;
import com.dianping.phoenix.console.dal.deploy.DeploymentEntity;
import com.dianping.phoenix.deploy.DeployPlan;
import com.dianping.phoenix.deploy.model.entity.DeployModel;
import com.dianping.phoenix.deploy.model.entity.HostModel;
import com.dianping.phoenix.project.entity.BussinessLine;
import com.dianping.phoenix.project.entity.Project;
import com.dianping.phoenix.project.entity.Root;
import com.dianping.phoenix.project.transform.DefaultSaxParser;
public class DefaultProjectManager implements ProjectManager, Initializable, LogEnabled{
@Inject
private DeploymentDao m_deploymentDao;
@Inject
private DeploymentDetailsDao m_deploymentDetailsDao;
@Inject
private DeviceManager m_deviceManager;
private Root m_root;
private Logger m_logger;
private Map<String, DeployModel> m_models = new HashMap<String, DeployModel>();
@Override
public void enableLogging(Logger logger) {
this.m_logger = logger;
}
@Override
public Deployment findActiveDeploy(String type, String name) {
try {
Deployment deploy = m_deploymentDao.findActiveByWarTypeAndDomain(type, name, DeploymentEntity.READSET_FULL);
return deploy;
} catch (DalNotFoundException e) {
return null;
} catch (Exception e) {
throw new RuntimeException(String.format("Error when finding active deployment by name(%s)!", name));
}
}
@Override
public DeployModel findModel(int deployId) {
for (DeployModel model : m_models.values()) {
if (model.getId() == deployId) {
return model;
}
}
try {
Deployment d = m_deploymentDao.findByPK(deployId, DeploymentEntity.READSET_FULL);
List<DeploymentDetails> detailsList = m_deploymentDetailsDao.findAllByDeployId(deployId,
DeploymentDetailsEntity.READSET_FULL);
DeployModel model = new DeployModel();
DeployPlan plan = new DeployPlan();
for (DeploymentDetails details : detailsList) {
String rawLog = details.getRawLog();
DeployModel deploy = com.dianping.phoenix.deploy.model.transform.DefaultSaxParser.parse(rawLog);
for (HostModel host : deploy.getHosts().values()) {
model.addHost(host);
}
}
model.setId(deployId);
model.setDomain(d.getDomain());
model.setPlan(plan);
plan.setAbortOnError(d.getErrorPolicy() == 1);
plan.setPolicy(d.getStrategy());
plan.setVersion(d.getWarVersion());
plan.setSkipTest(d.getSkipTest() == 1);
storeModel(model);
return model;
} catch (DalNotFoundException e) {
// ignore it
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void initialize() throws InitializationException {
try {
m_root = readConfigFromFile();
} catch (Exception e) {
throw new RuntimeException(
"Unable to load deploy model from resource(project.xml)!", e);
}
}
private Root readConfigFromFile() throws SAXException, IOException{
Root root = null;
File file = new File("/data/appdatas/phoenix/project.xml");
InputStream in = null;
if (file.exists()) {
in = new FileInputStream(file);
System.out.println("read project.xml from /data/appdatas/phoenix/project.xml");
}
if (in == null) {
// TODO test purpose
in = getClass().getResourceAsStream("/com/dianping/phoenix/deploy/project.xml");
System.out.println("read project.xml from classpath");
}
root = DefaultSaxParser.parse(in);
return root;
}
@Override
public List<BussinessLine> getBussinessLineList() throws Exception {
Root root;
try{
root = readConfigFromFile();
} catch(Exception e) {
m_logger.warn("Fail to read project.xml",e);
root = m_root;
}
List<BussinessLine> list = new ArrayList<BussinessLine>();
list.addAll(root.getBussinessLines().values());
return list;
}
@Override
public void storeModel(DeployModel model) {
m_models.put(model.getDomain(), model);
}
@Override
public Project findProjectBy(String name) throws Exception {
return m_deviceManager.findProjectBy(name);
}
}
| 4,901 | 0.748827 | 0.748419 | 173 | 27.329479 | 26.625015 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.901734 | false | false |
12
|
621d5105d4ca537e75e1c284d160cb39d96c1ef3
| 1,400,159,359,104 |
5b89c1b4cd0f826ef833ef5fef8b7c5a86bcefe2
|
/app/src/main/java/com/example/myhome/PaymentMode.java
|
40fc385dc3c2b03210605fbb96ddefbb0ebb1697
|
[] |
no_license
|
TEGDHILLON/rental-home
|
https://github.com/TEGDHILLON/rental-home
|
c505864f25ab8730d8619c05de49f13ac58cdc74
|
2f63aa16722328623547168dcc8e30adf50bc74c
|
refs/heads/master
| 2022-12-25T03:39:16.093000 | 2020-09-30T23:26:29 | 2020-09-30T23:26:29 | 300,086,589 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.myhome;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class PaymentMode extends Activity {
RadioGroup rdg;
RadioButton rdbt1, rdbt2, rdbt3;
Button bt;
Intent it;
String str,apt;
TextView TvCashPayment,TvPayAmount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_mode);
rdg = findViewById(R.id.rdgrp);
rdbt1 = findViewById(R.id.rbcash);
rdbt2 = findViewById(R.id.rbcredit);
rdbt3 = findViewById(R.id.rbdebit);
bt = findViewById(R.id.btProceedToPay);
TvCashPayment = findViewById(R.id.cashpayment);
TvPayAmount = findViewById(R.id.payamount);
try {
it=getIntent();
str = it.getStringExtra("Amount");
apt = it.getStringExtra("Apartment");
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
TvPayAmount.setText("Amount to be Paid is: " + str);
}catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
rdbt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(PaymentMode.this, "Cash Payment Mode Selected", Toast.LENGTH_SHORT).show();
}
});
rdbt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// str = (it.getStringExtra("Cash"));
// if(str!=null) it.removeExtra("Cash");
//
//
// str = (it.getStringExtra("Debit"));
// if(str!=null) it.removeExtra("Debit");
runOnUiThread(new Runnable() {
@Override
public void run() {
TvCashPayment.setText("");
}
});
Toast.makeText(PaymentMode.this, "Credit Card Mode Selected", Toast.LENGTH_SHORT).show();
}
});
rdbt3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
runOnUiThread(new Runnable() {
@Override
public void run() {
TvCashPayment.setText("");
}
});
Toast.makeText(PaymentMode.this, "Debit Card Mode Selected", Toast.LENGTH_SHORT).show();
}
});
}
public void proceedToPay(View view) {
if(rdbt1.isChecked())
{
runOnUiThread(new Runnable() {
@Override
public void run() {
TvCashPayment.setText("Please pay the cash and notify the owner!");
}
});
}
else if(rdbt2.isChecked())
{
it = new Intent(this, Payment.class);
it.putExtra("Credit",0);
it.putExtra("Amount",str);
it.putExtra("Apartment",apt);
startActivity(it);
}
else if(rdbt3.isChecked())
{
it = new Intent(this, Payment.class);
it.putExtra("Debit",1);
it.putExtra("Amount",str);
it.putExtra("Apartment",apt);
startActivity(it);
}
else {
Toast.makeText(this, "Choose any Payment Mode", Toast.LENGTH_LONG).show();
}
}
}
|
UTF-8
|
Java
| 3,882 |
java
|
PaymentMode.java
|
Java
|
[] | null |
[] |
package com.example.myhome;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class PaymentMode extends Activity {
RadioGroup rdg;
RadioButton rdbt1, rdbt2, rdbt3;
Button bt;
Intent it;
String str,apt;
TextView TvCashPayment,TvPayAmount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_mode);
rdg = findViewById(R.id.rdgrp);
rdbt1 = findViewById(R.id.rbcash);
rdbt2 = findViewById(R.id.rbcredit);
rdbt3 = findViewById(R.id.rbdebit);
bt = findViewById(R.id.btProceedToPay);
TvCashPayment = findViewById(R.id.cashpayment);
TvPayAmount = findViewById(R.id.payamount);
try {
it=getIntent();
str = it.getStringExtra("Amount");
apt = it.getStringExtra("Apartment");
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
TvPayAmount.setText("Amount to be Paid is: " + str);
}catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
rdbt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(PaymentMode.this, "Cash Payment Mode Selected", Toast.LENGTH_SHORT).show();
}
});
rdbt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// str = (it.getStringExtra("Cash"));
// if(str!=null) it.removeExtra("Cash");
//
//
// str = (it.getStringExtra("Debit"));
// if(str!=null) it.removeExtra("Debit");
runOnUiThread(new Runnable() {
@Override
public void run() {
TvCashPayment.setText("");
}
});
Toast.makeText(PaymentMode.this, "Credit Card Mode Selected", Toast.LENGTH_SHORT).show();
}
});
rdbt3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
runOnUiThread(new Runnable() {
@Override
public void run() {
TvCashPayment.setText("");
}
});
Toast.makeText(PaymentMode.this, "Debit Card Mode Selected", Toast.LENGTH_SHORT).show();
}
});
}
public void proceedToPay(View view) {
if(rdbt1.isChecked())
{
runOnUiThread(new Runnable() {
@Override
public void run() {
TvCashPayment.setText("Please pay the cash and notify the owner!");
}
});
}
else if(rdbt2.isChecked())
{
it = new Intent(this, Payment.class);
it.putExtra("Credit",0);
it.putExtra("Amount",str);
it.putExtra("Apartment",apt);
startActivity(it);
}
else if(rdbt3.isChecked())
{
it = new Intent(this, Payment.class);
it.putExtra("Debit",1);
it.putExtra("Amount",str);
it.putExtra("Apartment",apt);
startActivity(it);
}
else {
Toast.makeText(this, "Choose any Payment Mode", Toast.LENGTH_LONG).show();
}
}
}
| 3,882 | 0.540701 | 0.537094 | 135 | 27.762962 | 23.807005 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622222 | false | false |
12
|
a64eff35ce36da40850c935e39206e3bc595b54f
| 16,587,163,732,114 |
d04f1e1d63ca803ef90a757e6c029f4fc0e1d217
|
/src/cn/edu/buaa/act/service4all/webapp/qualification/QualificationUtil.java
|
25bfe5fd3a218b219447a2e863fd9e5523458530
|
[] |
no_license
|
winstone/Service4All
|
https://github.com/winstone/Service4All
|
e7c08286c3704892798f91eb70a8247b20748856
|
a190a95a2599e75ae533699c62c494923f6660ac
|
refs/heads/master
| 2021-01-01T17:28:09.499000 | 2014-08-04T07:59:58 | 2014-08-04T07:59:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Service4All: A Service-oriented Cloud Platform for All about Software Development
* Copyright (C) Institute of Advanced Computing Technology, Beihang University
* Contact: service4all@act.buaa.edu.cn
*
* This library 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 3.0 of the License, or any later version.
*
* This library 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 General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package cn.edu.buaa.act.service4all.webapp.qualification;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import cn.edu.buaa.act.service4all.webapp.utility.Constants;
import cn.edu.buaa.act.service4all.webapp.utility.XMLUtil;
public class QualificationUtil {
private final static Log logger = LogFactory.getLog(QualificationUtil.class);
public static Document getResult(Document document, String url) {
File tmp = null;
String tmpresult = null;
Document result = null;
tmp = saveXmlToFile(document);
if (tmp == null)
return null;
tmpresult = sendAndGetResult(tmp, url);
if (tmpresult == null)
return null;
result = XMLUtil.StringToDoc(tmpresult);
return result;
}
private static String sendAndGetResult(File tmp, String url) {
PostMethod post = new PostMethod(url);
RequestEntity entity = new FileRequestEntity(tmp, Constants.CODE);
post.setRequestEntity(entity);
HttpClient client = new HttpClient();
String result = null;
try {
int resultCode = client.executeMethod(post);
logger.info(resultCode);
result = post.getResponseBodyAsString();
logger.info("Response body:\n " + result);
// remove the tmp file
tmp.delete();
post.releaseConnection();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static File saveXmlToFile(Document doc) {
File tmp = new File(Constants.FILE_PERFIX
+ Calendar.getInstance().getTimeInMillis()
+ Constants.FILE_SUFFIX);
if (!tmp.exists()) {
try {
tmp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
TransformerFactory transFac = TransformerFactory.newInstance();
try {
Transformer trans = transFac.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(tmp);
trans.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return tmp;
}
}
|
UTF-8
|
Java
| 3,676 |
java
|
QualificationUtil.java
|
Java
|
[
{
"context": "omputing Technology, Beihang University\n* Contact: service4all@act.buaa.edu.cn\n*\n* This library is free software; you can redist",
"end": 205,
"score": 0.9999344944953918,
"start": 178,
"tag": "EMAIL",
"value": "service4all@act.buaa.edu.cn"
}
] | null |
[] |
/**
* Service4All: A Service-oriented Cloud Platform for All about Software Development
* Copyright (C) Institute of Advanced Computing Technology, Beihang University
* Contact: <EMAIL>
*
* This library 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 3.0 of the License, or any later version.
*
* This library 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 General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package cn.edu.buaa.act.service4all.webapp.qualification;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import cn.edu.buaa.act.service4all.webapp.utility.Constants;
import cn.edu.buaa.act.service4all.webapp.utility.XMLUtil;
public class QualificationUtil {
private final static Log logger = LogFactory.getLog(QualificationUtil.class);
public static Document getResult(Document document, String url) {
File tmp = null;
String tmpresult = null;
Document result = null;
tmp = saveXmlToFile(document);
if (tmp == null)
return null;
tmpresult = sendAndGetResult(tmp, url);
if (tmpresult == null)
return null;
result = XMLUtil.StringToDoc(tmpresult);
return result;
}
private static String sendAndGetResult(File tmp, String url) {
PostMethod post = new PostMethod(url);
RequestEntity entity = new FileRequestEntity(tmp, Constants.CODE);
post.setRequestEntity(entity);
HttpClient client = new HttpClient();
String result = null;
try {
int resultCode = client.executeMethod(post);
logger.info(resultCode);
result = post.getResponseBodyAsString();
logger.info("Response body:\n " + result);
// remove the tmp file
tmp.delete();
post.releaseConnection();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static File saveXmlToFile(Document doc) {
File tmp = new File(Constants.FILE_PERFIX
+ Calendar.getInstance().getTimeInMillis()
+ Constants.FILE_SUFFIX);
if (!tmp.exists()) {
try {
tmp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
TransformerFactory transFac = TransformerFactory.newInstance();
try {
Transformer trans = transFac.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(tmp);
trans.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return tmp;
}
}
| 3,656 | 0.757617 | 0.751632 | 107 | 33.355141 | 22.583698 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.981308 | false | false |
12
|
ea6ad69b1726a88910a894316d4568b88744cfc1
| 14,173,392,095,211 |
942c71c9b5dcd9475d030a98f718682241786b1d
|
/core.rest/src/main/java/com/lsq/core/rest/components/hello/HelloController.java
|
26d747879882c724e0be52884ca47e3baa26c117
|
[] |
no_license
|
treemark/lsq
|
https://github.com/treemark/lsq
|
57356ede8997b1e2babb5ea2a1d7df867e59569f
|
e253fb523e361805771be5e29bccbe8a4ad78e49
|
refs/heads/master
| 2023-01-08T10:46:05.680000 | 2020-11-04T01:45:36 | 2020-11-04T01:45:36 | 309,525,397 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lsq.core.rest.components.hello;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
@Service
@RestController
@Api(tags = { "Hello" })
public class HelloController {
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String index() {
return "Greetings from Spring Boot!";
}
}
|
UTF-8
|
Java
| 531 |
java
|
HelloController.java
|
Java
|
[] | null |
[] |
package com.lsq.core.rest.components.hello;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
@Service
@RestController
@Api(tags = { "Hello" })
public class HelloController {
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String index() {
return "Greetings from Spring Boot!";
}
}
| 531 | 0.79096 | 0.79096 | 20 | 25.6 | 23.463589 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false |
12
|
bb6d5613c255cd43e5cf6a2533e22e93dda2ed72
| 7,129,645,756,872 |
64b83596de6ff77ae1bd7c46667e7f28c8855205
|
/account/src/main/java/com/sakurasou/moshiro/account/AccountApplication.java
|
3353742e79acdd3b260594ad35d40c1676a0a264
|
[] |
no_license
|
SeeleVonVollerei/Moshiro
|
https://github.com/SeeleVonVollerei/Moshiro
|
1f177fcc593439684a65bbe945fce93bb175fd47
|
2fb92ecc0780b32b78eb5c3b06ffe9cb70478437
|
refs/heads/master
| 2020-07-21T02:50:43.043000 | 2019-09-10T07:37:43 | 2019-09-10T07:37:43 | 206,745,960 | 0 | 0 | null | true | 2019-09-10T07:37:44 | 2019-09-06T08:10:49 | 2019-09-10T03:08:32 | 2019-09-10T07:37:44 | 19 | 0 | 0 | 0 |
Java
| false | false |
package com.sakurasou.moshiro.account;
import com.sakurasou.moshiro.account.mapper.MarkMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@MapperScan(basePackageClasses = {MarkMapper.class})
public class AccountApplication {
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
}
}
|
UTF-8
|
Java
| 577 |
java
|
AccountApplication.java
|
Java
|
[] | null |
[] |
package com.sakurasou.moshiro.account;
import com.sakurasou.moshiro.account.mapper.MarkMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@MapperScan(basePackageClasses = {MarkMapper.class})
public class AccountApplication {
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
}
}
| 577 | 0.82149 | 0.82149 | 18 | 31.055555 | 24.523169 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
12
|
200d381d382ccb83ae1948fe97e27710414844df
| 3,547,643,048,344 |
1d36fa545673a9b9737011aa9aba57afedd4ebe7
|
/app/src/main/java/com/yunma/utils/AppManager.java
|
976e45896de062236a2d7b0ec884012353f16c2d
|
[
"MIT"
] |
permissive
|
JsonDing/Jhuo
|
https://github.com/JsonDing/Jhuo
|
c39eaf448c390093f9ce2ae050dc57b284c9ee8e
|
bfdc263d44a61b1accedd0d1f27a1cb34a5b24b5
|
refs/heads/master
| 2022-01-19T02:19:02.649000 | 2021-12-29T03:32:16 | 2021-12-29T03:32:16 | 142,241,679 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yunma.utils;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import java.util.List;
import java.util.Stack;
import static com.yunma.jhuo.general.MyApplication.applicationContext;
/**
* Created by Json on 2017/4/3.
*/
public class AppManager {
private static Stack<Activity> activityStack;
private static AppManager instance;
private AppManager() {
}
/**
* 单一实例
*/
public static AppManager getAppManager() {
if (instance == null) {
instance = new AppManager();
}
return instance;
}
/**
* 添加Activity到堆栈
*/
public void addActivity(Activity activity) {
if (activityStack == null) {
activityStack = new Stack<>();
}
for (Activity act : activityStack) {
if (!act.getClass().equals(activity.getClass())) {
activityStack.add(activity);
}
}
}
/**
* 获取当前Activity(堆栈中最后一个压入的)
*/
public Activity currentActivity() {
Activity activity = activityStack.lastElement();
return activity;
}
/**
* 结束当前Activity(堆栈中最后一个压入的)
*/
public void finishActivity() {
Activity activity = activityStack.lastElement();
finishActivity(activity);
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
}
getCurrentStack();
}
/**
* 结束指定类名的Activity
*/
public void finishActivity(Class<?> cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
finishActivity(activity);
}
}
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
LogUtils.json("结束所有MainActivity之外的activity");
activityStack.clear();
}
/**
* 退出应用程序
*/
public void AppExit() {
try {
GlideUtils.glidClearMemory(applicationContext);
GlideUtils.glidClearDisk(applicationContext);
finishAllActivity();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
} catch (Exception ignored) {
}
}
/**
* 结束指定的Activity
*/
public void getActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
}
}
/**
* 得到指定类名的Activity
*/
public Activity getActivity(Class<?> cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
return activity;
}
}
return null;
}
private void getCurrentStack(){
assert activityStack != null;
LogUtils.json("当前栈中Activity数量:" + activityStack.size());
for(Activity activity : activityStack){
LogUtils.json("当前栈中Activity: " + activity);
}
}
/**
* 获取版本号
* @return 当前应用的版本号
*/
public String getVersion(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
return info.versionName;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 启动第三方 app
* @param mcontext
* @param packagename
*/
public void doStartApplicationWithPackageName (Context mcontext, String packagename) {
// 通过包名获取此 APP 详细信息,包括 Activities、 services 、versioncode 、 name等等
PackageInfo packageinfo = null;
try {
packageinfo = mcontext.getPackageManager().getPackageInfo(packagename, 0 );
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace() ;
}
if (packageinfo == null) {
return;
}
// 创建一个类别为 CATEGORY_LAUNCHER 的该包名的 Intent
Intent resolveIntent = new Intent(Intent. ACTION_MAIN, null) ;
resolveIntent.setFlags(Intent. FLAG_ACTIVITY_NEW_TASK ) ;
resolveIntent.addCategory(Intent. CATEGORY_LAUNCHER );
resolveIntent.setPackage(packageinfo. packageName );
// 通过 getPackageManager()的 queryIntentActivities 方法遍历
List<ResolveInfo> resolveinfoList = mcontext.getPackageManager()
.queryIntentActivities(resolveIntent , 0) ;
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null ) {
// packagename = 参数 packname
String packageName = resolveinfo.activityInfo . packageName;
// 这个就是我们要找的该 APP 的LAUNCHER 的 Activity[组织形式: packagename.mainActivityname]
String className = resolveinfo. activityInfo .name ;
// LAUNCHER Intent
Intent intent = new Intent(Intent. ACTION_MAIN) ;
intent.setFlags(Intent. FLAG_ACTIVITY_NEW_TASK ) ;
intent.addCategory(Intent. CATEGORY_LAUNCHER );
// 设置 ComponentName参数 1:packagename 参数2:MainActivity 路径
ComponentName cn = new ComponentName(packageName , className) ;
intent.setComponent(cn) ;
mcontext.startActivity(intent) ;
}
}
}
|
UTF-8
|
Java
| 6,139 |
java
|
AppManager.java
|
Java
|
[
{
"context": "Application.applicationContext;\n\n/**\n * Created by Json on 2017/4/3.\n */\n\npublic class AppManager {\n\n ",
"end": 419,
"score": 0.8601494431495667,
"start": 415,
"tag": "USERNAME",
"value": "Json"
}
] | null |
[] |
package com.yunma.utils;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import java.util.List;
import java.util.Stack;
import static com.yunma.jhuo.general.MyApplication.applicationContext;
/**
* Created by Json on 2017/4/3.
*/
public class AppManager {
private static Stack<Activity> activityStack;
private static AppManager instance;
private AppManager() {
}
/**
* 单一实例
*/
public static AppManager getAppManager() {
if (instance == null) {
instance = new AppManager();
}
return instance;
}
/**
* 添加Activity到堆栈
*/
public void addActivity(Activity activity) {
if (activityStack == null) {
activityStack = new Stack<>();
}
for (Activity act : activityStack) {
if (!act.getClass().equals(activity.getClass())) {
activityStack.add(activity);
}
}
}
/**
* 获取当前Activity(堆栈中最后一个压入的)
*/
public Activity currentActivity() {
Activity activity = activityStack.lastElement();
return activity;
}
/**
* 结束当前Activity(堆栈中最后一个压入的)
*/
public void finishActivity() {
Activity activity = activityStack.lastElement();
finishActivity(activity);
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
}
getCurrentStack();
}
/**
* 结束指定类名的Activity
*/
public void finishActivity(Class<?> cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
finishActivity(activity);
}
}
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
LogUtils.json("结束所有MainActivity之外的activity");
activityStack.clear();
}
/**
* 退出应用程序
*/
public void AppExit() {
try {
GlideUtils.glidClearMemory(applicationContext);
GlideUtils.glidClearDisk(applicationContext);
finishAllActivity();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
} catch (Exception ignored) {
}
}
/**
* 结束指定的Activity
*/
public void getActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
}
}
/**
* 得到指定类名的Activity
*/
public Activity getActivity(Class<?> cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
return activity;
}
}
return null;
}
private void getCurrentStack(){
assert activityStack != null;
LogUtils.json("当前栈中Activity数量:" + activityStack.size());
for(Activity activity : activityStack){
LogUtils.json("当前栈中Activity: " + activity);
}
}
/**
* 获取版本号
* @return 当前应用的版本号
*/
public String getVersion(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
return info.versionName;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 启动第三方 app
* @param mcontext
* @param packagename
*/
public void doStartApplicationWithPackageName (Context mcontext, String packagename) {
// 通过包名获取此 APP 详细信息,包括 Activities、 services 、versioncode 、 name等等
PackageInfo packageinfo = null;
try {
packageinfo = mcontext.getPackageManager().getPackageInfo(packagename, 0 );
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace() ;
}
if (packageinfo == null) {
return;
}
// 创建一个类别为 CATEGORY_LAUNCHER 的该包名的 Intent
Intent resolveIntent = new Intent(Intent. ACTION_MAIN, null) ;
resolveIntent.setFlags(Intent. FLAG_ACTIVITY_NEW_TASK ) ;
resolveIntent.addCategory(Intent. CATEGORY_LAUNCHER );
resolveIntent.setPackage(packageinfo. packageName );
// 通过 getPackageManager()的 queryIntentActivities 方法遍历
List<ResolveInfo> resolveinfoList = mcontext.getPackageManager()
.queryIntentActivities(resolveIntent , 0) ;
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null ) {
// packagename = 参数 packname
String packageName = resolveinfo.activityInfo . packageName;
// 这个就是我们要找的该 APP 的LAUNCHER 的 Activity[组织形式: packagename.mainActivityname]
String className = resolveinfo. activityInfo .name ;
// LAUNCHER Intent
Intent intent = new Intent(Intent. ACTION_MAIN) ;
intent.setFlags(Intent. FLAG_ACTIVITY_NEW_TASK ) ;
intent.addCategory(Intent. CATEGORY_LAUNCHER );
// 设置 ComponentName参数 1:packagename 参数2:MainActivity 路径
ComponentName cn = new ComponentName(packageName , className) ;
intent.setComponent(cn) ;
mcontext.startActivity(intent) ;
}
}
}
| 6,139 | 0.585796 | 0.583549 | 211 | 26.42654 | 23.033833 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341232 | false | false |
12
|
655dc7241a48c3eaed0e8139d6c64317be8797ef
| 30,588,757,151,770 |
c74bf678f64d564a8f14b0a2dcb6dab1534edd82
|
/src/main/java/geektime/algo/offer/DuplicateArray1.java
|
4dea21a8aebca96da181ece7a1e6bf173236c4ed
|
[
"MIT"
] |
permissive
|
neverzhai/GeekTimeAlgoJava
|
https://github.com/neverzhai/GeekTimeAlgoJava
|
2a4030b316c4b451847dac951a414ad4a25f02fa
|
4e854935b698f70c9696e2e3e73c42b4df71277a
|
refs/heads/master
| 2022-05-26T20:20:45.727000 | 2022-05-14T12:19:10 | 2022-05-14T12:19:10 | 201,937,097 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package geektime.algo.offer;
/**
* @author: zhaixiaoshuang
* @date: 2021-02-24 08:32
* @description: 数组中重复的数字
* 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,
* 也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
*/
public class DuplicateArray1 {
// 问题分析: 有n个数字范围都在0~n-1的范围内的数字,如果不重复的话, 这n个数字一定就是0~n-1, 正好和数组下标一致。
// 利用这个特性, 将数组中的元素归位
public int getDuplicateNumber(int[] numbers) {
if (numbers == null || numbers.length == 0) {
return -1;
}
for (int index = 0; index < numbers.length; index ++) {
while (numbers[index] != index) {
// 找到重复的
if(numbers[index] == numbers[numbers[index]]) {
return numbers[index];
}
// 没重复, 进行交换numbers[index] 和 numbers[numbers[index]]
int temp = numbers[index];
numbers[index] = numbers[temp];
numbers[temp] = temp;
}
}
return -1;
}
}
|
UTF-8
|
Java
| 1,328 |
java
|
DuplicateArray1.java
|
Java
|
[
{
"context": "package geektime.algo.offer;\n\n/**\n * @author: zhaixiaoshuang\n * @date: 2021-02-24 08:32\n * @description: 数组中重复",
"end": 60,
"score": 0.9141914248466492,
"start": 46,
"tag": "USERNAME",
"value": "zhaixiaoshuang"
}
] | null |
[] |
package geektime.algo.offer;
/**
* @author: zhaixiaoshuang
* @date: 2021-02-24 08:32
* @description: 数组中重复的数字
* 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,
* 也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
*/
public class DuplicateArray1 {
// 问题分析: 有n个数字范围都在0~n-1的范围内的数字,如果不重复的话, 这n个数字一定就是0~n-1, 正好和数组下标一致。
// 利用这个特性, 将数组中的元素归位
public int getDuplicateNumber(int[] numbers) {
if (numbers == null || numbers.length == 0) {
return -1;
}
for (int index = 0; index < numbers.length; index ++) {
while (numbers[index] != index) {
// 找到重复的
if(numbers[index] == numbers[numbers[index]]) {
return numbers[index];
}
// 没重复, 进行交换numbers[index] 和 numbers[numbers[index]]
int temp = numbers[index];
numbers[index] = numbers[temp];
numbers[temp] = temp;
}
}
return -1;
}
}
| 1,328 | 0.540161 | 0.517068 | 35 | 27.485714 | 22.162222 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314286 | false | false |
12
|
dcec3761679cb8cd82214106bbf1d2757b4a4642
| 36,799,279,798,067 |
c938f9c29bdb3f11f969c365998ac68807ca0ac5
|
/app/src/main/java/com/yuedong/youbutie_merchant_android/model/bmob/bean/ServiceInfo.java
|
48c155c90bd3ed1f22e9869872771ee04980e167
|
[] |
no_license
|
lixiansheng123/Youbutie-merchant-android
|
https://github.com/lixiansheng123/Youbutie-merchant-android
|
cda779d38e9af65c2331bcaf67e49c9f1c2f9ac5
|
5f0ccf3923826659600661acf2c43d7768b17210
|
refs/heads/master
| 2021-01-10T08:15:34.062000 | 2016-02-17T01:33:35 | 2016-02-17T01:33:35 | 48,572,094 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yuedong.youbutie_merchant_android.model.bmob.bean;
import cn.bmob.v3.BmobObject;
/**
* Created by Administrator on 2015/11/27.
* 服务表
*
* @author 俊鹏
*/
public class ServiceInfo extends BmobObject {
private String name; // 服务名称
private String icon; // 服务icon
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
@Override
public String toString() {
return "ServiceInfo{" +
"name='" + name + '\'' +
", icon='" + icon + '\'' +
'}';
}
}
|
UTF-8
|
Java
| 758 |
java
|
ServiceInfo.java
|
Java
|
[
{
"context": "Administrator on 2015/11/27.\n * 服务表\n *\n * @author 俊鹏\n */\npublic class ServiceInfo extends BmobObject {",
"end": 165,
"score": 0.9997832775115967,
"start": 163,
"tag": "NAME",
"value": "俊鹏"
}
] | null |
[] |
package com.yuedong.youbutie_merchant_android.model.bmob.bean;
import cn.bmob.v3.BmobObject;
/**
* Created by Administrator on 2015/11/27.
* 服务表
*
* @author 俊鹏
*/
public class ServiceInfo extends BmobObject {
private String name; // 服务名称
private String icon; // 服务icon
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
@Override
public String toString() {
return "ServiceInfo{" +
"name='" + name + '\'' +
", icon='" + icon + '\'' +
'}';
}
}
| 758 | 0.543478 | 0.53125 | 39 | 17.871796 | 16.767153 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25641 | false | false |
12
|
45cefb3814586f5938bc5afcebb883678de633d7
| 6,897,717,516,764 |
9be93d585f0c8f10bb6dba312fc15b7ab899bad0
|
/RollDice.java
|
d1dddd84f9f69a3a20a6306a6d5c06ffc00caa8b
|
[] |
no_license
|
Sleepingisimportant/Java-Basics
|
https://github.com/Sleepingisimportant/Java-Basics
|
21f7c777432b818ba320f42f1e59f8b14f198b8c
|
2dbd4b8bcfd4277b35a2ada0aca4acdd85f7b040
|
refs/heads/master
| 2020-04-08T19:18:11.045000 | 2017-05-01T22:00:01 | 2017-05-01T22:00:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class RollDice {
/* random number example */
public static int roll(int sides) { // random roll parameter
//random number from 0 to almost 1
double randomNumber=Math.random();
//change range from 0 to almost 6
randomNumber=randomNumber * sides;
//shift range upto one
randomNumber=randomNumber + 1;
//cast to integer(ignore decimal part)
int randomInt= (int) randomNumber;
return randomInt;
}
public static void main(String[] args) {
System.out.println(roll(8));
}
}
|
UTF-8
|
Java
| 500 |
java
|
RollDice.java
|
Java
|
[] | null |
[] |
public class RollDice {
/* random number example */
public static int roll(int sides) { // random roll parameter
//random number from 0 to almost 1
double randomNumber=Math.random();
//change range from 0 to almost 6
randomNumber=randomNumber * sides;
//shift range upto one
randomNumber=randomNumber + 1;
//cast to integer(ignore decimal part)
int randomInt= (int) randomNumber;
return randomInt;
}
public static void main(String[] args) {
System.out.println(roll(8));
}
}
| 500 | 0.714 | 0.702 | 21 | 22.761906 | 17.609264 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false |
12
|
b7d69e337698da4f834942069f6df4bd93136591
| 7,121,055,788,664 |
9d3db1e4688f49d45be7f7cd4ed7ab7c918f99a4
|
/WebProject/src/main/java/com/aaa/mapper/BaoxiaoMapper.java
|
b11d443fae5b0789bad27b229c9752bea06a9094
|
[] |
no_license
|
hechaoqi123/SpringBoot
|
https://github.com/hechaoqi123/SpringBoot
|
0f7c2a9ec634faeaf20cdc1fe33e356997d6308e
|
c9b11707dc213661066def4f5a1e0e7cd733291b
|
refs/heads/master
| 2020-03-31T13:08:10.775000 | 2019-05-21T06:21:19 | 2019-05-21T06:21:19 | 152,242,904 | 1 | 1 | null | false | 2018-10-23T06:14:09 | 2018-10-09T11:55:43 | 2018-10-23T00:20:20 | 2018-10-23T06:14:08 | 9,837 | 0 | 0 | 0 |
CSS
| false | null |
package com.aaa.mapper;
import org.apache.ibatis.annotations.Select;
import com.aaa.bean.Baoxiao;
import tk.mybatis.mapper.common.Mapper;
public interface BaoxiaoMapper extends Mapper<Baoxiao>{
@Select("select max(baoxiaoid) from baoxiao")
public Integer getMaxId();
}
|
UTF-8
|
Java
| 291 |
java
|
BaoxiaoMapper.java
|
Java
|
[] | null |
[] |
package com.aaa.mapper;
import org.apache.ibatis.annotations.Select;
import com.aaa.bean.Baoxiao;
import tk.mybatis.mapper.common.Mapper;
public interface BaoxiaoMapper extends Mapper<Baoxiao>{
@Select("select max(baoxiaoid) from baoxiao")
public Integer getMaxId();
}
| 291 | 0.745704 | 0.745704 | 12 | 22.25 | 20.412926 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false |
12
|
ac026d316ebd7f3f8f913bf66e502a566aed5d01
| 25,512,105,807,616 |
46d60e27cbbed69b9f636d5c007935bbaef5ce72
|
/src/test/java/com/byteowls/jopencage/model/JOpenCageResponseTest.java
|
dfcf740a81aa76965461d538cee22f49b31657b6
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
moberwasserlechner/jopencage
|
https://github.com/moberwasserlechner/jopencage
|
8402fd27bac8b47ecc2ad4bfd74a5e950340fa2c
|
44efd2bafc01f88b1c63df70b53c64d6563b93c1
|
refs/heads/master
| 2023-08-17T07:40:46.167000 | 2023-07-05T18:34:53 | 2023-07-05T18:34:53 | 38,174,573 | 18 | 21 |
Apache-2.0
| false | 2023-08-11T18:13:02 | 2015-06-27T20:39:54 | 2023-07-02T13:00:52 | 2023-08-11T18:12:47 | 328 | 13 | 19 | 0 |
Java
| false | false |
package com.byteowls.jopencage.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.*;
class JOpenCageResponseTest {
private JOpenCageResponse loadTestResponse() throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(getClass().getResourceAsStream("toadd"), JOpenCageResponse.class);
}
@Test
public void mapping() throws IOException {
JOpenCageResponse jOpenCageResponse = loadTestResponse();
assertNotNull(jOpenCageResponse);
}
@Test
public void dateDeserialization() throws IOException {
JOpenCageResponse jOpenCageResponse = loadTestResponse();
assertNotNull(jOpenCageResponse);
Date createdAt = jOpenCageResponse.getTimestamp().getCreatedAt();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
String formattedDate = dateFormat.format(createdAt);
assertEquals("2015-05-03 14:29", formattedDate);
}
}
|
UTF-8
|
Java
| 1,242 |
java
|
JOpenCageResponseTest.java
|
Java
|
[] | null |
[] |
package com.byteowls.jopencage.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.*;
class JOpenCageResponseTest {
private JOpenCageResponse loadTestResponse() throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(getClass().getResourceAsStream("toadd"), JOpenCageResponse.class);
}
@Test
public void mapping() throws IOException {
JOpenCageResponse jOpenCageResponse = loadTestResponse();
assertNotNull(jOpenCageResponse);
}
@Test
public void dateDeserialization() throws IOException {
JOpenCageResponse jOpenCageResponse = loadTestResponse();
assertNotNull(jOpenCageResponse);
Date createdAt = jOpenCageResponse.getTimestamp().getCreatedAt();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
String formattedDate = dateFormat.format(createdAt);
assertEquals("2015-05-03 14:29", formattedDate);
}
}
| 1,242 | 0.7343 | 0.724638 | 39 | 30.846153 | 27.968424 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false |
12
|
4f3509db00cfd7430903963b937584f02782de36
| 30,537,217,541,710 |
2557011e0fb182a3f4b581b487ff76b558010e32
|
/E-Walletfinal/src/main/java/com/capgemini/ewallet/service/TransactionServiceImpl.java
|
b2fb3b54ed275be826d8b552911c8a989faa129e
|
[] |
no_license
|
akshitabajpai/EwalletIntegrated
|
https://github.com/akshitabajpai/EwalletIntegrated
|
f9d4369676025ca56a8d08defadbfdf657bd287a
|
56c9d0bcabcd6e47953c105688a85fa1c9d78638
|
refs/heads/master
| 2022-09-17T01:05:09.832000 | 2020-05-24T14:50:19 | 2020-05-24T14:50:19 | 266,557,629 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.capgemini.ewallet.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.capgemini.ewallet.dao.WalletAccountDao;
import com.capgemini.ewallet.dao.WalletTransactionDao;
import com.capgemini.ewallet.entity.WalletAccount;
import com.capgemini.ewallet.entity.WalletTransaction;
import com.capgemini.ewallet.exception.TransactionException;
@Service
@Transactional
public class TransactionServiceImpl implements TransactionService
{
@Autowired
WalletAccountDao accountdao;
@Autowired
WalletTransactionDao transactionDao;
@Override
@Transactional(readOnly = true)
public WalletAccount findAccount(int accId) {
// TODO Auto-generated method stub
Optional<WalletAccount> a = accountdao.findById(accId);
if (a.isPresent())
return a.get();
else
throw new TransactionException("AccountId not found!");
}
@Override
@Transactional(readOnly = true)
public List<WalletTransaction> transactionHistory(int senderId) {
// TODO Auto-generated method stub
List<WalletTransaction>history = transactionDao.findBySenderAccId(senderId);
System.out.println(history.get(0));
return history;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Boolean TransferAmount(WalletTransaction transfer) {
// TODO Auto-generated method stub
if(transfer.getAmount()<=0) {
throw new TransactionException("Amount is too less!!! ") ;
}
WalletAccount sender = findAccount(transfer.getSenderAccId());
WalletAccount receiver = findAccount(transfer.getReceiverAccId());
double senderbalance = sender.getBalance()-transfer.getAmount();
double receiverbalance = receiver.getBalance() +transfer.getAmount();
updateBalance(sender.getAccountId(),senderbalance);
updateBalance(receiver.getAccountId(),receiverbalance);
transactionDao.save(transfer);
return true;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void updateBalance(int accId, double amount) {
// TODO Auto-generated method stub
WalletAccount wallet;
Optional<WalletAccount> account = accountdao.findById(accId);
if (account.isPresent())
wallet = account.get();
else
throw new TransactionException("Account not found!");
wallet.setBalance(amount);
}
}
|
UTF-8
|
Java
| 2,511 |
java
|
TransactionServiceImpl.java
|
Java
|
[] | null |
[] |
package com.capgemini.ewallet.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.capgemini.ewallet.dao.WalletAccountDao;
import com.capgemini.ewallet.dao.WalletTransactionDao;
import com.capgemini.ewallet.entity.WalletAccount;
import com.capgemini.ewallet.entity.WalletTransaction;
import com.capgemini.ewallet.exception.TransactionException;
@Service
@Transactional
public class TransactionServiceImpl implements TransactionService
{
@Autowired
WalletAccountDao accountdao;
@Autowired
WalletTransactionDao transactionDao;
@Override
@Transactional(readOnly = true)
public WalletAccount findAccount(int accId) {
// TODO Auto-generated method stub
Optional<WalletAccount> a = accountdao.findById(accId);
if (a.isPresent())
return a.get();
else
throw new TransactionException("AccountId not found!");
}
@Override
@Transactional(readOnly = true)
public List<WalletTransaction> transactionHistory(int senderId) {
// TODO Auto-generated method stub
List<WalletTransaction>history = transactionDao.findBySenderAccId(senderId);
System.out.println(history.get(0));
return history;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Boolean TransferAmount(WalletTransaction transfer) {
// TODO Auto-generated method stub
if(transfer.getAmount()<=0) {
throw new TransactionException("Amount is too less!!! ") ;
}
WalletAccount sender = findAccount(transfer.getSenderAccId());
WalletAccount receiver = findAccount(transfer.getReceiverAccId());
double senderbalance = sender.getBalance()-transfer.getAmount();
double receiverbalance = receiver.getBalance() +transfer.getAmount();
updateBalance(sender.getAccountId(),senderbalance);
updateBalance(receiver.getAccountId(),receiverbalance);
transactionDao.save(transfer);
return true;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void updateBalance(int accId, double amount) {
// TODO Auto-generated method stub
WalletAccount wallet;
Optional<WalletAccount> account = accountdao.findById(accId);
if (account.isPresent())
wallet = account.get();
else
throw new TransactionException("Account not found!");
wallet.setBalance(amount);
}
}
| 2,511 | 0.775787 | 0.77499 | 89 | 27.213484 | 24.677458 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.719101 | false | false |
12
|
7abebd2d3bf162ee11b0e3dbfe8a93a9d922ba06
| 15,350,213,136,230 |
9cee8d179737d5466ad7dc9f267c7dfddd7094bf
|
/projectile/projectile.java
|
1987555f5d659f00ebda492f84a0d4d9e20fd97a
|
[] |
no_license
|
jchoi307/JavaProjects
|
https://github.com/jchoi307/JavaProjects
|
d855397e74975c100762b38611532414910755d4
|
5831d92d1f3e409c1e099556f4fc65bd91a1b0ba
|
refs/heads/master
| 2021-01-11T21:15:21.233000 | 2017-01-17T22:54:49 | 2017-01-17T22:54:49 | 79,278,516 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.*;
import java.math.*;
public class projectile{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
final double vi = in.nextDouble();
double v = vi;
double g = 9.81;
final double DELTA_T = 0.01;
double t2 = 0;
double s = v * DELTA_T;
int t = 0;
boolean velo = false;
for (int i=0; ;i++) {
s = s + Math.abs(v) * DELTA_T;
v = v - g * DELTA_T;
t2 += DELTA_T;
if (i == 100){
t++;
System.out.println("current position at " + t + " second : " + s);
System.out.println("cuttent velocity at " + t + " second : " + v);
System.out.println();
i = 0;
}
if (v <= 0){
velo = true;
System.out.println("Final position at " + Math.round(t2*100d)/100d + " second : " + s);
System.out.println("Final velocity at " + Math.round(t2*100d)/100d + " second : " + v);
System.out.println("by the equation, s(t) = -1/2gt^2 + vi*t");
System.out.println("s(t) = " + ((-0.5)*g*t*t + vi*t));
break;
}
}
}
}
|
UTF-8
|
Java
| 1,228 |
java
|
projectile.java
|
Java
|
[] | null |
[] |
import java.util.*;
import java.math.*;
public class projectile{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
final double vi = in.nextDouble();
double v = vi;
double g = 9.81;
final double DELTA_T = 0.01;
double t2 = 0;
double s = v * DELTA_T;
int t = 0;
boolean velo = false;
for (int i=0; ;i++) {
s = s + Math.abs(v) * DELTA_T;
v = v - g * DELTA_T;
t2 += DELTA_T;
if (i == 100){
t++;
System.out.println("current position at " + t + " second : " + s);
System.out.println("cuttent velocity at " + t + " second : " + v);
System.out.println();
i = 0;
}
if (v <= 0){
velo = true;
System.out.println("Final position at " + Math.round(t2*100d)/100d + " second : " + s);
System.out.println("Final velocity at " + Math.round(t2*100d)/100d + " second : " + v);
System.out.println("by the equation, s(t) = -1/2gt^2 + vi*t");
System.out.println("s(t) = " + ((-0.5)*g*t*t + vi*t));
break;
}
}
}
}
| 1,228 | 0.455212 | 0.42671 | 39 | 30.512821 | 24.813015 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717949 | false | false |
12
|
457756819327911261d3d731ce291c42059867b5
| 19,370,302,566,590 |
92b97e7676e8d4425266183f8934f2c1b4daf0f2
|
/agenda/src/main/java/br/senac/tads/dsw/agenda/repository/TelefoneRepository.java
|
b83239f1a1b927c4c658d274d86df75b5ea9e43b
|
[
"MIT"
] |
permissive
|
ftsuda-senac/tads-dswa-2001
|
https://github.com/ftsuda-senac/tads-dswa-2001
|
ea44b5c324a3693ba125ccea24d531c803b20c5d
|
0804f5adf39498b0f4b5963b4a80636b58af5caa
|
refs/heads/master
| 2022-06-16T11:25:38.170000 | 2020-06-11T13:34:32 | 2020-06-11T13:34:32 | 239,873,907 | 0 | 0 |
MIT
| false | 2022-06-03T03:39:14 | 2020-02-11T22:03:13 | 2020-06-11T13:34:28 | 2022-06-03T03:39:13 | 844 | 0 | 0 | 2 |
Java
| false | false |
package br.senac.tads.dsw.agenda.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.senac.tads.dsw.agenda.entidades.Telefone;
@Repository
public interface TelefoneRepository extends JpaRepository<Telefone, Integer>{
}
|
UTF-8
|
Java
| 316 |
java
|
TelefoneRepository.java
|
Java
|
[] | null |
[] |
package br.senac.tads.dsw.agenda.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.senac.tads.dsw.agenda.entidades.Telefone;
@Repository
public interface TelefoneRepository extends JpaRepository<Telefone, Integer>{
}
| 316 | 0.810127 | 0.810127 | 11 | 26.727272 | 28.368006 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
12
|
f51b8385820b90d32cffd056fa9240180e8ce639
| 19,370,302,569,848 |
6e7be9e9b42a348b0955aba6f093742137837f9d
|
/DayTrader/src/com/broadviewsoft/daytrader/service/impl/CsvDataFileService.java
|
75dc5a3ff4e88e7506100d6d28fe692d384e3d33
|
[] |
no_license
|
jingdaz/daytrader_1
|
https://github.com/jingdaz/daytrader_1
|
8fe3e9ecd2f775a1a5ece487b417e1806967569b
|
6e3d4d575200eb1c0bff2c1fd1558ed93d131137
|
refs/heads/master
| 2021-01-24T03:50:22.303000 | 2020-07-12T13:05:55 | 2020-07-12T13:05:55 | 122,901,793 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.broadviewsoft.daytrader.service.impl;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;
import com.broadviewsoft.daytrader.domain.CurrencyType;
import com.broadviewsoft.daytrader.domain.DataException;
import com.broadviewsoft.daytrader.domain.DataFileType;
import com.broadviewsoft.daytrader.domain.Period;
import com.broadviewsoft.daytrader.domain.StockItem;
import com.broadviewsoft.daytrader.service.IHistoryDataService;
import com.broadviewsoft.daytrader.util.Util;
public class CsvDataFileService implements IHistoryDataService {
private static Log logger = LogFactory.getLog(CsvDataFileService.class);
public List<StockItem> loadData(String symbol, Period period,
DataFileType type) throws DataException {
List<StockItem> result = new ArrayList<StockItem>();
String csvFilename = Util.getDataPath(symbol, period, type);
ICsvBeanReader beanReader = null;
StockItem item = null;
try {
beanReader = new CsvBeanReader(new FileReader(csvFilename),
CsvPreference.STANDARD_PREFERENCE);
// the header elements are used to map the values to the bean (names
// must match)
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processors = Util.getProcessors(type);
while ((item = beanReader.read(StockItem.class, header, processors)) != null) {
result.add(item);
}
} catch (FileNotFoundException e) {
logger.error(csvFilename, e);
throw new DataException();
} catch (IOException e) {
logger.error(item, e);
throw new DataException();
} finally {
if (beanReader != null) {
try {
beanReader.close();
} catch (IOException e) {
logger.error("Error when closing csv file.");
}
}
}
return result;
}
public List<StockItem> loadData(String csvFilename,
DataFileType type) throws DataException {
List<StockItem> result = new ArrayList<StockItem>();
ICsvBeanReader beanReader = null;
StockItem item = null;
try {
beanReader = new CsvBeanReader(new FileReader(csvFilename),
CsvPreference.STANDARD_PREFERENCE);
// the header elements are used to map the values to the bean (names
// must match)
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processors = Util.getProcessors(type);
while ((item = beanReader.read(StockItem.class, header, processors)) != null) {
result.add(item);
}
} catch (FileNotFoundException e) {
logger.error(csvFilename, e);
throw new DataException();
} catch (IOException e) {
logger.error(item, e);
throw new DataException();
} finally {
if (beanReader != null) {
try {
beanReader.close();
} catch (IOException e) {
logger.error("Error when closing csv file.");
}
}
}
return result;
}
public static void main(String[] args) throws DataException {
CsvDataFileService service = new CsvDataFileService();
// print out stock headers
CurrencyType curType = CurrencyType.USD;
String symbol = "UVXY";
// Period period = Period.MIN5;
// Period period = Period.DAY;
Period period = Period.MIN01;
System.out.println(StockItem.printHeaders(curType, symbol, period));
// print out stock data
List<StockItem> result = service.loadData(symbol, period,
DataFileType.BVS);
for (StockItem si : result) {
System.out.println(si);
}
}
}
|
UTF-8
|
Java
| 3,793 |
java
|
CsvDataFileService.java
|
Java
|
[] | null |
[] |
package com.broadviewsoft.daytrader.service.impl;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;
import com.broadviewsoft.daytrader.domain.CurrencyType;
import com.broadviewsoft.daytrader.domain.DataException;
import com.broadviewsoft.daytrader.domain.DataFileType;
import com.broadviewsoft.daytrader.domain.Period;
import com.broadviewsoft.daytrader.domain.StockItem;
import com.broadviewsoft.daytrader.service.IHistoryDataService;
import com.broadviewsoft.daytrader.util.Util;
public class CsvDataFileService implements IHistoryDataService {
private static Log logger = LogFactory.getLog(CsvDataFileService.class);
public List<StockItem> loadData(String symbol, Period period,
DataFileType type) throws DataException {
List<StockItem> result = new ArrayList<StockItem>();
String csvFilename = Util.getDataPath(symbol, period, type);
ICsvBeanReader beanReader = null;
StockItem item = null;
try {
beanReader = new CsvBeanReader(new FileReader(csvFilename),
CsvPreference.STANDARD_PREFERENCE);
// the header elements are used to map the values to the bean (names
// must match)
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processors = Util.getProcessors(type);
while ((item = beanReader.read(StockItem.class, header, processors)) != null) {
result.add(item);
}
} catch (FileNotFoundException e) {
logger.error(csvFilename, e);
throw new DataException();
} catch (IOException e) {
logger.error(item, e);
throw new DataException();
} finally {
if (beanReader != null) {
try {
beanReader.close();
} catch (IOException e) {
logger.error("Error when closing csv file.");
}
}
}
return result;
}
public List<StockItem> loadData(String csvFilename,
DataFileType type) throws DataException {
List<StockItem> result = new ArrayList<StockItem>();
ICsvBeanReader beanReader = null;
StockItem item = null;
try {
beanReader = new CsvBeanReader(new FileReader(csvFilename),
CsvPreference.STANDARD_PREFERENCE);
// the header elements are used to map the values to the bean (names
// must match)
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processors = Util.getProcessors(type);
while ((item = beanReader.read(StockItem.class, header, processors)) != null) {
result.add(item);
}
} catch (FileNotFoundException e) {
logger.error(csvFilename, e);
throw new DataException();
} catch (IOException e) {
logger.error(item, e);
throw new DataException();
} finally {
if (beanReader != null) {
try {
beanReader.close();
} catch (IOException e) {
logger.error("Error when closing csv file.");
}
}
}
return result;
}
public static void main(String[] args) throws DataException {
CsvDataFileService service = new CsvDataFileService();
// print out stock headers
CurrencyType curType = CurrencyType.USD;
String symbol = "UVXY";
// Period period = Period.MIN5;
// Period period = Period.DAY;
Period period = Period.MIN01;
System.out.println(StockItem.printHeaders(curType, symbol, period));
// print out stock data
List<StockItem> result = service.loadData(symbol, period,
DataFileType.BVS);
for (StockItem si : result) {
System.out.println(si);
}
}
}
| 3,793 | 0.707356 | 0.706565 | 119 | 29.873949 | 22.399563 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.521008 | false | false |
12
|
2144335325f3829a32e00edcf689b8c55afdf63c
| 16,312,285,852,197 |
09e9b8a1130d2c701a6ea1239ff749313fe468ae
|
/src/com/skbh/main/ColonReplace.java
|
9eed6b27dc0c0aaa9566d3bedbf477f7bbca2f41
|
[] |
no_license
|
xorasysgen/R_D
|
https://github.com/xorasysgen/R_D
|
86942495a26b7316d638a4b2c6f614c157d0c61b
|
4f892eb637796fb7e01a128e70ad8d5a96acf0f5
|
refs/heads/master
| 2022-09-26T05:02:34.356000 | 2020-05-16T04:26:15 | 2020-05-16T04:26:15 | 189,402,798 | 0 | 0 | null | false | 2022-08-18T19:06:03 | 2019-05-30T11:36:43 | 2020-05-16T04:26:55 | 2022-08-18T19:06:00 | 636 | 0 | 0 | 4 |
Java
| false | false |
package com.skbh.main;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ColonReplace {
public static void main(String[] args) {
String string="{\"xfa:data\": { \"labour:mainForm\": { \"activitySpecific\": { \"esic\": { \"name-details\": { \"name-of-taluka-tehsil\": \"XXXXX\", \"revenue-husbast\": \"No\", \"town-village\": \"No\", \"name-of-town-village\": \"XXXXX\", \"taluka-tehsil\": \"No\", \"police-station\": \"gdfgdf\", \"name-of-municipality-ward\": \"XXXXX\", \"name-of-revenue-husbast\": \"XXXXX\", \"municipality-ward\": \"No\" },";
Pattern p=Pattern.compile("\\w+:");
//Pattern p=Pattern.compile("\\w+:");
//Pattern p=Pattern.compile(":");
Matcher m=p.matcher(string);
System.out.println(m.replaceAll(""));
}
}
|
UTF-8
|
Java
| 995 |
java
|
ColonReplace.java
|
Java
|
[] | null |
[] |
package com.skbh.main;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ColonReplace {
public static void main(String[] args) {
String string="{\"xfa:data\": { \"labour:mainForm\": { \"activitySpecific\": { \"esic\": { \"name-details\": { \"name-of-taluka-tehsil\": \"XXXXX\", \"revenue-husbast\": \"No\", \"town-village\": \"No\", \"name-of-town-village\": \"XXXXX\", \"taluka-tehsil\": \"No\", \"police-station\": \"gdfgdf\", \"name-of-municipality-ward\": \"XXXXX\", \"name-of-revenue-husbast\": \"XXXXX\", \"municipality-ward\": \"No\" },";
Pattern p=Pattern.compile("\\w+:");
//Pattern p=Pattern.compile("\\w+:");
//Pattern p=Pattern.compile(":");
Matcher m=p.matcher(string);
System.out.println(m.replaceAll(""));
}
}
| 995 | 0.483417 | 0.483417 | 18 | 54.277779 | 142.970779 | 640 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.888889 | false | false |
12
|
d93b467f4fe8b1309a00596f02c19e51ca47a810
| 17,660,905,553,047 |
0b87e585ca70991bce564508102e105ef278ed51
|
/module/dataparse/src/test/java/com/dataparse/server/ingest/BaseIngestTests.java
|
77438f49b229b00c4743c879b48af6e1e08fb7ed
|
[] |
no_license
|
RamitAnandSharma/datadocs_test
|
https://github.com/RamitAnandSharma/datadocs_test
|
5f353c30a022791e696435a553376e3505725254
|
a19bcce2095498757c708d5a9656df10ee7b24fb
|
refs/heads/master
| 2020-03-25T22:41:13.581000 | 2018-08-10T08:10:45 | 2018-08-10T08:10:45 | 144,236,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dataparse.server.ingest;
import com.dataparse.server.IsolatedContextTest;
import com.dataparse.server.auth.Auth;
import com.dataparse.server.controllers.api.table.CreateDatadocRequest;
import com.dataparse.server.controllers.api.table.SearchIndexRequest;
import com.dataparse.server.controllers.api.table.SearchIndexResponse;
import com.dataparse.server.service.docs.Datadoc;
import com.dataparse.server.service.parser.DataFormat;
import com.dataparse.server.service.schema.TableBookmark;
import com.dataparse.server.service.schema.TableRepository;
import com.dataparse.server.service.schema.TableService;
import com.dataparse.server.service.tasks.TaskManagementService;
import com.dataparse.server.service.upload.Upload;
import com.dataparse.server.service.user.User;
import com.dataparse.server.service.user.UserRepository;
import com.dataparse.server.service.visualization.VisualizationService;
import com.dataparse.server.util.FileUploadUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
@Slf4j
public class BaseIngestTests extends IsolatedContextTest {
final static public int MAX_PROCESSING_TIME = 10000;
@Autowired
private TableService tableService;
@Autowired
private FileUploadUtils fileUploadUtils;
@Autowired
private TaskManagementService taskManagementService;
@Autowired
private VisualizationService visualizationService;
@Autowired
private UserRepository userRepository;
@Autowired
private TableRepository tableRepository;
public static Collection<IngestInput> data = Lists.newArrayList(
new IngestInput("test.xml", 2, 4, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_TEXT_XML)
// new IngestInput("test.csv", 6, 3, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_CSV)
// new IngestInput("test_array.json",2, 5, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_JSON),
// new IngestInput("test_one_tab.xlsx",6, 4, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_XLSX)
);
@Test
public void ingestTest() throws Exception {
for (IngestInput ingestInput : data) {
log.info("Start processing {}", ingestInput.getName());
User u = new User("user" + ingestInput.getName(), "user1");
u.setRegistered(true);
User user = userRepository.saveUser(u);
Auth.set(new Auth(user.getId(), ""));
long start = System.currentTimeMillis();
Upload file = fileUploadUtils.createFile(ingestInput.getName(), user.getId(), null, ingestInput.getContentType());
CreateDatadocRequest createDoc = new CreateDatadocRequest("d", null, "id:" + file.getId(), true, true, start, true);
Datadoc datadoc = tableService.createDatadoc(createDoc);
List<String> tasks = datadoc.getLastFlowExecutionTasks();
long processionTime = System.currentTimeMillis() - start;
log.info("File {} ingested for {}", ingestInput.getName(), processionTime);
if(processionTime > ingestInput.getMaxTime()) {
throw new RuntimeException("Creating datadoc took too much time. " + ingestInput);
}
taskManagementService.waitUntilFinished(tasks);
List<TableBookmark> tableBookmarks = tableRepository.getTableBookmarks(datadoc.getId(), true);
Assert.assertEquals(tableBookmarks.size(), 1);
TableBookmark tableBookmark = tableBookmarks.get(0);
SearchIndexRequest request = SearchIndexRequest.builder()
.tableId(datadoc.getId())
.tableBookmarkId(tableBookmark.getId())
.stateId(tableBookmark.getBookmarkStateId().getStateId())
.from(0L)
.build();
SearchIndexResponse response = visualizationService.search(request);
int rowsCount = response.getData().getChildren().size();
Assert.assertTrue(ingestInput.getExpectedRowsCount() == rowsCount);
Set<String> columns = new HashSet<>(response.getData().getChildren().get(0).getData().keySet());
columns.remove("es_metadata_id");
Assert.assertTrue(columns.size() == ingestInput.getExpectedColumnsCount());
}
}
}
|
UTF-8
|
Java
| 4,148 |
java
|
BaseIngestTests.java
|
Java
|
[
{
"context": "ser u = new User(\"user\" + ingestInput.getName(), \"user1\");\n u.setRegistered(true);\n User user =",
"end": 2330,
"score": 0.9634373784065247,
"start": 2325,
"tag": "USERNAME",
"value": "user1"
}
] | null |
[] |
package com.dataparse.server.ingest;
import com.dataparse.server.IsolatedContextTest;
import com.dataparse.server.auth.Auth;
import com.dataparse.server.controllers.api.table.CreateDatadocRequest;
import com.dataparse.server.controllers.api.table.SearchIndexRequest;
import com.dataparse.server.controllers.api.table.SearchIndexResponse;
import com.dataparse.server.service.docs.Datadoc;
import com.dataparse.server.service.parser.DataFormat;
import com.dataparse.server.service.schema.TableBookmark;
import com.dataparse.server.service.schema.TableRepository;
import com.dataparse.server.service.schema.TableService;
import com.dataparse.server.service.tasks.TaskManagementService;
import com.dataparse.server.service.upload.Upload;
import com.dataparse.server.service.user.User;
import com.dataparse.server.service.user.UserRepository;
import com.dataparse.server.service.visualization.VisualizationService;
import com.dataparse.server.util.FileUploadUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
@Slf4j
public class BaseIngestTests extends IsolatedContextTest {
final static public int MAX_PROCESSING_TIME = 10000;
@Autowired
private TableService tableService;
@Autowired
private FileUploadUtils fileUploadUtils;
@Autowired
private TaskManagementService taskManagementService;
@Autowired
private VisualizationService visualizationService;
@Autowired
private UserRepository userRepository;
@Autowired
private TableRepository tableRepository;
public static Collection<IngestInput> data = Lists.newArrayList(
new IngestInput("test.xml", 2, 4, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_TEXT_XML)
// new IngestInput("test.csv", 6, 3, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_CSV)
// new IngestInput("test_array.json",2, 5, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_JSON),
// new IngestInput("test_one_tab.xlsx",6, 4, MAX_PROCESSING_TIME, DataFormat.CONTENT_TYPE_XLSX)
);
@Test
public void ingestTest() throws Exception {
for (IngestInput ingestInput : data) {
log.info("Start processing {}", ingestInput.getName());
User u = new User("user" + ingestInput.getName(), "user1");
u.setRegistered(true);
User user = userRepository.saveUser(u);
Auth.set(new Auth(user.getId(), ""));
long start = System.currentTimeMillis();
Upload file = fileUploadUtils.createFile(ingestInput.getName(), user.getId(), null, ingestInput.getContentType());
CreateDatadocRequest createDoc = new CreateDatadocRequest("d", null, "id:" + file.getId(), true, true, start, true);
Datadoc datadoc = tableService.createDatadoc(createDoc);
List<String> tasks = datadoc.getLastFlowExecutionTasks();
long processionTime = System.currentTimeMillis() - start;
log.info("File {} ingested for {}", ingestInput.getName(), processionTime);
if(processionTime > ingestInput.getMaxTime()) {
throw new RuntimeException("Creating datadoc took too much time. " + ingestInput);
}
taskManagementService.waitUntilFinished(tasks);
List<TableBookmark> tableBookmarks = tableRepository.getTableBookmarks(datadoc.getId(), true);
Assert.assertEquals(tableBookmarks.size(), 1);
TableBookmark tableBookmark = tableBookmarks.get(0);
SearchIndexRequest request = SearchIndexRequest.builder()
.tableId(datadoc.getId())
.tableBookmarkId(tableBookmark.getId())
.stateId(tableBookmark.getBookmarkStateId().getStateId())
.from(0L)
.build();
SearchIndexResponse response = visualizationService.search(request);
int rowsCount = response.getData().getChildren().size();
Assert.assertTrue(ingestInput.getExpectedRowsCount() == rowsCount);
Set<String> columns = new HashSet<>(response.getData().getChildren().get(0).getData().keySet());
columns.remove("es_metadata_id");
Assert.assertTrue(columns.size() == ingestInput.getExpectedColumnsCount());
}
}
}
| 4,148 | 0.750723 | 0.745661 | 95 | 42.663158 | 31.069231 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.926316 | false | false |
12
|
4d26b9f19625c287480491cecbe547fd32683c91
| 18,820,546,744,860 |
7e9d40ade7b65b73a0c707cf76e729683b67cf82
|
/src/api/java/Zeno410Utils/MethodAccessor.java
|
6df4bb8a379fa22710d88c0353689de908ec58d2
|
[
"Artistic-2.0"
] |
permissive
|
reteo/CustomOreGen
|
https://github.com/reteo/CustomOreGen
|
3012372c0627c0410103da1d7b78157c5766f88c
|
3c702e4dce8d66a886c336b8c21c91bdb441dbe5
|
refs/heads/master
| 2018-03-08T00:59:14.961000 | 2016-12-09T20:34:23 | 2016-12-09T20:34:23 | 40,027,070 | 0 | 0 | null | true | 2016-11-18T18:40:14 | 2015-07-31T22:19:51 | 2016-01-13T02:56:55 | 2016-11-18T18:40:14 | 3,170 | 0 | 0 | 0 |
Java
| null | null |
package Zeno410Utils;
import java.lang.reflect.*;
/**
*
* @author Zeno410
*/
public class MethodAccessor<ObjectType>{
private Method method;
private final String methodName;
public MethodAccessor(String _fieldName) {
methodName = _fieldName;
}
private Method method(ObjectType example) {
Class<?> classObject = example.getClass();
if (method == null) {
try {setMethod(classObject);}
catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return method;
}
private void setMethod(Class<?> classObject) throws IllegalAccessException{
// hunts through the class object and all superclasses looking for the field name
Method [] methods;
do {
methods = classObject.getDeclaredMethods();
for (int i = 0; i < methods.length;i ++) {
if (methods[i].getName().contains(methodName)) {
method = methods[i];
method.setAccessible(true);
return;
}
}
classObject = classObject.getSuperclass();
} while (classObject != Object.class);
throw new RuntimeException(methodName +" not found in class "+classObject.getName());
}
public void run(ObjectType object) {
try {
method(object).invoke(object);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
}
|
UTF-8
|
Java
| 1,720 |
java
|
MethodAccessor.java
|
Java
|
[
{
"context": "ils;\nimport java.lang.reflect.*;\n/**\n *\n * @author Zeno410\n */\npublic class MethodAccessor<ObjectType>{\n ",
"end": 75,
"score": 0.9996243715286255,
"start": 68,
"tag": "USERNAME",
"value": "Zeno410"
}
] | null |
[] |
package Zeno410Utils;
import java.lang.reflect.*;
/**
*
* @author Zeno410
*/
public class MethodAccessor<ObjectType>{
private Method method;
private final String methodName;
public MethodAccessor(String _fieldName) {
methodName = _fieldName;
}
private Method method(ObjectType example) {
Class<?> classObject = example.getClass();
if (method == null) {
try {setMethod(classObject);}
catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return method;
}
private void setMethod(Class<?> classObject) throws IllegalAccessException{
// hunts through the class object and all superclasses looking for the field name
Method [] methods;
do {
methods = classObject.getDeclaredMethods();
for (int i = 0; i < methods.length;i ++) {
if (methods[i].getName().contains(methodName)) {
method = methods[i];
method.setAccessible(true);
return;
}
}
classObject = classObject.getSuperclass();
} while (classObject != Object.class);
throw new RuntimeException(methodName +" not found in class "+classObject.getName());
}
public void run(ObjectType object) {
try {
method(object).invoke(object);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}
}
| 1,720 | 0.577326 | 0.573256 | 55 | 30.290909 | 23.106609 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.418182 | false | false |
12
|
7a5b52e9e674bc638ba68f004a5f02775188ceae
| 13,915,694,051,299 |
53d9720d3b0f3b45eb123e350c82fe9ab5832fc8
|
/src/app/db/Connection.java
|
9686d7aa50f86563d8f21df783ed7c757669ba91
|
[] |
no_license
|
jvhoven/INF-G
|
https://github.com/jvhoven/INF-G
|
cb9043db86ac3853e4fbb4410f667b3e29f590a8
|
50f3fb721f59f9533b5b4b938ef9c57765dcd223
|
refs/heads/master
| 2021-01-01T03:54:48.806000 | 2016-04-14T19:28:21 | 2016-04-14T19:28:21 | 56,143,227 | 1 | 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 app.db;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
*
* @author Henk-PC
*/
public class Connection {
public java.sql.Connection conn;
public Connection(String db_connect_string, String db_userid, String db_password) {
this.conn = this.connect(db_connect_string, db_userid, db_password);
}
public java.sql.Connection connect(String db_connect_string, String db_userid, String db_password) {
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
java.sql.Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
System.out.println("connected");
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
UTF-8
|
Java
| 1,006 |
java
|
Connection.java
|
Java
|
[
{
"context": "Set;\nimport java.sql.Statement;\n\n/**\n *\n * @author Henk-PC\n */\npublic class Connection {\n \n public jav",
"end": 313,
"score": 0.9984786510467529,
"start": 306,
"tag": "USERNAME",
"value": "Henk-PC"
}
] | 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 app.db;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
*
* @author Henk-PC
*/
public class Connection {
public java.sql.Connection conn;
public Connection(String db_connect_string, String db_userid, String db_password) {
this.conn = this.connect(db_connect_string, db_userid, db_password);
}
public java.sql.Connection connect(String db_connect_string, String db_userid, String db_password) {
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
java.sql.Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
System.out.println("connected");
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 1,006 | 0.685885 | 0.685885 | 36 | 26.944445 | 30.47945 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false |
12
|
fdab01fbc52a02a88cdba99a34594d6fc3bebd25
| 850,403,552,479 |
dfeaf07a9bea5e4d492d7e085fe8016575a89bfd
|
/src/com/bankofdavid/accounts/Account.java
|
a46a3a9427ac06ccb86580d767b6b0b97c454f9d
|
[
"Unlicense"
] |
permissive
|
dhaynespls/BankOfDavid
|
https://github.com/dhaynespls/BankOfDavid
|
8881bdb6c1bf4a6a2d56a4afd9efcd2edeb33458
|
3dae2b52e5399761fec9f072d5e09d03853a2db2
|
refs/heads/master
| 2020-04-10T02:53:11.509000 | 2018-12-10T22:03:59 | 2018-12-10T22:03:59 | 160,755,128 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bankofdavid.accounts;
import com.bankofdavid.stores.CashStore;
import java.util.Map;
import java.util.UUID;
/**
* The Account abstract class describes common functionality of a BankOfDavid account as well as any high level
* functions that are utilized in all accounts.
*
* Date: 12/10/18
* Author: dhaynes3@gmu.edu
*/
public abstract class Account {
// Name of the Account
private String accountName;
// Associated CashStore for this Account
private CashStore myCashStore;
/**
* Generate a new account with default values.
*/
public Account () {
super();
this.accountName = "";
this.myCashStore = new CashStore(0);
}
/**
* Generating a new account with non-default values.
* @param startingBalance How much money to insert initially into the account.
* @param accountName The name of the account holder.
*/
public Account (int startingBalance, String accountName) {
super();
this.accountName = accountName;
// Initialize a new CashStore object to store the money and transaction history.
this.myCashStore = new CashStore(startingBalance);
}
/**
* Add money to an account's CashStore.
* @param amountToDeposit The amount of money to place into the store.
*/
public abstract void deposit(int amountToDeposit);
/**
* Return the last UUID used to store a transaction into the CashStore.
*/
public UUID getLastUUID() {
return this.myCashStore.getLastUsedUUID();
}
/**
* Return transaction details for a given UUID.
* @param specificTransactionUUID The UUID to use when querying for the specific transaction.
*/
public Map<String, String> getSpecificTransaction(UUID specificTransactionUUID) {
return this.myCashStore.getFromStore(specificTransactionUUID);
}
public void updateStore(int cashValue) {
this.myCashStore.updateStore(cashValue);
}
public int getCurrentBalance() {
return this.myCashStore.getCurrentBalance();
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
|
UTF-8
|
Java
| 2,269 |
java
|
Account.java
|
Java
|
[
{
"context": "d in all accounts.\n *\n * Date: 12/10/18\n * Author: dhaynes3@gmu.edu\n */\npublic abstract class Account {\n\n // Name ",
"end": 335,
"score": 0.9999306201934814,
"start": 319,
"tag": "EMAIL",
"value": "dhaynes3@gmu.edu"
}
] | null |
[] |
package com.bankofdavid.accounts;
import com.bankofdavid.stores.CashStore;
import java.util.Map;
import java.util.UUID;
/**
* The Account abstract class describes common functionality of a BankOfDavid account as well as any high level
* functions that are utilized in all accounts.
*
* Date: 12/10/18
* Author: <EMAIL>
*/
public abstract class Account {
// Name of the Account
private String accountName;
// Associated CashStore for this Account
private CashStore myCashStore;
/**
* Generate a new account with default values.
*/
public Account () {
super();
this.accountName = "";
this.myCashStore = new CashStore(0);
}
/**
* Generating a new account with non-default values.
* @param startingBalance How much money to insert initially into the account.
* @param accountName The name of the account holder.
*/
public Account (int startingBalance, String accountName) {
super();
this.accountName = accountName;
// Initialize a new CashStore object to store the money and transaction history.
this.myCashStore = new CashStore(startingBalance);
}
/**
* Add money to an account's CashStore.
* @param amountToDeposit The amount of money to place into the store.
*/
public abstract void deposit(int amountToDeposit);
/**
* Return the last UUID used to store a transaction into the CashStore.
*/
public UUID getLastUUID() {
return this.myCashStore.getLastUsedUUID();
}
/**
* Return transaction details for a given UUID.
* @param specificTransactionUUID The UUID to use when querying for the specific transaction.
*/
public Map<String, String> getSpecificTransaction(UUID specificTransactionUUID) {
return this.myCashStore.getFromStore(specificTransactionUUID);
}
public void updateStore(int cashValue) {
this.myCashStore.updateStore(cashValue);
}
public int getCurrentBalance() {
return this.myCashStore.getCurrentBalance();
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
| 2,260 | 0.676069 | 0.672543 | 81 | 27.012346 | 27.301018 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.259259 | false | false |
12
|
1d1408e50374f00fadab87ffb7ef3f2e57c7006a
| 5,901,285,098,672 |
5709320d4f7bc5882a5c025364c43a5353352ba3
|
/JavaDesignPatterns/src/com/pattern/BasicConcept/Contact.java
|
1ceaeb827f96f99b9fd126a5d259317615413d93
|
[] |
no_license
|
Vinodhinithulukkanam/StudyMaterials
|
https://github.com/Vinodhinithulukkanam/StudyMaterials
|
f94be87163f9b8159f004444f8b466e728833312
|
78c23733410c567bf21f2e755161e7f084dd8458
|
refs/heads/master
| 2023-06-24T04:44:58.585000 | 2021-07-13T06:21:44 | 2021-07-13T06:21:44 | 385,259,384 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pattern.BasicConcept;
public class Contact {
public String name;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String temp="";
if(this instanceof FriendContact){
temp = "Contact [" + (name != null ? "name=" + name : "") + (((FriendContact)this).phoneNumber != null ? "phoneNumber=" + ((FriendContact)this).phoneNumber : "") + "]";
}else if(this instanceof WorkContact){
temp = "Contact [" + (name != null ? "name=" + name : "") + (((WorkContact)this).email != null ? "email=" + ((WorkContact)this).email : "") + "]";
}
return temp;
}
}
|
UTF-8
|
Java
| 631 |
java
|
Contact.java
|
Java
|
[] | null |
[] |
package com.pattern.BasicConcept;
public class Contact {
public String name;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String temp="";
if(this instanceof FriendContact){
temp = "Contact [" + (name != null ? "name=" + name : "") + (((FriendContact)this).phoneNumber != null ? "phoneNumber=" + ((FriendContact)this).phoneNumber : "") + "]";
}else if(this instanceof WorkContact){
temp = "Contact [" + (name != null ? "name=" + name : "") + (((WorkContact)this).email != null ? "email=" + ((WorkContact)this).email : "") + "]";
}
return temp;
}
}
| 631 | 0.602219 | 0.602219 | 19 | 31.210526 | 46.437939 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false |
12
|
0db260cc98bdaa1dc4e3b4701491989dc5e33ea9
| 6,682,969,140,457 |
8225e7e6a6ce5d916d783039d947a91beafbde5e
|
/src/main/java/com/sensiblemetrics/api/alpenidos/core/mvc/controller/GiantController.java
|
40026b64bebb6424bab21d0f2ba0b6672089ae6a
|
[
"MIT"
] |
permissive
|
AlexRogalskiy/alpenidos
|
https://github.com/AlexRogalskiy/alpenidos
|
ac90708fbf8b9898529c23016d5555b386e8571a
|
44d3229db5628733f8edea76ae0a9d9ead14db45
|
refs/heads/master
| 2020-06-24T19:21:04.345000 | 2019-12-24T23:38:31 | 2019-12-24T23:38:31 | 199,058,299 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sensiblemetrics.api.alpenidos.core.mvc.controller;
import com.sensiblemetrics.api.alpenidos.core.mvc.model.GiantModel;
import com.sensiblemetrics.api.alpenidos.core.mvc.view.GiantView;
import com.sensiblemetrics.api.alpenidos.core.mvc.enums.Health;
import com.sensiblemetrics.api.alpenidos.core.mvc.enums.Nourishment;
import com.sensiblemetrics.api.alpenidos.core.mvc.enums.Fatigue;
import lombok.Data;
import lombok.RequiredArgsConstructor;
/**
* GiantController can update the giant data and redraw it using the view.
*/
@Data
@RequiredArgsConstructor
public class GiantController {
private final GiantModel giant;
private final GiantView view;
public Health getHealth() {
return this.giant.getHealth();
}
public void setHealth(final Health health) {
this.giant.setHealth(health);
}
public Fatigue getFatigue() {
return this.giant.getFatigue();
}
public void setFatigue(final Fatigue fatigue) {
this.giant.setFatigue(fatigue);
}
public Nourishment getNourishment() {
return this.giant.getNourishment();
}
public void setNourishment(final Nourishment nourishment) {
this.giant.setNourishment(nourishment);
}
public void updateView() {
this.view.displayGiant(this.giant);
}
}
|
UTF-8
|
Java
| 1,319 |
java
|
GiantController.java
|
Java
|
[] | null |
[] |
package com.sensiblemetrics.api.alpenidos.core.mvc.controller;
import com.sensiblemetrics.api.alpenidos.core.mvc.model.GiantModel;
import com.sensiblemetrics.api.alpenidos.core.mvc.view.GiantView;
import com.sensiblemetrics.api.alpenidos.core.mvc.enums.Health;
import com.sensiblemetrics.api.alpenidos.core.mvc.enums.Nourishment;
import com.sensiblemetrics.api.alpenidos.core.mvc.enums.Fatigue;
import lombok.Data;
import lombok.RequiredArgsConstructor;
/**
* GiantController can update the giant data and redraw it using the view.
*/
@Data
@RequiredArgsConstructor
public class GiantController {
private final GiantModel giant;
private final GiantView view;
public Health getHealth() {
return this.giant.getHealth();
}
public void setHealth(final Health health) {
this.giant.setHealth(health);
}
public Fatigue getFatigue() {
return this.giant.getFatigue();
}
public void setFatigue(final Fatigue fatigue) {
this.giant.setFatigue(fatigue);
}
public Nourishment getNourishment() {
return this.giant.getNourishment();
}
public void setNourishment(final Nourishment nourishment) {
this.giant.setNourishment(nourishment);
}
public void updateView() {
this.view.displayGiant(this.giant);
}
}
| 1,319 | 0.730099 | 0.730099 | 47 | 27.063829 | 24.135614 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361702 | false | false |
12
|
1c971ca23aa69131b09018877edba46d41768d47
| 28,733,331,268,601 |
90874bfc09c1ddf7da4ca0ac12426fae16af980f
|
/src/test/java/cz/mikealdo/pages/HtmlProvider.java
|
8931720144d746cfd1f261c7b29d0d50b0324d9b
|
[
"Apache-2.0"
] |
permissive
|
mikealdo/fotbal-cz-api
|
https://github.com/mikealdo/fotbal-cz-api
|
cbf3df69e6ddd23f7af804797088fa4456827912
|
cad2268d0c5f369f3dcde117373420279244c41d
|
refs/heads/master
| 2020-04-05T14:39:00.356000 | 2016-10-25T05:14:50 | 2016-10-25T05:14:50 | 42,345,583 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cz.mikealdo.pages;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class HtmlProvider {
public Document getMatchStatistics() {
return Jsoup.parse(getMatchStatisticsHTML());
}
public String getMatchStatisticsHTML() {
try {
return IOUtils.toString(
this.getClass().getResource("/html/match-statistics.html"),
"UTF-8"
);
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalStateException("File for match statistics was not loaded.");
}
public Document getMatchSummary() {
return Jsoup.parse(getMatchStatisticsHTML());
}
public String getMatchSummaryHTML() {
try {
return IOUtils.toString(
this.getClass().getResource("/html/match-summary.html"),
"UTF-8"
);
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalStateException("File for match summary was not loaded.");
}
}
|
UTF-8
|
Java
| 1,157 |
java
|
HtmlProvider.java
|
Java
|
[] | null |
[] |
package cz.mikealdo.pages;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class HtmlProvider {
public Document getMatchStatistics() {
return Jsoup.parse(getMatchStatisticsHTML());
}
public String getMatchStatisticsHTML() {
try {
return IOUtils.toString(
this.getClass().getResource("/html/match-statistics.html"),
"UTF-8"
);
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalStateException("File for match statistics was not loaded.");
}
public Document getMatchSummary() {
return Jsoup.parse(getMatchStatisticsHTML());
}
public String getMatchSummaryHTML() {
try {
return IOUtils.toString(
this.getClass().getResource("/html/match-summary.html"),
"UTF-8"
);
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalStateException("File for match summary was not loaded.");
}
}
| 1,157 | 0.588591 | 0.586863 | 42 | 26.547619 | 23.508057 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
12
|
9655efdba113104a54391904a8459fd242aee6ce
| 14,233,521,648,694 |
60e51976a1cfe38ef37689af8e994efb65d4a047
|
/src/main/java/com/elearntez/springmvc/controller/LoginController.java
|
ef9771713943f5578738f3ed4deeb47f7463fe13
|
[] |
no_license
|
JawinSoft/SpringMvcDemo2
|
https://github.com/JawinSoft/SpringMvcDemo2
|
a01f88edba1e58e0f0716f14979e0fcfd61453f7
|
e2556ada20e679c364e1be08e2d9d0e10eb82e38
|
refs/heads/master
| 2022-07-03T01:46:50.147000 | 2018-11-18T17:58:26 | 2018-11-18T17:58:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.elearntez.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.elearntez.springmvc.bean.User;
@Controller
@RequestMapping("/user")
@SessionAttributes("user")
public class LoginController {
/*
* Add user in model attribute
*/
@ModelAttribute("user")
public User setUpUserForm() {
return new User();
}
@GetMapping("/login")
public String index() {
return "index";
}
@PostMapping("/dologin")
public String doLogin(@ModelAttribute("user") User user, Model model) {
// Implement your business logic
if (user.getEmail().equals("manakasunil@gmail.com") &&
user.getPassword().equals("abc@123")) {
user.setFname("Sunil");
user.setLname("Manaka");
user.setMname("Kumar");
return "success";
} else {
model.addAttribute("message", "Login failed. Try again.");
return "index";
}
}
/*
* Get user from session attribute
*/
@GetMapping("/info")
public String userInfo(@SessionAttribute("user") User user) {
System.out.println("Email: " + user.getEmail());
System.out.println("First Name: " + user.getFname());
return "user";
}
}
|
UTF-8
|
Java
| 1,656 |
java
|
LoginController.java
|
Java
|
[
{
"context": " business logic\n if (user.getEmail().equals(\"manakasunil@gmail.com\") && \n \t\t user.getPassword().equals(\"abc@123",
"end": 1065,
"score": 0.9999063014984131,
"start": 1044,
"tag": "EMAIL",
"value": "manakasunil@gmail.com"
},
{
"context": "ail.com\") && \n \t\t user.getPassword().equals(\"abc@123\")) {\n \t user.setFname(\"Sunil\");\n \t user.s",
"end": 1115,
"score": 0.9993173480033875,
"start": 1108,
"tag": "PASSWORD",
"value": "abc@123"
},
{
"context": "word().equals(\"abc@123\")) {\n \t user.setFname(\"Sunil\");\n \t user.setLname(\"Manaka\");\n \t user.se",
"end": 1148,
"score": 0.999614417552948,
"start": 1143,
"tag": "NAME",
"value": "Sunil"
},
{
"context": " \t user.setFname(\"Sunil\");\n \t user.setLname(\"Manaka\");\n \t user.setMname(\"Kumar\");\n \t return \"",
"end": 1180,
"score": 0.9995805025100708,
"start": 1174,
"tag": "NAME",
"value": "Manaka"
},
{
"context": "\t user.setLname(\"Manaka\");\n \t user.setMname(\"Kumar\");\n \t return \"success\";\n } else {\n ",
"end": 1211,
"score": 0.9994857311248779,
"start": 1206,
"tag": "NAME",
"value": "Kumar"
}
] | null |
[] |
package com.elearntez.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.elearntez.springmvc.bean.User;
@Controller
@RequestMapping("/user")
@SessionAttributes("user")
public class LoginController {
/*
* Add user in model attribute
*/
@ModelAttribute("user")
public User setUpUserForm() {
return new User();
}
@GetMapping("/login")
public String index() {
return "index";
}
@PostMapping("/dologin")
public String doLogin(@ModelAttribute("user") User user, Model model) {
// Implement your business logic
if (user.getEmail().equals("<EMAIL>") &&
user.getPassword().equals("<PASSWORD>")) {
user.setFname("Sunil");
user.setLname("Manaka");
user.setMname("Kumar");
return "success";
} else {
model.addAttribute("message", "Login failed. Try again.");
return "index";
}
}
/*
* Get user from session attribute
*/
@GetMapping("/info")
public String userInfo(@SessionAttribute("user") User user) {
System.out.println("Email: " + user.getEmail());
System.out.println("First Name: " + user.getFname());
return "user";
}
}
| 1,645 | 0.681159 | 0.679348 | 60 | 26.616667 | 22.453724 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
2d5632e537936797f5d5c69e5ecbc163c26ab2e5
| 8,976,481,673,057 |
6dbae30c806f661bcdcbc5f5f6a366ad702b1eea
|
/Corpus/eclipse.jdt.ui/4121.java
|
361d21fdbc523135fceed0b2e741e8d417206e20
|
[
"MIT"
] |
permissive
|
SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
|
https://github.com/SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
|
d3fd21745dfddb2979e8ac262588cfdfe471899f
|
0f8f4affd0ce1ecaa8ff8f487426f8edd6ad02c0
|
refs/heads/master
| 2020-03-31T15:52:01.005000 | 2018-10-01T23:38:50 | 2018-10-01T23:38:50 | 152,354,327 | 1 | 0 |
MIT
| true | 2018-10-10T02:57:02 | 2018-10-10T02:57:02 | 2018-10-01T23:38:52 | 2018-10-01T23:38:50 | 135,431 | 0 | 0 | 0 | null | false | null |
//7, 28, 7, 34
package p;
import java.util.function.Consumer;
public class A {
Consumer<Integer> a1 = x -> {
System.out.println(x + 10);
};
}
|
UTF-8
|
Java
| 162 |
java
|
4121.java
|
Java
|
[] | null |
[] |
//7, 28, 7, 34
package p;
import java.util.function.Consumer;
public class A {
Consumer<Integer> a1 = x -> {
System.out.println(x + 10);
};
}
| 162 | 0.574074 | 0.518519 | 11 | 13.727273 | 13.889767 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false |
12
|
0ce8da5a7ab15a507781380bb78490b6be6547c1
| 8,976,481,672,458 |
26b07a43157d0ae4b25201eb996ae42df972c705
|
/src/test/java/gov/dol/bg/test/DailyRegression.java
|
9eb51ed30fb9efd17b5719a78c16b9d85b9582c1
|
[] |
no_license
|
dotJPG/OPA
|
https://github.com/dotJPG/OPA
|
b9a3ebfed4f29732b7daf69e966b45809c8f1c2c
|
a948b1006e9af9e0c7bfca442c6ad43b358523c6
|
refs/heads/master
| 2021-08-31T08:58:09.547000 | 2017-12-20T21:12:50 | 2017-12-20T21:12:50 | 104,510,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package gov.dol.bg.test;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
//import gov.dol.bg.test.steps.serenity.User;
public class DailyRegression {
@Steps
User user;
//Scenario: Verify all of the navbar tabs to assert that the pages open correctly
@Given("the user is on the DOL home page")
public void the_user_is_on_homepage() {
user.onHomePage();
}
@When("the user clicks on <navMenuItem> within the top navigation bar")
public void when_I_click_on_each_link_in_the_top_navigation_bar(@Named("navMenuItem") String navMenuItem) {
user.clickNavNode(navMenuItem);
}
@Then("the <navMenuItem> page should open correctly")
public void then_the_navigation_tab_should_open_correctly(@Named("navMenuItem") String navMenuItem) {
user.shouldSeePage(navMenuItem);
}
//sub nav Topics
@When("the user clicks on the <subNavMenuItem> within the top navigation bar")
public void when_user_clicks_on_each_sublink_in_the_top_navigation_bar(@Named("subNavMenuItem") String subNavMenuItem) {
user.clickNavNode(subNavMenuItem);
}
@Then("the <subNavMenuItem> page should open correctly")
public void then_the_sub_navigation_page_should_open_correctly(@Named("subNavMenuItem") String subNavMenuItem) {
user.shouldSeePage(subNavMenuItem);
}
//Sub nav Agencies
@When("the user clicks on the <subNavMenuAgencies> within the Agencies navigation bar")
public void the_user_clicks_on_the_subNavMenuAgencies_within_the_Agencies_navigation_bar(@Named("subNavMenuAgencies") String subNavMenuAgencies) {
user.clickNavNode(subNavMenuAgencies);
}
@Then("the <subNavMenuAgencies> page should open correctly")
public void the_subNavMenuAgencies_page_should_open_correctly(@Named("subNavMenuAgencies") String subNavMenuAgencies) {
user.shouldSeePage(subNavMenuAgencies);
}
//Press
@When("the user clicks on the <subNavMenuPress> within the Press navigation bar")
public void the_user_clicks_on_the_subNavMenuPress_within_the_Press_navigation_bar(@Named("subNavMenuPress") String subNavMenuPress) {
user.clickNavNode(subNavMenuPress);
}
@Then("the <subNavMenuPress> page should open correctly")
public void the_subNavMenuPress_page_should_open_correctly(@Named("subNavMenuPress") String subNavMenuPress) {
user.shouldSeePage(subNavMenuPress);
}
//Footer
@When("the user clicks on the <navFooterItem> within the Footer")
public void the_user_clicks_on_the_navFooterItem_within_the_Press_navigation_bar(@Named("navFooterItem") String navFooterItem) {
user.clickNavNode(navFooterItem);
}
@Then("the <navFooterItem> page should open correctly")
public void the_navFooterItem_page_should_open_correctly(@Named("navFooterItem") String navFooterItem) {
user.shouldSeePage(navFooterItem);
}
//Social Media
@When("the user clicks on the <socMediaLink> link")
public void the_user_clicks_on_the_socMediaLink_within_the_Press_navigation_barr(@Named("socMediaLink") String socMediaLink) {
user.clickNavNode(socMediaLink);
}
@Then("the <socMediaLink> page should open correctly")
public void the_socMediaLink_page_should_open_correctlyy(@Named("socMediaLink") String socMediaLink) {
user.shouldSeePage(socMediaLink);
}
//ILAB Homepage
//******************************************************************************************************//
@Given("the user is on the ILAB home page")
public void the_user_is_on_ihomepage() {
user.onILABPage();
}
@When("the user clicks on <aboutUsMenuItem> within the About Us tab on the menu bar")
public void when_I_click_on_each_link_in_the_top_nav_bar(@Named("aboutUsMenuItem") String aboutUsMenuItem) {
user.clickNavNode(aboutUsMenuItem);
}
@Then("the <aboutUsMenuItem> page should open correctly")
public void then_the_nav_tab_should_open_correctly(@Named("aboutUsMenuItem") String aboutUsMenuItem) {
user.shouldSeePage(aboutUsMenuItem);
}
@When("the user clicks on <ourWorkMenuItem> within the Our Work tab on the menu bar")
public void when_I_click_on_each_link_in_the_top_nav_panel(@Named("ourWorkMenuItem") String ourWorkMenuItem) {
user.clickNavNode(ourWorkMenuItem);
}
@Then("the <ourWorkMenuItem> page should open correctly")
public void then_the_OurWorkMenuItem_tab_should_open_correctly(@Named("ourWorkMenuItem") String ourWorkMenuItem) {
user.shouldSeePage(ourWorkMenuItem);
}
@When("the user clicks on <resourcesMenuItem> within the Resources tab on the menu bar")
public void when_I_click_on_each_link_in_the_resources_panel(@Named("resourcesMenuItem") String resourcesMenuItem) {
user.clickNavNode(resourcesMenuItem);
}
@Then("the <resourcesMenuItem> page should open correctly")
public void then_the_resource_should_open_correctly(@Named("resourcesMenuItem") String resourcesMenuItem) {
user.shouldSeePage(resourcesMenuItem);
}
@When("the user clicks on <actionMenuItem> within the ILAB In Action tab on the menu bar")
public void when_I_click_on_each_link_in_the_action_panel(@Named("actionMenuItem") String actionMenuItem) {
user.clickNavNode(actionMenuItem);
}
@Then("the <actionMenuItem> page should open correctly")
public void then_the_action_should_open_correctly(@Named("actionMenuItem") String actionMenuItem) {
user.shouldSeePage(actionMenuItem);
}
//EBSA Homepage
//******************************************************************************************************//
@Given("the user is on the EBSA home page")
public void the_user_is_on_ehomepage() {
user.onEBSAPage();
}
@When("the user clicks on <ebsaMenuItem> within the menu bar")
public void when_I_click_on_each_link_in_the_top_nav(@Named("ebsaMenuItem") String ebsaMenuItem) {
user.clickNavNode(ebsaMenuItem);
}
@Then("the <ebsaMenuItem> page should open correctly")
public void then_the_ebsa_tab_should_open_correctly(@Named("ebsaMenuItem") String ebsaMenuItem) {
user.shouldSeePage(ebsaMenuItem);
}
@When("the user clicks on <aboutEBSAMenuItem> within the About Us tab on the menu bar")
public void when_I_click_on_each_link_in_the_aboutEBSA_tab(@Named("aboutEBSAMenuItem") String aboutEBSAMenuItem) {
user.clickNavNode(aboutEBSAMenuItem);
}
@Then("the <aboutEBSAMenuItem> page should open correctly")
public void then_the_aboutEBSA_tab_should_open_correctly(@Named("aboutEBSAMenuItem") String aboutEBSAMenuItem) {
user.shouldSeePage(aboutEBSAMenuItem);
}
@When("the user clicks on <workFamMenuItem> within the Workers & Families tab on the menu bar")
public void when_I_click_on_each_link_in_the_workFam_tab(@Named("workFamMenuItem") String workFamMenuItem) {
user.clickNavNode(workFamMenuItem);
}
@Then("the <workFamMenuItem> page should open correctly")
public void then_the_workFam_tab_should_open_correctly(@Named("workFamMenuItem") String workFamMenuItem) {
user.shouldSeePage(workFamMenuItem);
}
@When("the user clicks on <employerAdviserMenuItem> within the Employers & Advisers tab on the menu bar")
public void when_I_click_on_each_link_in_the_employerAdviser_tab(@Named("employerAdviserMenuItem") String employerAdviserMenuItem) {
user.clickNavNode(employerAdviserMenuItem);
}
@Then("the <employerAdviserMenuItem> page should open correctly")
public void then_the_employerAdviser_tab_should_open_correctly(@Named("employerAdviserMenuItem") String employerAdviserMenuItem) {
user.shouldSeePage(employerAdviserMenuItem);
}
@When("the user clicks on <researchersMenuItem> within the Researchers tab on the menu bar")
public void when_I_click_on_each_link_in_the_researchers_tab(@Named("researchersMenuItem") String researchersMenuItem) {
user.clickNavNode(researchersMenuItem);
}
@Then("the <researchersMenuItem> page should open correctly")
public void then_the__tab_should_open_correctly(@Named("researchersMenuItem") String researchersMenuItem) {
user.shouldSeePage(researchersMenuItem);
}
@When("the user clicks on <keyTopicMenuItem> within the Key Topics tab on the menu bar")
public void when_I_click_on_each_link_in_the_keyTopic_tab(@Named("keyTopicMenuItem") String keyTopicMenuItem) {
user.clickNavNode(keyTopicMenuItem);
}
@Then("the <keyTopicMenuItem> page should open correctly")
public void then_the__keyTopic_should_open_correctly(@Named("keyTopicMenuItem") String keyTopicMenuItem) {
user.shouldSeePage(keyTopicMenuItem);
}
@When("the user clicks on <lawsregsMenuItem> within the Laws & Regulations tab on the menu bar")
public void when_I_click_on_each_link_in_the_lawsregs_tab(@Named("lawsregsMenuItem") String lawsregsMenuItem) {
user.clickNavNode(lawsregsMenuItem);
}
@Then("the <lawsregsMenuItem> page should open correctly")
public void then_the__lawsregs_should_open_correctly(@Named("lawsregsMenuItem") String lawsregsMenuItem) {
user.shouldSeePage(lawsregsMenuItem);
}
}
|
UTF-8
|
Java
| 9,241 |
java
|
DailyRegression.java
|
Java
|
[] | null |
[] |
package gov.dol.bg.test;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
//import gov.dol.bg.test.steps.serenity.User;
public class DailyRegression {
@Steps
User user;
//Scenario: Verify all of the navbar tabs to assert that the pages open correctly
@Given("the user is on the DOL home page")
public void the_user_is_on_homepage() {
user.onHomePage();
}
@When("the user clicks on <navMenuItem> within the top navigation bar")
public void when_I_click_on_each_link_in_the_top_navigation_bar(@Named("navMenuItem") String navMenuItem) {
user.clickNavNode(navMenuItem);
}
@Then("the <navMenuItem> page should open correctly")
public void then_the_navigation_tab_should_open_correctly(@Named("navMenuItem") String navMenuItem) {
user.shouldSeePage(navMenuItem);
}
//sub nav Topics
@When("the user clicks on the <subNavMenuItem> within the top navigation bar")
public void when_user_clicks_on_each_sublink_in_the_top_navigation_bar(@Named("subNavMenuItem") String subNavMenuItem) {
user.clickNavNode(subNavMenuItem);
}
@Then("the <subNavMenuItem> page should open correctly")
public void then_the_sub_navigation_page_should_open_correctly(@Named("subNavMenuItem") String subNavMenuItem) {
user.shouldSeePage(subNavMenuItem);
}
//Sub nav Agencies
@When("the user clicks on the <subNavMenuAgencies> within the Agencies navigation bar")
public void the_user_clicks_on_the_subNavMenuAgencies_within_the_Agencies_navigation_bar(@Named("subNavMenuAgencies") String subNavMenuAgencies) {
user.clickNavNode(subNavMenuAgencies);
}
@Then("the <subNavMenuAgencies> page should open correctly")
public void the_subNavMenuAgencies_page_should_open_correctly(@Named("subNavMenuAgencies") String subNavMenuAgencies) {
user.shouldSeePage(subNavMenuAgencies);
}
//Press
@When("the user clicks on the <subNavMenuPress> within the Press navigation bar")
public void the_user_clicks_on_the_subNavMenuPress_within_the_Press_navigation_bar(@Named("subNavMenuPress") String subNavMenuPress) {
user.clickNavNode(subNavMenuPress);
}
@Then("the <subNavMenuPress> page should open correctly")
public void the_subNavMenuPress_page_should_open_correctly(@Named("subNavMenuPress") String subNavMenuPress) {
user.shouldSeePage(subNavMenuPress);
}
//Footer
@When("the user clicks on the <navFooterItem> within the Footer")
public void the_user_clicks_on_the_navFooterItem_within_the_Press_navigation_bar(@Named("navFooterItem") String navFooterItem) {
user.clickNavNode(navFooterItem);
}
@Then("the <navFooterItem> page should open correctly")
public void the_navFooterItem_page_should_open_correctly(@Named("navFooterItem") String navFooterItem) {
user.shouldSeePage(navFooterItem);
}
//Social Media
@When("the user clicks on the <socMediaLink> link")
public void the_user_clicks_on_the_socMediaLink_within_the_Press_navigation_barr(@Named("socMediaLink") String socMediaLink) {
user.clickNavNode(socMediaLink);
}
@Then("the <socMediaLink> page should open correctly")
public void the_socMediaLink_page_should_open_correctlyy(@Named("socMediaLink") String socMediaLink) {
user.shouldSeePage(socMediaLink);
}
//ILAB Homepage
//******************************************************************************************************//
@Given("the user is on the ILAB home page")
public void the_user_is_on_ihomepage() {
user.onILABPage();
}
@When("the user clicks on <aboutUsMenuItem> within the About Us tab on the menu bar")
public void when_I_click_on_each_link_in_the_top_nav_bar(@Named("aboutUsMenuItem") String aboutUsMenuItem) {
user.clickNavNode(aboutUsMenuItem);
}
@Then("the <aboutUsMenuItem> page should open correctly")
public void then_the_nav_tab_should_open_correctly(@Named("aboutUsMenuItem") String aboutUsMenuItem) {
user.shouldSeePage(aboutUsMenuItem);
}
@When("the user clicks on <ourWorkMenuItem> within the Our Work tab on the menu bar")
public void when_I_click_on_each_link_in_the_top_nav_panel(@Named("ourWorkMenuItem") String ourWorkMenuItem) {
user.clickNavNode(ourWorkMenuItem);
}
@Then("the <ourWorkMenuItem> page should open correctly")
public void then_the_OurWorkMenuItem_tab_should_open_correctly(@Named("ourWorkMenuItem") String ourWorkMenuItem) {
user.shouldSeePage(ourWorkMenuItem);
}
@When("the user clicks on <resourcesMenuItem> within the Resources tab on the menu bar")
public void when_I_click_on_each_link_in_the_resources_panel(@Named("resourcesMenuItem") String resourcesMenuItem) {
user.clickNavNode(resourcesMenuItem);
}
@Then("the <resourcesMenuItem> page should open correctly")
public void then_the_resource_should_open_correctly(@Named("resourcesMenuItem") String resourcesMenuItem) {
user.shouldSeePage(resourcesMenuItem);
}
@When("the user clicks on <actionMenuItem> within the ILAB In Action tab on the menu bar")
public void when_I_click_on_each_link_in_the_action_panel(@Named("actionMenuItem") String actionMenuItem) {
user.clickNavNode(actionMenuItem);
}
@Then("the <actionMenuItem> page should open correctly")
public void then_the_action_should_open_correctly(@Named("actionMenuItem") String actionMenuItem) {
user.shouldSeePage(actionMenuItem);
}
//EBSA Homepage
//******************************************************************************************************//
@Given("the user is on the EBSA home page")
public void the_user_is_on_ehomepage() {
user.onEBSAPage();
}
@When("the user clicks on <ebsaMenuItem> within the menu bar")
public void when_I_click_on_each_link_in_the_top_nav(@Named("ebsaMenuItem") String ebsaMenuItem) {
user.clickNavNode(ebsaMenuItem);
}
@Then("the <ebsaMenuItem> page should open correctly")
public void then_the_ebsa_tab_should_open_correctly(@Named("ebsaMenuItem") String ebsaMenuItem) {
user.shouldSeePage(ebsaMenuItem);
}
@When("the user clicks on <aboutEBSAMenuItem> within the About Us tab on the menu bar")
public void when_I_click_on_each_link_in_the_aboutEBSA_tab(@Named("aboutEBSAMenuItem") String aboutEBSAMenuItem) {
user.clickNavNode(aboutEBSAMenuItem);
}
@Then("the <aboutEBSAMenuItem> page should open correctly")
public void then_the_aboutEBSA_tab_should_open_correctly(@Named("aboutEBSAMenuItem") String aboutEBSAMenuItem) {
user.shouldSeePage(aboutEBSAMenuItem);
}
@When("the user clicks on <workFamMenuItem> within the Workers & Families tab on the menu bar")
public void when_I_click_on_each_link_in_the_workFam_tab(@Named("workFamMenuItem") String workFamMenuItem) {
user.clickNavNode(workFamMenuItem);
}
@Then("the <workFamMenuItem> page should open correctly")
public void then_the_workFam_tab_should_open_correctly(@Named("workFamMenuItem") String workFamMenuItem) {
user.shouldSeePage(workFamMenuItem);
}
@When("the user clicks on <employerAdviserMenuItem> within the Employers & Advisers tab on the menu bar")
public void when_I_click_on_each_link_in_the_employerAdviser_tab(@Named("employerAdviserMenuItem") String employerAdviserMenuItem) {
user.clickNavNode(employerAdviserMenuItem);
}
@Then("the <employerAdviserMenuItem> page should open correctly")
public void then_the_employerAdviser_tab_should_open_correctly(@Named("employerAdviserMenuItem") String employerAdviserMenuItem) {
user.shouldSeePage(employerAdviserMenuItem);
}
@When("the user clicks on <researchersMenuItem> within the Researchers tab on the menu bar")
public void when_I_click_on_each_link_in_the_researchers_tab(@Named("researchersMenuItem") String researchersMenuItem) {
user.clickNavNode(researchersMenuItem);
}
@Then("the <researchersMenuItem> page should open correctly")
public void then_the__tab_should_open_correctly(@Named("researchersMenuItem") String researchersMenuItem) {
user.shouldSeePage(researchersMenuItem);
}
@When("the user clicks on <keyTopicMenuItem> within the Key Topics tab on the menu bar")
public void when_I_click_on_each_link_in_the_keyTopic_tab(@Named("keyTopicMenuItem") String keyTopicMenuItem) {
user.clickNavNode(keyTopicMenuItem);
}
@Then("the <keyTopicMenuItem> page should open correctly")
public void then_the__keyTopic_should_open_correctly(@Named("keyTopicMenuItem") String keyTopicMenuItem) {
user.shouldSeePage(keyTopicMenuItem);
}
@When("the user clicks on <lawsregsMenuItem> within the Laws & Regulations tab on the menu bar")
public void when_I_click_on_each_link_in_the_lawsregs_tab(@Named("lawsregsMenuItem") String lawsregsMenuItem) {
user.clickNavNode(lawsregsMenuItem);
}
@Then("the <lawsregsMenuItem> page should open correctly")
public void then_the__lawsregs_should_open_correctly(@Named("lawsregsMenuItem") String lawsregsMenuItem) {
user.shouldSeePage(lawsregsMenuItem);
}
}
| 9,241 | 0.726328 | 0.726328 | 198 | 45.671719 | 42.593311 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.742424 | false | false |
12
|
e0787661b0f063ce3ea70fcb7e70231252ab981f
| 28,398,323,784,583 |
4abf0db235155fc51ae1966c824dfaf80f74eec5
|
/src/main/java/photosrenamer/gui/FileItemListModel.java
|
023ae7546164161c9be8d1474a3fb413a884bd1c
|
[] |
no_license
|
sualeh/photosrenamer
|
https://github.com/sualeh/photosrenamer
|
810b9013b06e123b47034d774c31fbb2869fc275
|
6dff2aa2028ba8ce77118583a3c35b7c7a538c30
|
refs/heads/main
| 2023-08-08T08:06:58.663000 | 2023-08-01T21:17:41 | 2023-08-01T21:17:41 | 8,834,814 | 0 | 1 | null | false | 2023-08-01T21:17:43 | 2013-03-17T13:34:52 | 2022-03-03T21:22:55 | 2023-08-01T21:17:42 | 255 | 0 | 1 | 0 |
Java
| false | false |
/*
* Copyright (c) 2004-2023, Sualeh Fatehi <sualeh@hotmail.com>
* This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
* or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*/
package photosrenamer.gui;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.swing.AbstractListModel;
import photosrenamer.photosrenamer.FileComparator;
import photosrenamer.photosrenamer.FileItem;
public class FileItemListModel extends AbstractListModel<FileItem> {
private static final long serialVersionUID = 4050810987907022589L;
private static final Logger logger = Logger.getGlobal();
private final List<FileItem> fileItems;
private Path workingDir;
public FileItemListModel() {
fileItems = new ArrayList<>();
}
@Override
public FileItem getElementAt(final int index) {
return fileItems.get(index);
}
public List<Path> getFiles() {
final List<Path> files = new ArrayList<>(fileItems.size());
for (final FileItem fileItem : fileItems) {
files.add(fileItem.getFile());
}
return files;
}
@Override
public int getSize() {
return fileItems.size();
}
public void load() {
if (workingDir == null && !Files.isDirectory(workingDir)) {
return;
}
fileItems.clear();
try (DirectoryStream<Path> dirStream =
Files.newDirectoryStream(workingDir, "*.{jpeg,jpg,gif,tiff,tif,png}")) {
for (final Path file : dirStream) {
fileItems.add(new FileItem(file));
}
} catch (final IOException e) {
logger.log(new LogRecord(Level.CONFIG, e.getMessage()));
}
sort(FileComparator.BY_NAME);
}
public void setWorkingDirectory(final Path workingDirectory) {
if (workingDirectory != null && Files.isDirectory(workingDirectory)) {
workingDir = workingDirectory;
load();
} else {
workingDir = null;
fileItems.clear();
}
}
/**
* Sorts items in the list.
*
* @param comparator Comparator for sorting.
*/
public void sort(final Comparator<FileItem> comparator) {
Collections.sort(fileItems, comparator);
fireContentsChanged(this, 0, getSize() - 1);
}
public void swap(final int i, final int j) {
if (i == j) {
return;
}
Collections.swap(fileItems, i, j);
fireContentsChanged(this, i, j);
}
}
|
UTF-8
|
Java
| 2,783 |
java
|
FileItemListModel.java
|
Java
|
[
{
"context": "/*\n * Copyright (c) 2004-2023, Sualeh Fatehi <sualeh@hotmail.com>\n * This work is licensed und",
"end": 44,
"score": 0.9998711943626404,
"start": 31,
"tag": "NAME",
"value": "Sualeh Fatehi"
},
{
"context": "/*\n * Copyright (c) 2004-2023, Sualeh Fatehi <sualeh@hotmail.com>\n * This work is licensed under the Creative Comm",
"end": 64,
"score": 0.9999317526817322,
"start": 46,
"tag": "EMAIL",
"value": "sualeh@hotmail.com"
}
] | null |
[] |
/*
* Copyright (c) 2004-2023, <NAME> <<EMAIL>>
* This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
* or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*/
package photosrenamer.gui;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.swing.AbstractListModel;
import photosrenamer.photosrenamer.FileComparator;
import photosrenamer.photosrenamer.FileItem;
public class FileItemListModel extends AbstractListModel<FileItem> {
private static final long serialVersionUID = 4050810987907022589L;
private static final Logger logger = Logger.getGlobal();
private final List<FileItem> fileItems;
private Path workingDir;
public FileItemListModel() {
fileItems = new ArrayList<>();
}
@Override
public FileItem getElementAt(final int index) {
return fileItems.get(index);
}
public List<Path> getFiles() {
final List<Path> files = new ArrayList<>(fileItems.size());
for (final FileItem fileItem : fileItems) {
files.add(fileItem.getFile());
}
return files;
}
@Override
public int getSize() {
return fileItems.size();
}
public void load() {
if (workingDir == null && !Files.isDirectory(workingDir)) {
return;
}
fileItems.clear();
try (DirectoryStream<Path> dirStream =
Files.newDirectoryStream(workingDir, "*.{jpeg,jpg,gif,tiff,tif,png}")) {
for (final Path file : dirStream) {
fileItems.add(new FileItem(file));
}
} catch (final IOException e) {
logger.log(new LogRecord(Level.CONFIG, e.getMessage()));
}
sort(FileComparator.BY_NAME);
}
public void setWorkingDirectory(final Path workingDirectory) {
if (workingDirectory != null && Files.isDirectory(workingDirectory)) {
workingDir = workingDirectory;
load();
} else {
workingDir = null;
fileItems.clear();
}
}
/**
* Sorts items in the list.
*
* @param comparator Comparator for sorting.
*/
public void sort(final Comparator<FileItem> comparator) {
Collections.sort(fileItems, comparator);
fireContentsChanged(this, 0, getSize() - 1);
}
public void swap(final int i, final int j) {
if (i == j) {
return;
}
Collections.swap(fileItems, i, j);
fireContentsChanged(this, i, j);
}
}
| 2,765 | 0.696011 | 0.68092 | 105 | 25.504763 | 25.074793 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590476 | false | false |
12
|
c456b093f48840141abf9593a4de2dadad7e46e1
| 25,348,897,027,205 |
17c06e3d0744ef433538904c317b3b4830702fa8
|
/cdiwebproject/src/main/java/com/learn/pojoentitywithparamconstruct/ApplicationScopeWithConstruct.java
|
3c3d70928a2a53d509c7089a9d426263727b17e6
|
[] |
no_license
|
ravirohit/jbos-webdeploy-learning
|
https://github.com/ravirohit/jbos-webdeploy-learning
|
d96627b4430862bc2a5111186089ad1f3e759abb
|
ddd1731f9fc81a1b553689be7033987b39a7d3dc
|
refs/heads/master
| 2020-04-27T12:50:54.100000 | 2019-03-10T06:21:56 | 2019-03-10T06:21:56 | 174,346,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.learn.pojoentitywithparamconstruct;
public class ApplicationScopeWithConstruct {
private String name;
public ApplicationScopeWithConstruct(String name){
this.name = name;
}
public String getString(){
return name;
}
}
|
UTF-8
|
Java
| 251 |
java
|
ApplicationScopeWithConstruct.java
|
Java
|
[] | null |
[] |
package com.learn.pojoentitywithparamconstruct;
public class ApplicationScopeWithConstruct {
private String name;
public ApplicationScopeWithConstruct(String name){
this.name = name;
}
public String getString(){
return name;
}
}
| 251 | 0.749004 | 0.749004 | 15 | 15.733334 | 18.684992 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.066667 | false | false |
12
|
f13c3b63962d0e163eb3e530d6c35805c03da2fc
| 30,494,267,843,243 |
d3b3d14496afddb3237b2bece3102ce465693172
|
/gimt-web/src/edu/gimt/validators/KilometerValidator.java
|
c5815f2c65d6a75c07adef320dfac1df88c777dd
|
[] |
no_license
|
vmsobrino/TFG-IncidenciasGeolocalizadas
|
https://github.com/vmsobrino/TFG-IncidenciasGeolocalizadas
|
6811069be24c3159f5a0d14bff79346107eed40e
|
bbd71d43cd9eb3babe409f316936573653acc6be
|
refs/heads/master
| 2020-06-23T15:05:09.468000 | 2019-07-24T16:14:28 | 2019-07-24T16:14:28 | 198,657,646 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.gimt.validators;
import edu.gimt.validators.exception.ValidationException;
public class KilometerValidator extends GeoIncidenceAbstractValidator implements IValidator {
public KilometerValidator(Object validationItem) {
super(validationItem);
}
@Override
public void validate() throws ValidationException {
StringBuilder errors = new StringBuilder();
String initialKm = null;
String finalKm = null;
//stParams = getParams(); // No Parameters for validation
initialKm = (validationItem != null ? validationItem.getInitialKilometer() : null);
finalKm = (validationItem != null ? validationItem.getFinalKilometer() : null);
if (initialKm != null && finalKm != null ) {
try {
Double.parseDouble(initialKm);
Double.parseDouble(finalKm);
}
catch (NumberFormatException nfe) {
errors.append("Km. Inicial y/o Final: <" + initialKm + ", " + finalKm + "> no tienen un valor numérico.");
throw new ValidationException (errors.toString());
}
}
}
}
|
ISO-8859-2
|
Java
| 1,040 |
java
|
KilometerValidator.java
|
Java
|
[] | null |
[] |
package edu.gimt.validators;
import edu.gimt.validators.exception.ValidationException;
public class KilometerValidator extends GeoIncidenceAbstractValidator implements IValidator {
public KilometerValidator(Object validationItem) {
super(validationItem);
}
@Override
public void validate() throws ValidationException {
StringBuilder errors = new StringBuilder();
String initialKm = null;
String finalKm = null;
//stParams = getParams(); // No Parameters for validation
initialKm = (validationItem != null ? validationItem.getInitialKilometer() : null);
finalKm = (validationItem != null ? validationItem.getFinalKilometer() : null);
if (initialKm != null && finalKm != null ) {
try {
Double.parseDouble(initialKm);
Double.parseDouble(finalKm);
}
catch (NumberFormatException nfe) {
errors.append("Km. Inicial y/o Final: <" + initialKm + ", " + finalKm + "> no tienen un valor numérico.");
throw new ValidationException (errors.toString());
}
}
}
}
| 1,040 | 0.699711 | 0.699711 | 34 | 28.617647 | 30.789623 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.911765 | false | false |
12
|
3bc5aa8a43050d3274e5122d7301d70dedda7119
| 13,812,614,840,385 |
09ded4803adff8bc1906ce75c7c9687a385317a8
|
/Week1/day4/src/main/com/sultana/assignment1/DemoSingleton.java
|
5be39acf8c616d68071914520776d466db017b26
|
[] |
no_license
|
SultanaSmoothStack/Week1
|
https://github.com/SultanaSmoothStack/Week1
|
f0596f27b4bc9f2a1973ff68154cc05b23775ee0
|
971616f251f49af9aa8c782754d12254d34b2bab
|
refs/heads/master
| 2023-03-13T01:30:58.808000 | 2021-03-01T20:43:28 | 2021-03-01T20:43:28 | 341,622,808 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package main.com.sultana.assignment1;
public class DemoSingleton {
private static volatile DemoSingleton instance;
int value;
private DemoSingleton(){
}
public static DemoSingleton getInstance(){
if(instance == null){
synchronized (DemoSingleton.class){
if(instance == null){
instance = new DemoSingleton();
}
}
}
return instance;
}
}
|
UTF-8
|
Java
| 465 |
java
|
DemoSingleton.java
|
Java
|
[] | null |
[] |
package main.com.sultana.assignment1;
public class DemoSingleton {
private static volatile DemoSingleton instance;
int value;
private DemoSingleton(){
}
public static DemoSingleton getInstance(){
if(instance == null){
synchronized (DemoSingleton.class){
if(instance == null){
instance = new DemoSingleton();
}
}
}
return instance;
}
}
| 465 | 0.554839 | 0.552688 | 23 | 19.217392 | 18.108265 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.217391 | false | false |
12
|
fd0db181cc8768417812ec9d9cea657a9e448bdf
| 25,761,213,899,070 |
fd4093a997f702a141f152b58bd6abf4c8ae094d
|
/src/com/dfpbacas/subgame/MainActivity.java
|
e4f022c7353f4e255d28491044487b5f7442773f
|
[] |
no_license
|
AShirtz/SubGame
|
https://github.com/AShirtz/SubGame
|
01bbb05628ddaa2f8f36a04c6b7a24a0220e30f5
|
2921061fcb5ec1d1d344b05bd0f62dc6ee23e88a
|
refs/heads/master
| 2020-05-24T12:38:17.622000 | 2013-12-05T14:39:27 | 2013-12-05T14:39:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dfpbacas.subgame;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private MenuFrag mMenuFragment = null;
private final String MENU_FRAG_TAG = "menu_frag_tag";
private DisplayGameFragment mDisplayGameFragment = null;
private final String DISPLAY_GAME_FRAG_TAG = "display_game_frag_tag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*setContentView(R.layout.activity_main);
mDisplayGameFragment = (DisplayGameFragment) this.getSupportFragmentManager().findFragmentByTag(DISPLAY_GAME_FRAG_TAG);
if (mDisplayGameFragment == null) {
mDisplayGameFragment = new DisplayGameFragment();
this.getSupportFragmentManager().beginTransaction().add(android.R.id.content, mDisplayGameFragment, DISPLAY_GAME_FRAG_TAG).commit();
}*/
setContentView(R.layout.activity_main);
mMenuFragment = (MenuFrag) this.getSupportFragmentManager().findFragmentByTag(MENU_FRAG_TAG);
if(mMenuFragment == null){
mMenuFragment = new MenuFrag();
this.getSupportFragmentManager().beginTransaction().add(android.R.id.content, mMenuFragment, MENU_FRAG_TAG).commit();
}
}
protected void GameScreen(Bundle savedInstanceState){
mDisplayGameFragment = (DisplayGameFragment) this.getSupportFragmentManager().findFragmentByTag(DISPLAY_GAME_FRAG_TAG);
if (mDisplayGameFragment == null) {
mDisplayGameFragment = new DisplayGameFragment();
this.getSupportFragmentManager().beginTransaction().add(android.R.id.content, mDisplayGameFragment, DISPLAY_GAME_FRAG_TAG).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
UTF-8
|
Java
| 1,871 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.dfpbacas.subgame;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private MenuFrag mMenuFragment = null;
private final String MENU_FRAG_TAG = "menu_frag_tag";
private DisplayGameFragment mDisplayGameFragment = null;
private final String DISPLAY_GAME_FRAG_TAG = "display_game_frag_tag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*setContentView(R.layout.activity_main);
mDisplayGameFragment = (DisplayGameFragment) this.getSupportFragmentManager().findFragmentByTag(DISPLAY_GAME_FRAG_TAG);
if (mDisplayGameFragment == null) {
mDisplayGameFragment = new DisplayGameFragment();
this.getSupportFragmentManager().beginTransaction().add(android.R.id.content, mDisplayGameFragment, DISPLAY_GAME_FRAG_TAG).commit();
}*/
setContentView(R.layout.activity_main);
mMenuFragment = (MenuFrag) this.getSupportFragmentManager().findFragmentByTag(MENU_FRAG_TAG);
if(mMenuFragment == null){
mMenuFragment = new MenuFrag();
this.getSupportFragmentManager().beginTransaction().add(android.R.id.content, mMenuFragment, MENU_FRAG_TAG).commit();
}
}
protected void GameScreen(Bundle savedInstanceState){
mDisplayGameFragment = (DisplayGameFragment) this.getSupportFragmentManager().findFragmentByTag(DISPLAY_GAME_FRAG_TAG);
if (mDisplayGameFragment == null) {
mDisplayGameFragment = new DisplayGameFragment();
this.getSupportFragmentManager().beginTransaction().add(android.R.id.content, mDisplayGameFragment, DISPLAY_GAME_FRAG_TAG).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| 1,871 | 0.774987 | 0.774452 | 48 | 37.979168 | 38.432022 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.0625 | false | false |
12
|
e1d4faab1dbc53a3805a4c96762d80cfedc13732
| 38,036,230,397,218 |
262c98fde7ca35a2a13e49275f96719ff384b51e
|
/app/src/main/java/com/beta/MoneyballMaster/http/utils/CommonInterceptor.java
|
0f1f496c7cb11307edf889becbc013684b901a02
|
[] |
no_license
|
wysthelastcrazy/BaseFrameDemo
|
https://github.com/wysthelastcrazy/BaseFrameDemo
|
1b805f972ee966c7012b28ed6190d7be7ad3efe5
|
7ac78e9ba5509da8b22401d8f6181738cfe44960
|
refs/heads/master
| 2018-09-19T16:22:30.206000 | 2018-06-21T02:42:13 | 2018-06-21T02:42:13 | 112,708,690 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.beta.MoneyballMaster.http.utils;
import android.text.TextUtils;
import com.beta.MoneyballMaster.BuildConfig;
import com.beta.MoneyballMaster.utils.MyLog;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by yas on 2017/11/30.
* 封装公共参数
*/
public class CommonInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request oldRequest = chain.request();
// 新的请求
Request.Builder newBuilder = oldRequest.newBuilder();
if ("GET".equals(oldRequest.method())){
newBuilder.url(addGetCommonParams(oldRequest).build());
newBuilder.method(oldRequest.method(),oldRequest.body());
}else if ("POST".equals(oldRequest.method())){
RequestBody body=oldRequest.body();
if (body instanceof FormBody){
//不普通的post请求
FormBody formBody= (FormBody) body;
newBuilder.method(oldRequest.method(),addParamsToFormBody(formBody))
.url(oldRequest.url());
}else if (body instanceof MultipartBody){
//有文件上传的post请求
//公共参数在组织生成MultipartBody时已添加,此处无需再添加
// return chain.proceed(oldRequest);
}
}
// 新的请求
newBuilder.addHeader("Cookie", getCookie())
.build();
Response response = chain.proceed(newBuilder.build());
// if (BuildConfig.DEBUG) {
// MyLog.debug("---> " + response.body().string());
// }
return response;
}
/***
* cookie
* @return
*/
private final String getCookie(){
return "";
}
/**
* 给普通post请求添加公共参数,并且转换为json形式
* @param formBody
* @return
*/
private final RequestBody addParamsToFormBody(FormBody formBody){
int size=formBody.size();
Map<String,Object> mMap=new HashMap<>();
for (int i=0;i<size;i++){
mMap.put(formBody.name(i),formBody.value(i));
}
String strJson= HttpUtils.mapToJsonStr(mMap);
RequestBody body=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),strJson);
return body;
}
/**
* 添加get方式公共参数
* @param oldRequest
* @return
*/
private HttpUrl.Builder addGetCommonParams(Request oldRequest){
HttpUrl.Builder authorizedUrlBuilder=oldRequest.url().newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host());
//遍历参数,用于sign计算
int size=oldRequest.url().querySize();
Map<String,Object> mMap=new HashMap<>();
for (int i=0;i<size;i++){
mMap.put(oldRequest.url().queryParameterName(i),oldRequest.url().queryParameterValue(i));
}
//计算sign并添加
String sign=HttpUtils.getSignParam(mMap);
if (!TextUtils.isEmpty(sign)) {
authorizedUrlBuilder.addQueryParameter("sign", sign);
}
//添加公共参数
Map<String,Object> commonParams=HttpUtils.getCommonParams();
for (Map.Entry<String,Object> entry:commonParams.entrySet()){
authorizedUrlBuilder.addQueryParameter(entry.getKey(), entry.getValue()+"");
}
return authorizedUrlBuilder;
}
private void debugLog(Chain chain) {
if (BuildConfig.DEBUG) {
}
}
}
|
UTF-8
|
Java
| 3,810 |
java
|
CommonInterceptor.java
|
Java
|
[
{
"context": "tBody;\nimport okhttp3.Response;\n\n/**\n * Created by yas on 2017/11/30.\n * 封装公共参数\n */\n\npublic class Common",
"end": 478,
"score": 0.9988937377929688,
"start": 475,
"tag": "USERNAME",
"value": "yas"
}
] | null |
[] |
package com.beta.MoneyballMaster.http.utils;
import android.text.TextUtils;
import com.beta.MoneyballMaster.BuildConfig;
import com.beta.MoneyballMaster.utils.MyLog;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by yas on 2017/11/30.
* 封装公共参数
*/
public class CommonInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request oldRequest = chain.request();
// 新的请求
Request.Builder newBuilder = oldRequest.newBuilder();
if ("GET".equals(oldRequest.method())){
newBuilder.url(addGetCommonParams(oldRequest).build());
newBuilder.method(oldRequest.method(),oldRequest.body());
}else if ("POST".equals(oldRequest.method())){
RequestBody body=oldRequest.body();
if (body instanceof FormBody){
//不普通的post请求
FormBody formBody= (FormBody) body;
newBuilder.method(oldRequest.method(),addParamsToFormBody(formBody))
.url(oldRequest.url());
}else if (body instanceof MultipartBody){
//有文件上传的post请求
//公共参数在组织生成MultipartBody时已添加,此处无需再添加
// return chain.proceed(oldRequest);
}
}
// 新的请求
newBuilder.addHeader("Cookie", getCookie())
.build();
Response response = chain.proceed(newBuilder.build());
// if (BuildConfig.DEBUG) {
// MyLog.debug("---> " + response.body().string());
// }
return response;
}
/***
* cookie
* @return
*/
private final String getCookie(){
return "";
}
/**
* 给普通post请求添加公共参数,并且转换为json形式
* @param formBody
* @return
*/
private final RequestBody addParamsToFormBody(FormBody formBody){
int size=formBody.size();
Map<String,Object> mMap=new HashMap<>();
for (int i=0;i<size;i++){
mMap.put(formBody.name(i),formBody.value(i));
}
String strJson= HttpUtils.mapToJsonStr(mMap);
RequestBody body=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),strJson);
return body;
}
/**
* 添加get方式公共参数
* @param oldRequest
* @return
*/
private HttpUrl.Builder addGetCommonParams(Request oldRequest){
HttpUrl.Builder authorizedUrlBuilder=oldRequest.url().newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host());
//遍历参数,用于sign计算
int size=oldRequest.url().querySize();
Map<String,Object> mMap=new HashMap<>();
for (int i=0;i<size;i++){
mMap.put(oldRequest.url().queryParameterName(i),oldRequest.url().queryParameterValue(i));
}
//计算sign并添加
String sign=HttpUtils.getSignParam(mMap);
if (!TextUtils.isEmpty(sign)) {
authorizedUrlBuilder.addQueryParameter("sign", sign);
}
//添加公共参数
Map<String,Object> commonParams=HttpUtils.getCommonParams();
for (Map.Entry<String,Object> entry:commonParams.entrySet()){
authorizedUrlBuilder.addQueryParameter(entry.getKey(), entry.getValue()+"");
}
return authorizedUrlBuilder;
}
private void debugLog(Chain chain) {
if (BuildConfig.DEBUG) {
}
}
}
| 3,810 | 0.616086 | 0.610835 | 116 | 30.189655 | 24.389057 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517241 | false | false |
12
|
9fee5dff593b832e017ffe73c1ff7d01032d1502
| 35,442,070,169,097 |
dc6df22ede86f38234ce0a4c08e68a2008fcb0f2
|
/tools-json/src/main/java/com/wen/tools/json/util/JsonObject.java
|
0a6fd534affdc7f7145454980aa3a4173aa8b2b7
|
[] |
no_license
|
haha174/tools
|
https://github.com/haha174/tools
|
d18ddec2d36a8b55668b38bbd9a48e21abf03110
|
545dd08d9d0ea4fb8fb49266231949b081c22138
|
refs/heads/log_util
| 2022-10-27T00:03:48.330000 | 2020-05-25T08:23:48 | 2020-05-25T08:23:48 | 140,415,293 | 1 | 0 | null | false | 2019-03-07T06:02:58 | 2018-07-10T10:23:05 | 2019-02-17T11:24:39 | 2019-03-07T06:02:58 | 25 | 1 | 0 | 0 |
Java
| false | null |
package com.wen.tools.json.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
public final class JsonObject extends JSONObject {
private JsonObject() {
}
public static final JsonObject create() {
JsonObject jo = new JsonObject();
return jo;
}
public final JsonObject append(String jsonValue) {
Map m = JSON.parseObject(jsonValue, Map.class);
if (m != null) {
super.getInnerMap().putAll(m);
}
return this;
}
public final JsonObject append(JsonObject value) {
if (value != null) {
super.getInnerMap().putAll(value.toMap());
}
return this;
}
public JsonObject append(String key, String value) {
super.getInnerMap().put(key, value);
return this;
}
public JsonObject append(String key, Object value) {
super.getInnerMap().put(key, value);
return this;
}
public String getValue(String key) {
Object o = super.getInnerMap().get(key);
return o == null ? null : String.valueOf(o);
}
public <T> T getValue(String key, Class<T> ct) {
T o = (T)super.getInnerMap().get(key);
return o == null ? null : o;
}
public String toJson() {
return super.toJSONString();
}
public Map<String, Object> toMap() {
return super.getInnerMap();
}
@Override
public String toString() {
return this.toJson();
}
}
|
UTF-8
|
Java
| 1,524 |
java
|
JsonObject.java
|
Java
|
[] | null |
[] |
package com.wen.tools.json.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
public final class JsonObject extends JSONObject {
private JsonObject() {
}
public static final JsonObject create() {
JsonObject jo = new JsonObject();
return jo;
}
public final JsonObject append(String jsonValue) {
Map m = JSON.parseObject(jsonValue, Map.class);
if (m != null) {
super.getInnerMap().putAll(m);
}
return this;
}
public final JsonObject append(JsonObject value) {
if (value != null) {
super.getInnerMap().putAll(value.toMap());
}
return this;
}
public JsonObject append(String key, String value) {
super.getInnerMap().put(key, value);
return this;
}
public JsonObject append(String key, Object value) {
super.getInnerMap().put(key, value);
return this;
}
public String getValue(String key) {
Object o = super.getInnerMap().get(key);
return o == null ? null : String.valueOf(o);
}
public <T> T getValue(String key, Class<T> ct) {
T o = (T)super.getInnerMap().get(key);
return o == null ? null : o;
}
public String toJson() {
return super.toJSONString();
}
public Map<String, Object> toMap() {
return super.getInnerMap();
}
@Override
public String toString() {
return this.toJson();
}
}
| 1,524 | 0.587927 | 0.587927 | 70 | 20.771429 | 19.853155 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414286 | false | false |
12
|
8c645dbe7c56500587a0a2449256944b86ea774a
| 38,912,403,716,144 |
4fe8d527a27add9378a970ea0f3d9c8cc5833a21
|
/TestWrite.java
|
4557a2b2c4b0648cb5a3abbc177dc328511ebd15
|
[] |
no_license
|
adewawa/My_github
|
https://github.com/adewawa/My_github
|
90cb77ed1ae4da7d461622856821e6db0144310b
|
dbcee4c205af5423bdf92980eac7e6ba4a1ab01b
|
refs/heads/master
| 2016-09-05T15:17:47.537000 | 2013-11-07T09:00:15 | 2013-11-07T09:00:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class TestWrite implements Runnable{
SerialTest st = new SerialTest();
private MessagePool mp;
public MessagePool getMessagePool(){
return mp;
}
public void setMessagePool(MessagePool mpp){
mp=mpp;
}
public void run(){
while(true){
try{
st.initialize();
String msg = mp.getMessage();
System.out.println(msg);
output=serialPort.getOutputStream();
output.write(msg);
}catch(Exception ex){
System.err.println(ex.toString());
}
}
}
}
|
UTF-8
|
Java
| 615 |
java
|
TestWrite.java
|
Java
|
[] | null |
[] |
public class TestWrite implements Runnable{
SerialTest st = new SerialTest();
private MessagePool mp;
public MessagePool getMessagePool(){
return mp;
}
public void setMessagePool(MessagePool mpp){
mp=mpp;
}
public void run(){
while(true){
try{
st.initialize();
String msg = mp.getMessage();
System.out.println(msg);
output=serialPort.getOutputStream();
output.write(msg);
}catch(Exception ex){
System.err.println(ex.toString());
}
}
}
}
| 615 | 0.534959 | 0.534959 | 25 | 23.559999 | 20.203129 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.52 | false | false |
12
|
b3340af0d8712ed337ecd6a8cf760a4c2496f6a8
| 34,196,529,660,624 |
1150f16bf7f7391ed7e3d7e1b67c4897008be532
|
/resource/src/main/java/com/exc/street/light/resource/qo/SlLampDeviceHistoryQuery.java
|
fdbeb9764b3552c4d3ad55f2bbcc2906f6b5d822
|
[] |
no_license
|
dragonxu/street_light_yancheng
|
https://github.com/dragonxu/street_light_yancheng
|
e0c957214aae2ebbba2470438c16cd1f8bf600ec
|
5d0d4fd4af0eb6b54f7e1ecef9651a3b9208d7f7
|
refs/heads/master
| 2023-01-15T19:36:53.113000 | 2020-11-24T07:37:34 | 2020-11-24T07:37:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.exc.street.light.resource.qo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author Xiezhipeng
* @Description 历史策略下的设备查询类
* @Date 2020/10/23
*/
@Data
public class SlLampDeviceHistoryQuery {
@ApiModelProperty(name = "createTime" , value = "创建时间")
private String createTime;
@ApiModelProperty(name = "strategyId" , value = "策略ID")
private Integer strategyId;
@ApiModelProperty(name = "isSuccess" , value = "2:失败 3:成功")
private Integer isSuccess;
}
|
UTF-8
|
Java
| 564 |
java
|
SlLampDeviceHistoryQuery.java
|
Java
|
[
{
"context": "ModelProperty;\nimport lombok.Data;\n\n/**\n * @author Xiezhipeng\n * @Description 历史策略下的设备查询类\n * @Date 2020/10/23\n ",
"end": 137,
"score": 0.9321039319038391,
"start": 127,
"tag": "NAME",
"value": "Xiezhipeng"
}
] | null |
[] |
package com.exc.street.light.resource.qo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author Xiezhipeng
* @Description 历史策略下的设备查询类
* @Date 2020/10/23
*/
@Data
public class SlLampDeviceHistoryQuery {
@ApiModelProperty(name = "createTime" , value = "创建时间")
private String createTime;
@ApiModelProperty(name = "strategyId" , value = "策略ID")
private Integer strategyId;
@ApiModelProperty(name = "isSuccess" , value = "2:失败 3:成功")
private Integer isSuccess;
}
| 564 | 0.709615 | 0.690385 | 23 | 21.608696 | 21.161366 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false |
12
|
0fc9f9de12c917b7f4d2d229e8e51f1a5ff1d29d
| 25,537,875,596,453 |
dcdb42b41e1b1cdff77fc09dd3e8dee65f7f94da
|
/cdi/src/main/java/net/gcolin/di/cdi/internal/Selector.java
|
7bc1a34e1db7c1e959a09bbd6e9a76e0f62b20d5
|
[
"Apache-2.0"
] |
permissive
|
gcolin/juikito
|
https://github.com/gcolin/juikito
|
aee63e672495bd1723351f9923b90e7ae63ef070
|
0575c723f60dd8c500903271d3e91e34580662de
|
refs/heads/master
| 2020-05-21T16:32:06.347000 | 2017-08-15T16:31:55 | 2017-08-15T16:31:55 | 41,266,107 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | 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 net.gcolin.di.cdi.internal;
import net.gcolin.common.reflect.Reflect;
import net.gcolin.di.cdi.internal.model.BeanAttributesImpl;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.New;
import javax.enterprise.inject.spi.BeanAttributes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.util.TypeLiteral;
import javax.inject.Named;
/**
* A class for selecting objects.
*
* @author Gaël COLIN
* @since 1.0
* @see Selectable
*/
public class Selector {
private static enum Result {
YES, NO, MAYBE
}
private Function<Selectable, Result> accept;
private static Result of(boolean bool) {
return bool ? Result.YES : Result.NO;
}
/**
* Filter by qualifiers.
*
* @param qall qualifiers
* @param bm bean manager
* @return a new Selector
*/
public static Selector qualiferSelector(final Annotation[] qall, BeanManager bm) {
return qualiferSelector0(qall, bm, false);
}
/**
* Filter by qualifiers in an injection point.
*
* @param qall qualifiers
* @param bm bean manager
* @return a new Selector
*/
public static Selector qualiferSelectorInjectPoint(final Annotation[] qall, BeanManager bm) {
return qualiferSelector0(qall, bm, true);
}
/**
* Filter by qualifiers in an injection point.
*
* @param qall qualifiers
* @param bm bean manager
* @param ij is injectpoint
* @return a new Selector
*/
public static Selector qualiferSelector0(final Annotation[] qall, BeanManager bm, boolean ij) {
Annotation[] qualifiers = buildQualifiers(qall, ij);
Selector selector = new Selector();
selector.accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
Set<Annotation> allQualifiers = new HashSet<>(selectable.getSelectableQualifiers());
boolean found = true;
for (int i = 0; found && i < qualifiers.length; i++) {
found = false;
Annotation fa = null;
for (Annotation a : allQualifiers) {
if (checkNamed(a, qualifiers[i], selectable)
|| bm.areQualifiersEquivalent(a, qualifiers[i])) {
found = true;
fa = a;
break;
}
}
allQualifiers.remove(fa);
}
if (found && !allQualifiers.isEmpty() && !selectable.isSpecialized()) {
Annotation annotation = allQualifiers.iterator().next();
if (annotation.annotationType() != Named.class) {
return ij ? Result.MAYBE : Result.NO;
}
}
return of(found);
}
};
return selector;
}
private static Annotation[] buildQualifiers(final Annotation[] qall, boolean ij) {
List<Annotation> list = new ArrayList<>();
for (int i = 0; i < qall.length; i++) {
list.add(qall[i]);
}
if (qall.length == 0 || !ij && qall.length == 1 && qall[0].annotationType() == Named.class) {
list.add(BeanAttributesImpl.DEFAULT);
}
if (!Reflect.hasAnnotation(qall, New.class) && !Reflect.hasAnnotation(qall, Any.class)) {
list.add(BeanAttributesImpl.ANY);
}
return list.toArray(new Annotation[list.size()]);
}
protected static boolean checkNamed(Annotation a1, Annotation a2, Selectable selectable) {
if (a2.annotationType() != Named.class || a1.annotationType() != Named.class) {
return false;
}
Named an = (Named) a1;
String aname = an.value();
Named bn = (Named) a2;
if (aname.isEmpty() && selectable instanceof BeanAttributes) {
aname = ((BeanAttributes<?>) selectable).getName();
}
return bn.value().equals(aname);
}
/**
* Filter by qualifiers exclusive.
*
* @param qall qualifiers
* @param bm bean manager
* @return a new Selector
*/
public static Selector qualiferSelectorExclusive(final Annotation[] qall, BeanManager bm) {
Annotation[] qualifiers = buildQualifiers(qall, false);
Selector selector = new Selector();
selector.accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
if (selectable.getSelectableQualifiers().size() != qualifiers.length) {
return Result.NO;
}
boolean found = true;
for (int i = 0; found && i < qualifiers.length; i++) {
found = false;
for (Annotation a : selectable.getSelectableQualifiers()) {
if (checkNamed(a, qualifiers[i], selectable)
|| bm.areQualifiersEquivalent(a, qualifiers[i])) {
found = true;
break;
}
}
}
return of(found);
}
};
return selector;
}
/**
* Filter by generic types.
*
* @param types generic types
* @return a Selector
*/
public Selector and(final Set<Type> types) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(
selectable.getTypes().containsAll(types) && qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Filter by generic type.
*
* @param type a generic type
* @return a Selector
*/
public Selector and(final Type type) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(
selectable.getTypes().contains(type) && qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Filter by TypeLiteral.
*
* @param type a TypeLiteral
* @param <T> the type of class
* @return a Selector
*/
public <T> Selector and(final TypeLiteral<T> type) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(selectable.getTypes().contains(type.getType())
&& qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Filter by class.
*
* @param type a class
* @return a Selector
*/
public Selector andAccept(final Class<?> type) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(selectable.getType().isAssignableFrom(type)
&& qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Do the selection.
*
* @param possibles all possible beans
* @param <T> the type of selectable
* @return selected beans as a list
*/
public <T extends Selectable> List<T> asList(List<T> possibles) {
List<T> list = null;
List<T> maybe = null;
for (int i = 0, l = possibles.size(); i < l; i++) {
T possible = possibles.get(i);
Result bool = accept.apply(possible);
if (bool == Result.MAYBE) {
if (maybe == null) {
maybe = new ArrayList<>();
}
maybe.add(possible);
} else if (bool == Result.YES) {
if (list == null) {
list = new ArrayList<>();
}
list.add(possible);
}
}
return list == null ? (maybe == null ? Collections.emptyList() : maybe) : list;
}
/**
* Do the selection.
*
* @param possibles all possible beans
* @param <T> the type of selectable
* @return selected beans as a set
*/
public <T extends Selectable> Set<T> asSet(List<T> possibles) {
Set<T> list = null;
Set<T> maybe = null;
for (int i = 0, l = possibles.size(); i < l; i++) {
T possible = possibles.get(i);
Result bool = accept.apply(possible);
if (bool == Result.MAYBE) {
if (maybe == null) {
maybe = new HashSet<>();
}
maybe.add(possible);
} else if (bool == Result.YES) {
if (list == null) {
list = new HashSet<>();
}
list.add(possible);
}
}
return list == null ? (maybe == null ? Collections.emptySet() : maybe) : list;
}
/**
* Do the selection.
*
* @param possibles all possible beans
* @param <T> the type of selectable
* @return selected beans as a set
*/
public <T extends Selectable> Set<T> asSet(Set<T> possibles) {
Set<T> list = null;
Set<T> maybe = null;
for (T possible : possibles) {
Result bool = accept.apply(possible);
if (bool == Result.MAYBE) {
if (maybe == null) {
maybe = new HashSet<>();
}
maybe.add(possible);
} else if (bool == Result.YES) {
if (list == null) {
list = new HashSet<>();
}
list.add(possible);
}
}
return list == null ? (maybe == null ? Collections.emptySet() : maybe) : list;
}
}
|
UTF-8
|
Java
| 10,386 |
java
|
Selector.java
|
Java
|
[
{
"context": " * A class for selecting objects.\r\n * \r\n * @author Gaël COLIN\r\n * @since 1.0\r\n * @see Selectable\r\n */\r\npublic c",
"end": 1511,
"score": 0.9998515844345093,
"start": 1501,
"tag": "NAME",
"value": "Gaël COLIN"
}
] | 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 net.gcolin.di.cdi.internal;
import net.gcolin.common.reflect.Reflect;
import net.gcolin.di.cdi.internal.model.BeanAttributesImpl;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.New;
import javax.enterprise.inject.spi.BeanAttributes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.util.TypeLiteral;
import javax.inject.Named;
/**
* A class for selecting objects.
*
* @author <NAME>
* @since 1.0
* @see Selectable
*/
public class Selector {
private static enum Result {
YES, NO, MAYBE
}
private Function<Selectable, Result> accept;
private static Result of(boolean bool) {
return bool ? Result.YES : Result.NO;
}
/**
* Filter by qualifiers.
*
* @param qall qualifiers
* @param bm bean manager
* @return a new Selector
*/
public static Selector qualiferSelector(final Annotation[] qall, BeanManager bm) {
return qualiferSelector0(qall, bm, false);
}
/**
* Filter by qualifiers in an injection point.
*
* @param qall qualifiers
* @param bm bean manager
* @return a new Selector
*/
public static Selector qualiferSelectorInjectPoint(final Annotation[] qall, BeanManager bm) {
return qualiferSelector0(qall, bm, true);
}
/**
* Filter by qualifiers in an injection point.
*
* @param qall qualifiers
* @param bm bean manager
* @param ij is injectpoint
* @return a new Selector
*/
public static Selector qualiferSelector0(final Annotation[] qall, BeanManager bm, boolean ij) {
Annotation[] qualifiers = buildQualifiers(qall, ij);
Selector selector = new Selector();
selector.accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
Set<Annotation> allQualifiers = new HashSet<>(selectable.getSelectableQualifiers());
boolean found = true;
for (int i = 0; found && i < qualifiers.length; i++) {
found = false;
Annotation fa = null;
for (Annotation a : allQualifiers) {
if (checkNamed(a, qualifiers[i], selectable)
|| bm.areQualifiersEquivalent(a, qualifiers[i])) {
found = true;
fa = a;
break;
}
}
allQualifiers.remove(fa);
}
if (found && !allQualifiers.isEmpty() && !selectable.isSpecialized()) {
Annotation annotation = allQualifiers.iterator().next();
if (annotation.annotationType() != Named.class) {
return ij ? Result.MAYBE : Result.NO;
}
}
return of(found);
}
};
return selector;
}
private static Annotation[] buildQualifiers(final Annotation[] qall, boolean ij) {
List<Annotation> list = new ArrayList<>();
for (int i = 0; i < qall.length; i++) {
list.add(qall[i]);
}
if (qall.length == 0 || !ij && qall.length == 1 && qall[0].annotationType() == Named.class) {
list.add(BeanAttributesImpl.DEFAULT);
}
if (!Reflect.hasAnnotation(qall, New.class) && !Reflect.hasAnnotation(qall, Any.class)) {
list.add(BeanAttributesImpl.ANY);
}
return list.toArray(new Annotation[list.size()]);
}
protected static boolean checkNamed(Annotation a1, Annotation a2, Selectable selectable) {
if (a2.annotationType() != Named.class || a1.annotationType() != Named.class) {
return false;
}
Named an = (Named) a1;
String aname = an.value();
Named bn = (Named) a2;
if (aname.isEmpty() && selectable instanceof BeanAttributes) {
aname = ((BeanAttributes<?>) selectable).getName();
}
return bn.value().equals(aname);
}
/**
* Filter by qualifiers exclusive.
*
* @param qall qualifiers
* @param bm bean manager
* @return a new Selector
*/
public static Selector qualiferSelectorExclusive(final Annotation[] qall, BeanManager bm) {
Annotation[] qualifiers = buildQualifiers(qall, false);
Selector selector = new Selector();
selector.accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
if (selectable.getSelectableQualifiers().size() != qualifiers.length) {
return Result.NO;
}
boolean found = true;
for (int i = 0; found && i < qualifiers.length; i++) {
found = false;
for (Annotation a : selectable.getSelectableQualifiers()) {
if (checkNamed(a, qualifiers[i], selectable)
|| bm.areQualifiersEquivalent(a, qualifiers[i])) {
found = true;
break;
}
}
}
return of(found);
}
};
return selector;
}
/**
* Filter by generic types.
*
* @param types generic types
* @return a Selector
*/
public Selector and(final Set<Type> types) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(
selectable.getTypes().containsAll(types) && qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Filter by generic type.
*
* @param type a generic type
* @return a Selector
*/
public Selector and(final Type type) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(
selectable.getTypes().contains(type) && qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Filter by TypeLiteral.
*
* @param type a TypeLiteral
* @param <T> the type of class
* @return a Selector
*/
public <T> Selector and(final TypeLiteral<T> type) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(selectable.getTypes().contains(type.getType())
&& qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Filter by class.
*
* @param type a class
* @return a Selector
*/
public Selector andAccept(final Class<?> type) {
final Function<Selectable, Result> qualifier = accept;
accept = new Function<Selectable, Result>() {
@Override
public Result apply(Selectable selectable) {
return of(selectable.getType().isAssignableFrom(type)
&& qualifier.apply(selectable) == Result.YES);
}
};
return this;
}
/**
* Do the selection.
*
* @param possibles all possible beans
* @param <T> the type of selectable
* @return selected beans as a list
*/
public <T extends Selectable> List<T> asList(List<T> possibles) {
List<T> list = null;
List<T> maybe = null;
for (int i = 0, l = possibles.size(); i < l; i++) {
T possible = possibles.get(i);
Result bool = accept.apply(possible);
if (bool == Result.MAYBE) {
if (maybe == null) {
maybe = new ArrayList<>();
}
maybe.add(possible);
} else if (bool == Result.YES) {
if (list == null) {
list = new ArrayList<>();
}
list.add(possible);
}
}
return list == null ? (maybe == null ? Collections.emptyList() : maybe) : list;
}
/**
* Do the selection.
*
* @param possibles all possible beans
* @param <T> the type of selectable
* @return selected beans as a set
*/
public <T extends Selectable> Set<T> asSet(List<T> possibles) {
Set<T> list = null;
Set<T> maybe = null;
for (int i = 0, l = possibles.size(); i < l; i++) {
T possible = possibles.get(i);
Result bool = accept.apply(possible);
if (bool == Result.MAYBE) {
if (maybe == null) {
maybe = new HashSet<>();
}
maybe.add(possible);
} else if (bool == Result.YES) {
if (list == null) {
list = new HashSet<>();
}
list.add(possible);
}
}
return list == null ? (maybe == null ? Collections.emptySet() : maybe) : list;
}
/**
* Do the selection.
*
* @param possibles all possible beans
* @param <T> the type of selectable
* @return selected beans as a set
*/
public <T extends Selectable> Set<T> asSet(Set<T> possibles) {
Set<T> list = null;
Set<T> maybe = null;
for (T possible : possibles) {
Result bool = accept.apply(possible);
if (bool == Result.MAYBE) {
if (maybe == null) {
maybe = new HashSet<>();
}
maybe.add(possible);
} else if (bool == Result.YES) {
if (list == null) {
list = new HashSet<>();
}
list.add(possible);
}
}
return list == null ? (maybe == null ? Collections.emptySet() : maybe) : list;
}
}
| 10,381 | 0.593741 | 0.591526 | 347 | 27.927954 | 25.295784 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458213 | false | false |
12
|
59aa2ec94c7573eaca5df720ad0c2a04e9bc9d18
| 25,537,875,597,882 |
1214efc511261f910d8497e0edbdf6a60a007714
|
/proinClient/src/main/java/com/spring/services/AccountService.java
|
3bfb305f959c039c8d147c01dd0e4ec02eaa656b
|
[] |
no_license
|
SushantKhanal/Proin-Project
|
https://github.com/SushantKhanal/Proin-Project
|
5d078de7535d733ac48d65418478115903131507
|
741cfef7868dc5ebab62c0b8c765fd1f4c19d19b
|
refs/heads/master
| 2021-01-24T04:01:27.268000 | 2018-04-19T12:53:58 | 2018-04-19T12:53:58 | 122,914,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.spring.services;
import com.spring.model.*;
import com.spring.responseDto.UserDocInfo;
import java.util.List;
public interface AccountService {
void updateUser(User p);
User getUserById(Long id); //while updating user
void addProfilePic(UserProfilePic u_p);
UserProfilePic getUserPpByUsername(String username);
void addUserTags(UserTags userTags1);
UserTags getUserTagsByUsername(String username);
void addUserExperience(UserExperience userExperience1);
List<UserExperience> getUserExperienceByUsername(String username);
List<UserAcademics> getUserAcademicsByUsername(String username);
UserAcademics getUserAcademicsFromId(Long id);
UserExperience getExperienceFromId(Long id);
void addUserAcademics(UserAcademics userAcademics);
void deleteThisAcademics(Long id);
void deleteThisExperience(Long id);
List<NormalFollowRequest> checkFollowRequests(String username);
void approveFollowRequest(Long id);
void ignoreFollowRequest(Long id);
List<NormalFollowRequest> getIgnoredRequests();
void saveUserDoc(UserDocuments userDocuments);
List<UserDocInfo> checkForUploadedDocs(String username);
void deleteDocument(Long id);
}
|
UTF-8
|
Java
| 1,240 |
java
|
AccountService.java
|
Java
|
[] | null |
[] |
package com.spring.services;
import com.spring.model.*;
import com.spring.responseDto.UserDocInfo;
import java.util.List;
public interface AccountService {
void updateUser(User p);
User getUserById(Long id); //while updating user
void addProfilePic(UserProfilePic u_p);
UserProfilePic getUserPpByUsername(String username);
void addUserTags(UserTags userTags1);
UserTags getUserTagsByUsername(String username);
void addUserExperience(UserExperience userExperience1);
List<UserExperience> getUserExperienceByUsername(String username);
List<UserAcademics> getUserAcademicsByUsername(String username);
UserAcademics getUserAcademicsFromId(Long id);
UserExperience getExperienceFromId(Long id);
void addUserAcademics(UserAcademics userAcademics);
void deleteThisAcademics(Long id);
void deleteThisExperience(Long id);
List<NormalFollowRequest> checkFollowRequests(String username);
void approveFollowRequest(Long id);
void ignoreFollowRequest(Long id);
List<NormalFollowRequest> getIgnoredRequests();
void saveUserDoc(UserDocuments userDocuments);
List<UserDocInfo> checkForUploadedDocs(String username);
void deleteDocument(Long id);
}
| 1,240 | 0.775 | 0.773387 | 51 | 23.313726 | 24.646114 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false |
12
|
8b7eb417c133c153bb3729e1ac7d24be4bdae769
| 6,846,177,925,551 |
20b63c02af2974be430e58d7db193e24cbc17df3
|
/U8 - XML. Generar XML a partir de objetos. Analizar y Generar XML con SAX y DOM/U8_T2_Modificando_DOM/ModificarDOM.java
|
5fa2babd632a1a8e43e5f47fc1a1d0fda9b90b77
|
[] |
no_license
|
cmanzanop/Programacion_DAW
|
https://github.com/cmanzanop/Programacion_DAW
|
5e78a520b93ab7531eacb26f1c45a49430f28e9b
|
c743ff54fd2a85e53961656f957e8a00c2102de0
|
refs/heads/master
| 2020-07-29T13:10:24.803000 | 2020-05-26T16:56:52 | 2020-05-26T16:56:52 | 209,006,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package entregableT2;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ModificarDOM {
public static void main(String[] args) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Cargar el contenido del XML en la estructura DOM
Document doc = db.parse(new File("libros.xml"));
Node root = doc.getDocumentElement();
NodeList nl = doc.getElementsByTagName("libro");
// Añadir un comentario antes de cada nodo hijo de tipo etiqueta
Comment [] comentario = new Comment[nl.getLength()];
for (int i = 0; i < nl.getLength(); i++) {
comentario[i] = doc.createComment("COMENTARIO AÑADIDO DESDE DOM");
Element nodoHijo = (Element) doc.getElementsByTagName("libro").item(i);
root.insertBefore(comentario[i],nodoHijo);
}
// Creo una nueva etiqueta hija
Element libro = doc.createElement("libro");
libro.setAttribute("id","6");
//Creo la etiqueta hija titulo y le doy valor
Element titulo = doc.createElement("titulo");
titulo.setTextContent("El Conde de Montecristo");
//Creo la etiqueta hija autor y le doy valor
Element autor = doc.createElement("autor");
autor.setTextContent("Alexandre Dumas");
//Creo la etiqueta hija paginas y le doy valor
Element paginas = doc.createElement("paginas");
paginas.setTextContent("1144");
//Construyo toda la estructura general de la etiqueta
libro.appendChild(titulo);
libro.appendChild(autor);
libro.appendChild(paginas);
//Añadimos ese nuevo nodo al root, se añadirá el último
root.appendChild(libro);
// Creo un nuevo nodo libro
Element libroNuevo = doc.createElement("libro");
libroNuevo.setAttribute("id","1");
//Creo la etiqueta hija titulo y le doy valor
Element tituloNuevo = doc.createElement("titulo");
tituloNuevo.setTextContent("Nunca te pares");
//Creo la etiqueta hija autor y le doy valor
Element autorNuevo = doc.createElement("autor");
autorNuevo.setTextContent("Phil Knight");
//Creo la etiqueta hija paginas y le doy valor
Element paginasNuevo = doc.createElement("paginas");
paginasNuevo.setTextContent("338");
//Construyo toda la estructura general de la etiqueta
libroNuevo.appendChild(tituloNuevo);
libroNuevo.appendChild(autorNuevo);
libroNuevo.appendChild(paginasNuevo);
// Consigo la primera etiqueta hija para poder reemplezarla
Element primerLibro = (Element) doc.getElementsByTagName("libro").item(0);
// Reemplazo la nueva etiqueta creada por la primera
root.replaceChild(libroNuevo,primerLibro);
// PROCEDEMOS A VOLCAR TODAS LAS MODIFICACIONES, TODO EL ÁRBOL A UN NUEVO FICHERO
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
t.transform(new DOMSource(doc),new StreamResult(new FileOutputStream("dom_modificado.xml")));
//Creación del origen DOMSource
DOMSource origenDOM = new DOMSource(root);
//Creación del fichero que va a ser mi destino
File nuevoLibro = new File("dom_modificado.xml");
StreamResult destino = new StreamResult(nuevoLibro);
//Hacemos la transformación que en nuestro caso es la escritura
t.transform(origenDOM,destino);
} catch (ParserConfigurationException | IOException | SAXException
| TransformerException e) {
System.out.println(e.getStackTrace());
}
}
}
|
UTF-8
|
Java
| 4,626 |
java
|
ModificarDOM.java
|
Java
|
[
{
"context": "ement(\"autor\");\n autor.setTextContent(\"Alexandre Dumas\");\n\n //Creo la etiqueta hija paginas y",
"end": 1967,
"score": 0.9998656511306763,
"start": 1952,
"tag": "NAME",
"value": "Alexandre Dumas"
},
{
"context": "(\"autor\");\n autorNuevo.setTextContent(\"Phil Knight\");\n\n //Creo la etiqueta hija paginas y",
"end": 2923,
"score": 0.9998676180839539,
"start": 2912,
"tag": "NAME",
"value": "Phil Knight"
}
] | null |
[] |
package entregableT2;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ModificarDOM {
public static void main(String[] args) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Cargar el contenido del XML en la estructura DOM
Document doc = db.parse(new File("libros.xml"));
Node root = doc.getDocumentElement();
NodeList nl = doc.getElementsByTagName("libro");
// Añadir un comentario antes de cada nodo hijo de tipo etiqueta
Comment [] comentario = new Comment[nl.getLength()];
for (int i = 0; i < nl.getLength(); i++) {
comentario[i] = doc.createComment("COMENTARIO AÑADIDO DESDE DOM");
Element nodoHijo = (Element) doc.getElementsByTagName("libro").item(i);
root.insertBefore(comentario[i],nodoHijo);
}
// Creo una nueva etiqueta hija
Element libro = doc.createElement("libro");
libro.setAttribute("id","6");
//Creo la etiqueta hija titulo y le doy valor
Element titulo = doc.createElement("titulo");
titulo.setTextContent("El Conde de Montecristo");
//Creo la etiqueta hija autor y le doy valor
Element autor = doc.createElement("autor");
autor.setTextContent("<NAME>");
//Creo la etiqueta hija paginas y le doy valor
Element paginas = doc.createElement("paginas");
paginas.setTextContent("1144");
//Construyo toda la estructura general de la etiqueta
libro.appendChild(titulo);
libro.appendChild(autor);
libro.appendChild(paginas);
//Añadimos ese nuevo nodo al root, se añadirá el último
root.appendChild(libro);
// Creo un nuevo nodo libro
Element libroNuevo = doc.createElement("libro");
libroNuevo.setAttribute("id","1");
//Creo la etiqueta hija titulo y le doy valor
Element tituloNuevo = doc.createElement("titulo");
tituloNuevo.setTextContent("Nunca te pares");
//Creo la etiqueta hija autor y le doy valor
Element autorNuevo = doc.createElement("autor");
autorNuevo.setTextContent("<NAME>");
//Creo la etiqueta hija paginas y le doy valor
Element paginasNuevo = doc.createElement("paginas");
paginasNuevo.setTextContent("338");
//Construyo toda la estructura general de la etiqueta
libroNuevo.appendChild(tituloNuevo);
libroNuevo.appendChild(autorNuevo);
libroNuevo.appendChild(paginasNuevo);
// Consigo la primera etiqueta hija para poder reemplezarla
Element primerLibro = (Element) doc.getElementsByTagName("libro").item(0);
// Reemplazo la nueva etiqueta creada por la primera
root.replaceChild(libroNuevo,primerLibro);
// PROCEDEMOS A VOLCAR TODAS LAS MODIFICACIONES, TODO EL ÁRBOL A UN NUEVO FICHERO
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
t.transform(new DOMSource(doc),new StreamResult(new FileOutputStream("dom_modificado.xml")));
//Creación del origen DOMSource
DOMSource origenDOM = new DOMSource(root);
//Creación del fichero que va a ser mi destino
File nuevoLibro = new File("dom_modificado.xml");
StreamResult destino = new StreamResult(nuevoLibro);
//Hacemos la transformación que en nuestro caso es la escritura
t.transform(origenDOM,destino);
} catch (ParserConfigurationException | IOException | SAXException
| TransformerException e) {
System.out.println(e.getStackTrace());
}
}
}
| 4,612 | 0.642331 | 0.639298 | 117 | 38.452991 | 27.882076 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.623932 | false | false |
12
|
078447148072131fc882ce815a2586b48bc2093a
| 7,533,372,678,809 |
6d30d17e92f7281048df6b0a8d0c2dcb27a2f3cb
|
/src/main/java/com/shop/online/model/Product.java
|
291ccf6b92c3320dce31128ac4c521170a4acb77
|
[] |
no_license
|
AbandondR/shoponline
|
https://github.com/AbandondR/shoponline
|
8d85c0dfd1850c9d063a8d9a59e369dbd6f6c091
|
cf31a3d9e7b3cb95a7666904bdbb01a13ca4bbdc
|
refs/heads/master
| 2022-12-20T19:24:19.462000 | 2019-11-20T02:46:20 | 2019-11-20T02:46:20 | 205,847,553 | 0 | 0 | null | false | 2022-12-15T23:41:48 | 2019-09-02T12:00:15 | 2019-11-20T02:46:23 | 2022-12-15T23:41:45 | 8,586 | 0 | 0 | 8 |
CSS
| false | false |
package com.shop.online.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
*
* 商品表
* @author yjh
* @version V1.0 创建时间:2019-03-01
* Copyright 2018 by Myself
*
*/
@Data
@Table(name = "product")
@Entity
@ApiModel(value="Product对象", description="商品表")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "ID", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "产品编号", name="id", example = "", required = false)
@Id
private String id;
@Column(name = "product_name", columnDefinition = "varchar(255)" )
@ApiModelProperty(value = "产品名称", name="productName", example = "", required = false)
private String productName;
@Column(name = "brand_id", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "品牌ID", name="brandId", example = "", required = false)
private String brandId;
@Column(name = "cata_id", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "分类ID", name="cataId", example = "", required = false)
private String cataId;
@Column(name="sale_totalNum", columnDefinition = "varchar(20)")
@ApiModelProperty(value = "该商品总销量(所有sku销量之和)", name="saleTotalNum", example = "", required = false)
private String saleTotalNum;
@Column(name="total_stock", columnDefinition = "varchar(20)")
@ApiModelProperty(value = "该商品总库存(所有sku库存之和)", name="totalStock", example = "", required = false)
private String totalStock;
@Column(name = "create_time", columnDefinition = "datetime" )
@ApiModelProperty(value = "创建时间", name="createTime", example = "", required = false)
private Date createTime;
@Column(name = "product_num", columnDefinition = "varchar(36)" )
@ApiModelProperty(value = "商品编号", name="productNum", example = "", required = false)
private String productNum;
@Column(name = "status", columnDefinition = "varchar(2)" )
@ApiModelProperty(value = "状态(是否上架?)", name="status", example = "", required = false)
private String status;
@Column(name = "price_list_id", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "价格列表", name="priceListId", example = "", required = false)
private String priceListId;
@Column(name="description", columnDefinition = "varchar(500)")
@ApiModelProperty(value = "商品描述", name="priceListId", example = "", required = false)
private String description;
@Column(name = "picture_snapshot", columnDefinition = "varchar(255)" )
@ApiModelProperty(value = "图片快照地址(浏览商品时的显示图片)", name="pictureSnapshot", example = "", required = false)
private String pictureSnapshot;
}
|
UTF-8
|
Java
| 3,092 |
java
|
Product.java
|
Java
|
[
{
"context": "\nimport java.util.Date;\n\n/**\n * \n * 商品表\n * @author yjh\n * @version V1.0 创建时间:2019-03-01\n * Copy",
"end": 350,
"score": 0.9996486902236938,
"start": 347,
"tag": "USERNAME",
"value": "yjh"
},
{
"context": "V1.0 创建时间:2019-03-01\n * Copyright 2018 by Myself\n *\n */\n@Data\n@Table(name = \"product\")\n@Entity\n@Ap",
"end": 420,
"score": 0.8985400199890137,
"start": 414,
"tag": "USERNAME",
"value": "Myself"
}
] | null |
[] |
package com.shop.online.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
*
* 商品表
* @author yjh
* @version V1.0 创建时间:2019-03-01
* Copyright 2018 by Myself
*
*/
@Data
@Table(name = "product")
@Entity
@ApiModel(value="Product对象", description="商品表")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "ID", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "产品编号", name="id", example = "", required = false)
@Id
private String id;
@Column(name = "product_name", columnDefinition = "varchar(255)" )
@ApiModelProperty(value = "产品名称", name="productName", example = "", required = false)
private String productName;
@Column(name = "brand_id", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "品牌ID", name="brandId", example = "", required = false)
private String brandId;
@Column(name = "cata_id", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "分类ID", name="cataId", example = "", required = false)
private String cataId;
@Column(name="sale_totalNum", columnDefinition = "varchar(20)")
@ApiModelProperty(value = "该商品总销量(所有sku销量之和)", name="saleTotalNum", example = "", required = false)
private String saleTotalNum;
@Column(name="total_stock", columnDefinition = "varchar(20)")
@ApiModelProperty(value = "该商品总库存(所有sku库存之和)", name="totalStock", example = "", required = false)
private String totalStock;
@Column(name = "create_time", columnDefinition = "datetime" )
@ApiModelProperty(value = "创建时间", name="createTime", example = "", required = false)
private Date createTime;
@Column(name = "product_num", columnDefinition = "varchar(36)" )
@ApiModelProperty(value = "商品编号", name="productNum", example = "", required = false)
private String productNum;
@Column(name = "status", columnDefinition = "varchar(2)" )
@ApiModelProperty(value = "状态(是否上架?)", name="status", example = "", required = false)
private String status;
@Column(name = "price_list_id", columnDefinition = "varchar(50)" )
@ApiModelProperty(value = "价格列表", name="priceListId", example = "", required = false)
private String priceListId;
@Column(name="description", columnDefinition = "varchar(500)")
@ApiModelProperty(value = "商品描述", name="priceListId", example = "", required = false)
private String description;
@Column(name = "picture_snapshot", columnDefinition = "varchar(255)" )
@ApiModelProperty(value = "图片快照地址(浏览商品时的显示图片)", name="pictureSnapshot", example = "", required = false)
private String pictureSnapshot;
}
| 3,092 | 0.686726 | 0.673315 | 77 | 36.779221 | 32.119755 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.935065 | false | false |
12
|
8eca083462dfeacc76a672ce4a362b561275c742
| 5,841,155,541,011 |
63265bf5315f175f54e4c3c3feb4abcb0f5b60f8
|
/src/main/java/com/BossPyroski/languages/controllers/LanguageController.java
|
27a4a23b37af4c12ae9badb65758c96585492318
|
[] |
no_license
|
BossPyroski/languages
|
https://github.com/BossPyroski/languages
|
cb7f1c7d4212a4cfae2807cec5378a984bbfbb05
|
dc378bc28123e41b707bc0447e488fb097bf9151
|
refs/heads/main
| 2023-04-11T15:49:06.731000 | 2021-04-23T20:24:27 | 2021-04-23T20:24:27 | 360,997,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.BossPyroski.languages.controllers;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.BossPyroski.languages.Services.LanguageService;
import com.BossPyroski.languages.models.Language;
@Controller
public class LanguageController {
private final LanguageService langServ;
public LanguageController(LanguageService langServ) {
this.langServ = langServ;
}
@RequestMapping("/languages")
public String home (Model model, @ModelAttribute("language") Language language) {
this.langServ.allLangs();
model.addAttribute("allLang", this.langServ.allLangs());
return "index.jsp";
}
@PostMapping("/languages")
public String createLang(@Valid @ModelAttribute("language") Language language, BindingResult result, Model model) {
if(result.hasErrors()) {
model.addAttribute("allLang", this.langServ.allLangs());
return "index.jsp";
}else {
this.langServ.createLang(language);
return "redirect:/languages";
}
}
@RequestMapping("/languages/edit/{id}")
public String editLang(@PathVariable("id")Long id, Model model) {
Language lang = this.langServ.getLang(id);
model.addAttribute("language", lang);
return "edit.jsp";
}
@PostMapping("/languages/{id}/update")
public String updateLang(@Valid @ModelAttribute("language") Language language, BindingResult result) {
if(result.hasErrors()) {
return "edit.jsp";
} else {
this.langServ.updateLang(language);
return "redirect:/languages";
}
}
@GetMapping(value="/languages/{id}/delete")
public String destroy(@PathVariable("id") Long id) {
this.langServ.deleteLang(id);
return "redirect:/languages";
}
}
//@RequestMapping("/books/new")
//public String newBook(@ModelAttribute("book") Book book) {
// return "/books/new.jsp";
//}
//@RequestMapping(value="/books", method=RequestMethod.POST)
//public String create(@Valid @ModelAttribute("book") Book book, BindingResult result) {
// if (result.hasErrors()) {
// return "/books/new.jsp";
// } else {
// bookService.createBook(book);
// return "redirect:/books";
// }
|
UTF-8
|
Java
| 2,515 |
java
|
LanguageController.java
|
Java
|
[] | null |
[] |
package com.BossPyroski.languages.controllers;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.BossPyroski.languages.Services.LanguageService;
import com.BossPyroski.languages.models.Language;
@Controller
public class LanguageController {
private final LanguageService langServ;
public LanguageController(LanguageService langServ) {
this.langServ = langServ;
}
@RequestMapping("/languages")
public String home (Model model, @ModelAttribute("language") Language language) {
this.langServ.allLangs();
model.addAttribute("allLang", this.langServ.allLangs());
return "index.jsp";
}
@PostMapping("/languages")
public String createLang(@Valid @ModelAttribute("language") Language language, BindingResult result, Model model) {
if(result.hasErrors()) {
model.addAttribute("allLang", this.langServ.allLangs());
return "index.jsp";
}else {
this.langServ.createLang(language);
return "redirect:/languages";
}
}
@RequestMapping("/languages/edit/{id}")
public String editLang(@PathVariable("id")Long id, Model model) {
Language lang = this.langServ.getLang(id);
model.addAttribute("language", lang);
return "edit.jsp";
}
@PostMapping("/languages/{id}/update")
public String updateLang(@Valid @ModelAttribute("language") Language language, BindingResult result) {
if(result.hasErrors()) {
return "edit.jsp";
} else {
this.langServ.updateLang(language);
return "redirect:/languages";
}
}
@GetMapping(value="/languages/{id}/delete")
public String destroy(@PathVariable("id") Long id) {
this.langServ.deleteLang(id);
return "redirect:/languages";
}
}
//@RequestMapping("/books/new")
//public String newBook(@ModelAttribute("book") Book book) {
// return "/books/new.jsp";
//}
//@RequestMapping(value="/books", method=RequestMethod.POST)
//public String create(@Valid @ModelAttribute("book") Book book, BindingResult result) {
// if (result.hasErrors()) {
// return "/books/new.jsp";
// } else {
// bookService.createBook(book);
// return "redirect:/books";
// }
| 2,515 | 0.737177 | 0.737177 | 78 | 31.256411 | 25.78433 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.474359 | false | false |
12
|
95733a9fe1a04f0a4b6afa14bbec5bc49b5da942
| 111,669,188,593 |
9d013d245dde38e5778fded937b95114edde57b1
|
/provider/src/main/java/com/ydm/provider/service/impl/DepartmentServiceImpl.java
|
9c41bcdb3a358e2e89dbabd10ab965232304f6bc
|
[] |
no_license
|
BloodFlame/springcloud-demo
|
https://github.com/BloodFlame/springcloud-demo
|
916d168a49b5b83cbfb1f600d3c42636cb2f5183
|
10dedf3f4e2b771bc94096ed17309ee1b16cd01d
|
refs/heads/master
| 2020-07-04T16:08:21.853000 | 2019-08-26T09:27:34 | 2019-08-26T09:27:34 | 202,333,502 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ydm.provider.service.impl;
import com.ydm.provider.dao.DepartmentMapper;
import com.ydm.provider.domain.Department;
import com.ydm.provider.domain.DepartmentExample;
import com.ydm.provider.exception.NotFoundDepartmentException;
import com.ydm.provider.service.DepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;
@Override
public boolean addDepartment(Department department) {
int ret = departmentMapper.insert(department);
return ret==1;
}
@Override
public boolean removeDepartmentById(int id) {
int ret = departmentMapper.deleteByPrimaryKey(id);
return ret==1;
}
@Override
public boolean modifyDepartment(Department department) {
int ret = departmentMapper.updateByPrimaryKey(department);
return ret==1;
}
@Override
public Department getDepartmentById(int id) {
return departmentMapper.selectByPrimaryKey(id);
}
@Override
public Department queryDepartment(String name) {
DepartmentExample departmentExample = new DepartmentExample();
departmentExample.createCriteria().andNameEqualTo(name);
List<Department> result = departmentMapper.selectByExample(departmentExample);
if(result.size() < 1) throw new NotFoundDepartmentException();
return result.get(0);
}
@Override
public List<Department> listAllDepartments() {
log.info("list--");
DepartmentExample departmentExample = new DepartmentExample();
departmentExample.setOrderByClause("id desc");
return departmentMapper.selectByExample(departmentExample);
}
}
|
UTF-8
|
Java
| 1,966 |
java
|
DepartmentServiceImpl.java
|
Java
|
[] | null |
[] |
package com.ydm.provider.service.impl;
import com.ydm.provider.dao.DepartmentMapper;
import com.ydm.provider.domain.Department;
import com.ydm.provider.domain.DepartmentExample;
import com.ydm.provider.exception.NotFoundDepartmentException;
import com.ydm.provider.service.DepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;
@Override
public boolean addDepartment(Department department) {
int ret = departmentMapper.insert(department);
return ret==1;
}
@Override
public boolean removeDepartmentById(int id) {
int ret = departmentMapper.deleteByPrimaryKey(id);
return ret==1;
}
@Override
public boolean modifyDepartment(Department department) {
int ret = departmentMapper.updateByPrimaryKey(department);
return ret==1;
}
@Override
public Department getDepartmentById(int id) {
return departmentMapper.selectByPrimaryKey(id);
}
@Override
public Department queryDepartment(String name) {
DepartmentExample departmentExample = new DepartmentExample();
departmentExample.createCriteria().andNameEqualTo(name);
List<Department> result = departmentMapper.selectByExample(departmentExample);
if(result.size() < 1) throw new NotFoundDepartmentException();
return result.get(0);
}
@Override
public List<Department> listAllDepartments() {
log.info("list--");
DepartmentExample departmentExample = new DepartmentExample();
departmentExample.setOrderByClause("id desc");
return departmentMapper.selectByExample(departmentExample);
}
}
| 1,966 | 0.739064 | 0.734995 | 61 | 31.229507 | 25.601225 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459016 | false | false |
12
|
e2affca15df46fb785f64e60f2f373c388edd149
| 31,086,973,325,161 |
ac09a467d9981f67d346d1a9035d98f234ce38d5
|
/leetcode/src/main/java/org/leetcode/problems/_000028_ImplementstrStr.java
|
ee02294967848fbeaf5398d3d26f8bb1e4bc0a91
|
[] |
no_license
|
AlexKokoz/leetcode
|
https://github.com/AlexKokoz/leetcode
|
03c9749c97c846c4018295008095ac86ae4951ee
|
9449593df72d86dadc4c470f1f9698e066632859
|
refs/heads/master
| 2023-02-23T13:56:38.978000 | 2023-02-12T21:21:54 | 2023-02-12T21:21:54 | 232,152,255 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.leetcode.problems;
public class _000028_ImplementstrStr {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
|
UTF-8
|
Java
| 164 |
java
|
_000028_ImplementstrStr.java
|
Java
|
[] | null |
[] |
package org.leetcode.problems;
public class _000028_ImplementstrStr {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
| 164 | 0.768293 | 0.731707 | 7 | 22.428572 | 19.594877 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
12
|
7abb91699576f89f8291afaf0821ac85f992e036
| 27,101,243,705,978 |
ce8f0b3b59c79dbd929b8a47561f2e6470d62ecd
|
/Server/src/main/java/server/persistence/dataendpoints/SerializableFileEndpoint.java
|
04d46ceee41f3d1d3e4f8b323511fcfbbaea2ed8
|
[
"MIT"
] |
permissive
|
B-Stefan/Risiko
|
https://github.com/B-Stefan/Risiko
|
54ff277956e01874f346952822f50b9530abba99
|
a3cee2edae7692e9219bf2a46748de11cbaf773b
|
refs/heads/master
| 2021-06-02T11:37:05.606000 | 2020-12-28T19:37:36 | 2020-12-28T19:37:36 | 18,306,670 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* RISIKO-JAVA - Game, Copyright 2014 Jennifer Theloy, Stefan Bieliauskas - All Rights Reserved.
* Hochschule Bremen - University of Applied Sciences
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contact:
* Jennifer Theloy: jTheloy@stud.hs-bremen.de
* Stefan Bieliauskas: sBieliauskas@stud.hs-bremen.de
*
* Web:
* https://github.com/B-Stefan/Risiko
*
*/
package server.persistence.dataendpoints;
import server.persistence.PersistenceManager;
import server.persistence.objects.PersitenceObject;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;
/**
* Diese Klasse stellt die Möglichkeit zur Speicherung durch einfache Serialisierung zur Verfügung.
* @param <T>
*/
public class SerializableFileEndpoint<T> extends AbstractFileEndpoint<T> {
public SerializableFileEndpoint(Class<T> sourceClass, Class<? extends PersitenceObject<T>> dataClass, PersistenceManager manager) {
super(sourceClass, dataClass, manager);
}
/**
* Liest den File und packt alle Objekte des Files in die Liste chacedObjects
*/
@Override
protected void readFile() {
{
AbstractFileEndpoint.createDir();
try {
ObjectInputStream reader = new ObjectInputStream(new FileInputStream(AbstractFileEndpoint.convertFileNameToPath(this.fileName)));
this.chachedObjects = (HashMap<UUID, PersitenceObject<T>>) reader.readObject();
}catch (ClassNotFoundException | ClassCastException e){
throw new RuntimeException(e);
}
catch (EOFException | InvalidClassException e){
//File ist leer
} catch (FileNotFoundException e){
this.writeFile(); // File erstellen, wenn nicht vorhanden
}
catch (IOException e){
//@Todo Besseres Exception Handling
e.printStackTrace();
}
}
}
/**
* Schreibt die Liste chachedObjetcts in die Datei
*/
@Override
protected void writeFile() {
{
try {
FileOutputStream fos = new FileOutputStream(AbstractFileEndpoint.convertFileNameToPath(this.fileName),false);
ObjectOutputStream writer = new ObjectOutputStream(fos);
writer.writeObject(this.chachedObjects);
writer.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
|
UTF-8
|
Java
| 3,197 |
java
|
SerializableFileEndpoint.java
|
Java
|
[
{
"context": "/*\n * RISIKO-JAVA - Game, Copyright 2014 Jennifer Theloy, Stefan Bieliauskas - All Rights Reserved.\n * H",
"end": 57,
"score": 0.999865710735321,
"start": 42,
"tag": "NAME",
"value": "Jennifer Theloy"
},
{
"context": "SIKO-JAVA - Game, Copyright 2014 Jennifer Theloy, Stefan Bieliauskas - All Rights Reserved.\n * Hochschule Bremen - U",
"end": 77,
"score": 0.9998869299888611,
"start": 59,
"tag": "NAME",
"value": "Stefan Bieliauskas"
},
{
"context": "Boston, MA 02110-1301, USA.\n *\n * Contact:\n * Jennifer Theloy: jTheloy@stud.hs-bremen.de\n * Stefan Bieliaus",
"end": 919,
"score": 0.9998704791069031,
"start": 904,
"tag": "NAME",
"value": "Jennifer Theloy"
},
{
"context": "-1301, USA.\n *\n * Contact:\n * Jennifer Theloy: jTheloy@stud.hs-bremen.de\n * Stefan Bieliauskas: sBieliauskas@stud.hs-b",
"end": 946,
"score": 0.9999325275421143,
"start": 921,
"tag": "EMAIL",
"value": "jTheloy@stud.hs-bremen.de"
},
{
"context": " Jennifer Theloy: jTheloy@stud.hs-bremen.de\n * Stefan Bieliauskas: sBieliauskas@stud.hs-bremen.de\n *\n * Web:\n * ",
"end": 972,
"score": 0.9998858571052551,
"start": 954,
"tag": "NAME",
"value": "Stefan Bieliauskas"
},
{
"context": "heloy@stud.hs-bremen.de\n * Stefan Bieliauskas: sBieliauskas@stud.hs-bremen.de\n *\n * Web:\n * https://github.com/B-Stefan/Ris",
"end": 1004,
"score": 0.9999285340309143,
"start": 974,
"tag": "EMAIL",
"value": "sBieliauskas@stud.hs-bremen.de"
},
{
"context": "hs-bremen.de\n *\n * Web:\n * https://github.com/B-Stefan/Risiko\n *\n */\n\npackage server.persistence.dataend",
"end": 1050,
"score": 0.8500964045524597,
"start": 1042,
"tag": "USERNAME",
"value": "B-Stefan"
}
] | null |
[] |
/*
* RISIKO-JAVA - Game, Copyright 2014 <NAME>, <NAME> - All Rights Reserved.
* Hochschule Bremen - University of Applied Sciences
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contact:
* <NAME>: <EMAIL>
* <NAME>: <EMAIL>
*
* Web:
* https://github.com/B-Stefan/Risiko
*
*/
package server.persistence.dataendpoints;
import server.persistence.PersistenceManager;
import server.persistence.objects.PersitenceObject;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;
/**
* Diese Klasse stellt die Möglichkeit zur Speicherung durch einfache Serialisierung zur Verfügung.
* @param <T>
*/
public class SerializableFileEndpoint<T> extends AbstractFileEndpoint<T> {
public SerializableFileEndpoint(Class<T> sourceClass, Class<? extends PersitenceObject<T>> dataClass, PersistenceManager manager) {
super(sourceClass, dataClass, manager);
}
/**
* Liest den File und packt alle Objekte des Files in die Liste chacedObjects
*/
@Override
protected void readFile() {
{
AbstractFileEndpoint.createDir();
try {
ObjectInputStream reader = new ObjectInputStream(new FileInputStream(AbstractFileEndpoint.convertFileNameToPath(this.fileName)));
this.chachedObjects = (HashMap<UUID, PersitenceObject<T>>) reader.readObject();
}catch (ClassNotFoundException | ClassCastException e){
throw new RuntimeException(e);
}
catch (EOFException | InvalidClassException e){
//File ist leer
} catch (FileNotFoundException e){
this.writeFile(); // File erstellen, wenn nicht vorhanden
}
catch (IOException e){
//@Todo Besseres Exception Handling
e.printStackTrace();
}
}
}
/**
* Schreibt die Liste chachedObjetcts in die Datei
*/
@Override
protected void writeFile() {
{
try {
FileOutputStream fos = new FileOutputStream(AbstractFileEndpoint.convertFileNameToPath(this.fileName),false);
ObjectOutputStream writer = new ObjectOutputStream(fos);
writer.writeObject(this.chachedObjects);
writer.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
| 3,114 | 0.656338 | 0.65133 | 95 | 32.63158 | 33.290131 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442105 | false | false |
12
|
3eae5c603b9987fddbc45dd5577e15c5cab5474b
| 20,203,526,198,393 |
60119a4a5c999799a0e04cca31e54f47747237c6
|
/ws-server/src/main/java/com/honorzhang/web/service/server/mapper/PeopleMapper.java
|
de053d5400aff35f4d758d2a381da7e7c743528b
|
[] |
no_license
|
airhonor/WebService
|
https://github.com/airhonor/WebService
|
c1521b593c42c2d5db950ef311c38c0eadc2ea4a
|
b4f91d44b4090da79aec238a492153cf47c2edf4
|
refs/heads/master
| 2022-12-27T06:35:04.013000 | 2020-10-12T13:53:46 | 2020-10-12T13:53:46 | 292,210,368 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.honorzhang.web.service.server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.honorzhang.web.service.server.model.People;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
/**
* @program: webservice-example
* @author: zgr
* @create: 2020-09-16 12:36
**/
@Mapper
public interface PeopleMapper extends BaseMapper<People> {
}
|
UTF-8
|
Java
| 412 |
java
|
PeopleMapper.java
|
Java
|
[
{
"context": ";\n\n/**\n * @program: webservice-example\n * @author: zgr\n * @create: 2020-09-16 12:36\n **/\n@Mapper\npublic ",
"end": 308,
"score": 0.9996932148933411,
"start": 305,
"tag": "USERNAME",
"value": "zgr"
}
] | null |
[] |
package com.honorzhang.web.service.server.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.honorzhang.web.service.server.model.People;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
/**
* @program: webservice-example
* @author: zgr
* @create: 2020-09-16 12:36
**/
@Mapper
public interface PeopleMapper extends BaseMapper<People> {
}
| 412 | 0.786408 | 0.757282 | 15 | 26.466667 | 22.336418 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
12
|
a67535b73026e5e57188d0e91504260fdca2ae28
| 3,865,470,602,604 |
72b8822f2fceb754e8f614dd52e661aba780ff4c
|
/src/Classes/IndexPHP.java
|
45476e2b0dff7cdd80c3072a35b84ca9702452c3
|
[] |
no_license
|
TaffarelXavier/PDO_Modelagem
|
https://github.com/TaffarelXavier/PDO_Modelagem
|
ed50c408dc04a3e18fd37b0ad6006fb9b6d84153
|
6d19797fdd2bc7d77be82a253fd18473c35b5518
|
refs/heads/master
| 2020-06-17T23:26:05.839000 | 2019-07-09T23:33:26 | 2019-07-09T23:33:26 | 196,098,086 | 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 Classes;
/**
* <p>
* Cria um arquivo Index dentro da pasta root.</p>
*
* @author Taffrel Xavier <taffarel_deus@hotmail.com>
*/
public class IndexPHP {
public static String salvar(String titulo, String formulario) {
return "<?php\n"
+ "include 'autoload.php';\n"
+ "?>\n"
+ "<!DOCTYPE html>\n"
+ "<html lang=\"pt-br\">\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> \n"
+ " <title>" + titulo + "</title>\n"
+ " <script src=\"assets/js/jquery.js\"></script>"
+ " <script src=\"assets/js/jquery.form.js\"></script>"
+ " </head>\n"
+ " <body>\n"
+ " <p>Tabela(s) do banco <b><mark><?php echo DB_NAME; ?></mark></b>:</p>\n"
+ " <?php \n"
+ " $st = $connection->prepare(\"show tables;\");\n"
+ " $st->execute();\n"
+ " print_r($st->fetch(PDO::FETCH_ASSOC));\n"
+ formulario
+ " ?>"
+ "</body>\n"
+ "</html>";
}
}
|
UTF-8
|
Java
| 1,522 |
java
|
IndexPHP.java
|
Java
|
[
{
"context": "uivo Index dentro da pasta root.</p>\n *\n * @author Taffrel Xavier <taffarel_deus@hotmail.com>\n */\npublic class Inde",
"end": 293,
"score": 0.9998785853385925,
"start": 279,
"tag": "NAME",
"value": "Taffrel Xavier"
},
{
"context": " da pasta root.</p>\n *\n * @author Taffrel Xavier <taffarel_deus@hotmail.com>\n */\npublic class IndexPHP {\n\n public static S",
"end": 320,
"score": 0.9999353885650635,
"start": 295,
"tag": "EMAIL",
"value": "taffarel_deus@hotmail.com"
}
] | 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 Classes;
/**
* <p>
* Cria um arquivo Index dentro da pasta root.</p>
*
* @author <NAME> <<EMAIL>>
*/
public class IndexPHP {
public static String salvar(String titulo, String formulario) {
return "<?php\n"
+ "include 'autoload.php';\n"
+ "?>\n"
+ "<!DOCTYPE html>\n"
+ "<html lang=\"pt-br\">\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> \n"
+ " <title>" + titulo + "</title>\n"
+ " <script src=\"assets/js/jquery.js\"></script>"
+ " <script src=\"assets/js/jquery.form.js\"></script>"
+ " </head>\n"
+ " <body>\n"
+ " <p>Tabela(s) do banco <b><mark><?php echo DB_NAME; ?></mark></b>:</p>\n"
+ " <?php \n"
+ " $st = $connection->prepare(\"show tables;\");\n"
+ " $st->execute();\n"
+ " print_r($st->fetch(PDO::FETCH_ASSOC));\n"
+ formulario
+ " ?>"
+ "</body>\n"
+ "</html>";
}
}
| 1,496 | 0.428384 | 0.42707 | 40 | 37.049999 | 27.889917 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.325 | false | false |
12
|
4b621be2b6becd7a08763a2c51bef94d7a673065
| 22,986,664,983,934 |
54fa337e0aba15414a2fb7c19ba61eb01db409ce
|
/src/main/java/net/Indyuce/moarbows/util/LinearFormula.java
|
287b28a888b9e16b7ecefa156370af5b5c351998
|
[] |
no_license
|
Indyuce/moar-bows
|
https://github.com/Indyuce/moar-bows
|
06d68e7be89b53eb72ba2c1c0a63c552af20abf6
|
4eb8ef1d2d6ddb360cd2f5afcd04b20e0b1973bd
|
refs/heads/master
| 2022-05-03T14:32:13.511000 | 2022-03-18T18:09:43 | 2022-03-18T18:09:43 | 135,139,291 | 10 | 7 | null | false | 2022-04-20T13:47:07 | 2018-05-28T09:25:10 | 2022-01-01T23:09:03 | 2022-04-19T17:17:22 | 525 | 7 | 5 | 4 |
Java
| false | false |
package net.Indyuce.moarbows.util;
import org.bukkit.configuration.ConfigurationSection;
public class LinearFormula {
private final double base, scale, min, max;
private final boolean hasmin, hasmax;
/*
* a number which depends on the player level. it can be used as a skill
* modifier to make the ability better depending on the player level or as
* an attrribute value to make attributes increase with the player level
*/
public LinearFormula(double base, double scale) {
this.base = base;
this.scale = scale;
min = max = 0;
hasmin = hasmax = false;
}
public LinearFormula(double base, double scale, double min, double max) {
this.base = base;
this.scale = scale;
this.min = min;
this.max = max;
hasmin = true;
hasmax = true;
}
public LinearFormula(ConfigurationSection config) {
base = config.getDouble("base");
scale = config.getDouble("per-level");
hasmin = config.contains("min");
min = hasmin ? config.getDouble("min") : 0;
hasmax = config.contains("max");
max = hasmax ? config.getDouble("max") : 0;
}
public double getBase() {
return base;
}
public double getScale() {
return scale;
}
public double getMax() {
return max;
}
public double getMin() {
return min;
}
public boolean hasMax() {
return hasmax;
}
public boolean hasMin() {
return hasmin;
}
public double calculate(int level) {
double value = base + scale * (level - 1);
if (hasmin)
value = Math.max(min, value);
if (hasmax)
value = Math.min(max, value);
return value;
}
}
|
UTF-8
|
Java
| 1,544 |
java
|
LinearFormula.java
|
Java
|
[] | null |
[] |
package net.Indyuce.moarbows.util;
import org.bukkit.configuration.ConfigurationSection;
public class LinearFormula {
private final double base, scale, min, max;
private final boolean hasmin, hasmax;
/*
* a number which depends on the player level. it can be used as a skill
* modifier to make the ability better depending on the player level or as
* an attrribute value to make attributes increase with the player level
*/
public LinearFormula(double base, double scale) {
this.base = base;
this.scale = scale;
min = max = 0;
hasmin = hasmax = false;
}
public LinearFormula(double base, double scale, double min, double max) {
this.base = base;
this.scale = scale;
this.min = min;
this.max = max;
hasmin = true;
hasmax = true;
}
public LinearFormula(ConfigurationSection config) {
base = config.getDouble("base");
scale = config.getDouble("per-level");
hasmin = config.contains("min");
min = hasmin ? config.getDouble("min") : 0;
hasmax = config.contains("max");
max = hasmax ? config.getDouble("max") : 0;
}
public double getBase() {
return base;
}
public double getScale() {
return scale;
}
public double getMax() {
return max;
}
public double getMin() {
return min;
}
public boolean hasMax() {
return hasmax;
}
public boolean hasMin() {
return hasmin;
}
public double calculate(int level) {
double value = base + scale * (level - 1);
if (hasmin)
value = Math.max(min, value);
if (hasmax)
value = Math.min(max, value);
return value;
}
}
| 1,544 | 0.678109 | 0.675518 | 74 | 19.864864 | 20.099297 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.689189 | false | false |
12
|
04e3211404ecaa47a0246a760126848bb9b45244
| 26,877,905,404,328 |
f9b9ed0b36c1de5e469710602a18cfd0673cdcc0
|
/AIrtickets/src/test/java/airtickets/services/BranchOfficeServiceTest.java
|
e7ceb5c66d5e7aa08c9199b79709f46da0ef2c96
|
[] |
no_license
|
harmonikas996/airTickets
|
https://github.com/harmonikas996/airTickets
|
80163cd38c175b2a2b4395f9068ede4e6628d627
|
dfc833ef51ddf740cd4fe47fd5a631cb7039442c
|
refs/heads/airTickets
| 2023-01-08T03:19:43.770000 | 2019-09-11T09:57:46 | 2019-09-11T09:57:46 | 155,613,309 | 0 | 0 | null | false | 2023-01-07T02:39:23 | 2018-10-31T19:36:37 | 2019-10-14T10:12:35 | 2023-01-07T02:39:22 | 4,925 | 0 | 0 | 28 |
Java
| false | false |
package airtickets.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import airtickets.dto.rentacar.BranchOfficeDTO;
import airtickets.model.rentacar.BranchOffice;
import airtickets.model.rentacar.RentACar;
import airtickets.repo.rentacar.BranchOfficeRepository;
import airtickets.service.rentacar.BranchOfficeService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BranchOfficeServiceTest {
@Mock
private BranchOfficeRepository branchOfficeRepoMock;
@Mock
BranchOfficeDTO branchOfficeDTOMock;
@Mock
BranchOffice branchOfficeMock;
@Mock
RentACar rentacarMock;
@InjectMocks
private BranchOfficeService branchOfficeService;
@Test
public void getBranchOffices() {
// prepare data
branchOfficeMock = new BranchOffice();
rentacarMock = new RentACar();
branchOfficeMock.setRentACar(rentacarMock);
when(branchOfficeRepoMock.findAll()).thenReturn(Arrays.asList(branchOfficeMock));
// service method call
List<BranchOfficeDTO> returnedBranchOfficies = branchOfficeService.getBranchOffices();
// check data retrieval
assertThat(returnedBranchOfficies).hasSize(1);
verify(branchOfficeRepoMock, times(1)).findAll();
verifyNoMoreInteractions(branchOfficeRepoMock);
}
@Test
public void getBranchOffice() {
// prepare data
branchOfficeMock = new BranchOffice();
rentacarMock = new RentACar();
branchOfficeMock.setId(13);
branchOfficeMock.setRentACar(rentacarMock);
when(branchOfficeRepoMock.findById(13)).thenReturn(branchOfficeMock);
// service method call
BranchOfficeDTO returnedBranchOffice = branchOfficeService.getBranchOffice(13);
// check data retrieval
assertThat(returnedBranchOffice).isNotNull();
assertThat(returnedBranchOffice).hasFieldOrPropertyWithValue("id", new Long(13));
verify(branchOfficeRepoMock, times(1)).findById(13);
verifyNoMoreInteractions(branchOfficeRepoMock);
}
@Test
public void getLocations() {
// prepare data
when(branchOfficeRepoMock.findAllCities()).thenReturn(Arrays.asList(new String()));
// service method call
List<String> returnedLocations = branchOfficeService.getLocations();
// check data retrieval
assertThat(returnedLocations).isNotEmpty();
assertThat(returnedLocations).hasSize(1);
verify(branchOfficeRepoMock, times(1)).findAllCities();
verifyNoMoreInteractions(branchOfficeRepoMock);
}
@Test
public void addBranchOffice() {
// prepare data
branchOfficeDTOMock = new BranchOfficeDTO();
branchOfficeMock = new BranchOffice(branchOfficeDTOMock);
when(branchOfficeRepoMock.save(branchOfficeMock)).thenReturn(branchOfficeMock);
// service method call
BranchOfficeDTO returnedBranchOfficeDTO = branchOfficeService.addBranchOffice(branchOfficeDTOMock);
// check data retrieval
assertThat(returnedBranchOfficeDTO).isNotNull();
}
@Test
public void findByRentACarId() {
// prepare data
branchOfficeDTOMock = new BranchOfficeDTO();
branchOfficeDTOMock.setRentACarId(11);
branchOfficeMock = new BranchOffice(branchOfficeDTOMock);
when(branchOfficeRepoMock.findByRentACarId(11)).thenReturn(Arrays.asList(branchOfficeMock));
// service method call
List<BranchOfficeDTO> returnedBranchOfficeDTOs = branchOfficeService.findByRentACarId(11);
// check data retrieval
assertThat(returnedBranchOfficeDTOs).isNotEmpty();
assertThat(returnedBranchOfficeDTOs).hasSize(1);
verify(branchOfficeRepoMock, times(1)).findByRentACarId(11);
verifyNoMoreInteractions(branchOfficeRepoMock);
}
}
|
UTF-8
|
Java
| 4,064 |
java
|
BranchOfficeServiceTest.java
|
Java
|
[] | null |
[] |
package airtickets.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import airtickets.dto.rentacar.BranchOfficeDTO;
import airtickets.model.rentacar.BranchOffice;
import airtickets.model.rentacar.RentACar;
import airtickets.repo.rentacar.BranchOfficeRepository;
import airtickets.service.rentacar.BranchOfficeService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BranchOfficeServiceTest {
@Mock
private BranchOfficeRepository branchOfficeRepoMock;
@Mock
BranchOfficeDTO branchOfficeDTOMock;
@Mock
BranchOffice branchOfficeMock;
@Mock
RentACar rentacarMock;
@InjectMocks
private BranchOfficeService branchOfficeService;
@Test
public void getBranchOffices() {
// prepare data
branchOfficeMock = new BranchOffice();
rentacarMock = new RentACar();
branchOfficeMock.setRentACar(rentacarMock);
when(branchOfficeRepoMock.findAll()).thenReturn(Arrays.asList(branchOfficeMock));
// service method call
List<BranchOfficeDTO> returnedBranchOfficies = branchOfficeService.getBranchOffices();
// check data retrieval
assertThat(returnedBranchOfficies).hasSize(1);
verify(branchOfficeRepoMock, times(1)).findAll();
verifyNoMoreInteractions(branchOfficeRepoMock);
}
@Test
public void getBranchOffice() {
// prepare data
branchOfficeMock = new BranchOffice();
rentacarMock = new RentACar();
branchOfficeMock.setId(13);
branchOfficeMock.setRentACar(rentacarMock);
when(branchOfficeRepoMock.findById(13)).thenReturn(branchOfficeMock);
// service method call
BranchOfficeDTO returnedBranchOffice = branchOfficeService.getBranchOffice(13);
// check data retrieval
assertThat(returnedBranchOffice).isNotNull();
assertThat(returnedBranchOffice).hasFieldOrPropertyWithValue("id", new Long(13));
verify(branchOfficeRepoMock, times(1)).findById(13);
verifyNoMoreInteractions(branchOfficeRepoMock);
}
@Test
public void getLocations() {
// prepare data
when(branchOfficeRepoMock.findAllCities()).thenReturn(Arrays.asList(new String()));
// service method call
List<String> returnedLocations = branchOfficeService.getLocations();
// check data retrieval
assertThat(returnedLocations).isNotEmpty();
assertThat(returnedLocations).hasSize(1);
verify(branchOfficeRepoMock, times(1)).findAllCities();
verifyNoMoreInteractions(branchOfficeRepoMock);
}
@Test
public void addBranchOffice() {
// prepare data
branchOfficeDTOMock = new BranchOfficeDTO();
branchOfficeMock = new BranchOffice(branchOfficeDTOMock);
when(branchOfficeRepoMock.save(branchOfficeMock)).thenReturn(branchOfficeMock);
// service method call
BranchOfficeDTO returnedBranchOfficeDTO = branchOfficeService.addBranchOffice(branchOfficeDTOMock);
// check data retrieval
assertThat(returnedBranchOfficeDTO).isNotNull();
}
@Test
public void findByRentACarId() {
// prepare data
branchOfficeDTOMock = new BranchOfficeDTO();
branchOfficeDTOMock.setRentACarId(11);
branchOfficeMock = new BranchOffice(branchOfficeDTOMock);
when(branchOfficeRepoMock.findByRentACarId(11)).thenReturn(Arrays.asList(branchOfficeMock));
// service method call
List<BranchOfficeDTO> returnedBranchOfficeDTOs = branchOfficeService.findByRentACarId(11);
// check data retrieval
assertThat(returnedBranchOfficeDTOs).isNotEmpty();
assertThat(returnedBranchOfficeDTOs).hasSize(1);
verify(branchOfficeRepoMock, times(1)).findByRentACarId(11);
verifyNoMoreInteractions(branchOfficeRepoMock);
}
}
| 4,064 | 0.790108 | 0.783711 | 133 | 29.556391 | 25.908287 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.736842 | false | false |
12
|
2b9f6e47cd70d042804f48482c8db5305bad79a9
| 11,716,670,821,185 |
867b28a60911a44c5180b32ca99fe33ecb355ed8
|
/core/src/donnees/effet/EffetAttaque.java
|
bb8d729b5ba3dabe6fa5526565d57b47e1c1fd54
|
[] |
no_license
|
luCmoi/Arena
|
https://github.com/luCmoi/Arena
|
a6cd16aaa2255b12c59b5ad7be01c2f1073500e5
|
1f138604ffa950a17259777024e1452de1570e5c
|
refs/heads/master
| 2015-08-11T11:04:01 | 2014-07-21T13:54:13 | 2014-07-21T13:54:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package donnees.effet;
import donnees.nombreMax;
public class EffetAttaque {
public static void attaque(int touche, int esquive, int degat, nombreMax vie) {
int jeTouche = (int) (Math.random() * 100);
System.out.println("Jet : " + jeTouche + " Pourcent : " + touche);
if (jeTouche >= (100 - touche)) {
System.out.println("Toucher");
int jeSquive = (int) (Math.random() * 100);
System.out.println("Jet : " + jeSquive + " Pourcent : " + esquive);
if (jeSquive >= (100 - esquive)) {
System.out.println("Esquive");
} else {
System.out.println("Degat : "+degat+" Vie : "+vie.getActuel());
vie.setActuel(vie.getActuel()-degat);
System.out.println("Vie restante : "+vie.getActuel());
}
}
}
}
|
UTF-8
|
Java
| 864 |
java
|
EffetAttaque.java
|
Java
|
[] | null |
[] |
package donnees.effet;
import donnees.nombreMax;
public class EffetAttaque {
public static void attaque(int touche, int esquive, int degat, nombreMax vie) {
int jeTouche = (int) (Math.random() * 100);
System.out.println("Jet : " + jeTouche + " Pourcent : " + touche);
if (jeTouche >= (100 - touche)) {
System.out.println("Toucher");
int jeSquive = (int) (Math.random() * 100);
System.out.println("Jet : " + jeSquive + " Pourcent : " + esquive);
if (jeSquive >= (100 - esquive)) {
System.out.println("Esquive");
} else {
System.out.println("Degat : "+degat+" Vie : "+vie.getActuel());
vie.setActuel(vie.getActuel()-degat);
System.out.println("Vie restante : "+vie.getActuel());
}
}
}
}
| 864 | 0.533565 | 0.519676 | 23 | 36.565216 | 27.679573 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false |
12
|
fda71308dd12cbe84fbd2127ba3301d2ab5fe19a
| 26,929,445,002,406 |
09701614f7a19500a4249e197f73f6cceb0818f9
|
/app/src/main/java/com/example/restaurant/DAO/HoaDonDAO.java
|
adab79624763efa60f2a5e4c2548f002d4979a71
|
[] |
no_license
|
VinhLP/DoAnTotNghiep
|
https://github.com/VinhLP/DoAnTotNghiep
|
1ae6c019405770c831d39b76d3ed7413f92f4efb
|
a5b9f55c2c2840cf05e4a24309b6bd41ca4ebc4d
|
refs/heads/master
| 2020-06-24T14:57:50.437000 | 2019-07-26T10:04:18 | 2019-07-26T10:04:18 | 198,993,395 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.restaurant.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.example.restaurant.DTO.ChiTietHoaDonDTO;
import com.example.restaurant.DTO.HoaDonDTO;
import com.example.restaurant.Database.CreateDatabase;
public class HoaDonDAO {
SQLiteDatabase database;
public HoaDonDAO(Context context){
CreateDatabase createDatabase = new CreateDatabase(context);
database = createDatabase.open();
}
public long ThemHoaDon(HoaDonDTO hoaDonDTO){
ContentValues contentValues = new ContentValues();
contentValues.put(CreateDatabase.TB_HOADON_MABAN, hoaDonDTO.getMABAN());
contentValues.put(CreateDatabase.TB_HOADON_MANV, hoaDonDTO.getMANV());
contentValues.put(CreateDatabase.TB_HOADON_NGAYTHANHTOAN, hoaDonDTO.getNGAYTHANHTOAN());
contentValues.put(CreateDatabase.TB_HOADON_TONGTIEN, hoaDonDTO.getTONGTIEN());
long mahoadon = database.insert(CreateDatabase.TB_HOADON, null, contentValues);
return mahoadon;
}
}
|
UTF-8
|
Java
| 1,097 |
java
|
HoaDonDAO.java
|
Java
|
[] | null |
[] |
package com.example.restaurant.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.example.restaurant.DTO.ChiTietHoaDonDTO;
import com.example.restaurant.DTO.HoaDonDTO;
import com.example.restaurant.Database.CreateDatabase;
public class HoaDonDAO {
SQLiteDatabase database;
public HoaDonDAO(Context context){
CreateDatabase createDatabase = new CreateDatabase(context);
database = createDatabase.open();
}
public long ThemHoaDon(HoaDonDTO hoaDonDTO){
ContentValues contentValues = new ContentValues();
contentValues.put(CreateDatabase.TB_HOADON_MABAN, hoaDonDTO.getMABAN());
contentValues.put(CreateDatabase.TB_HOADON_MANV, hoaDonDTO.getMANV());
contentValues.put(CreateDatabase.TB_HOADON_NGAYTHANHTOAN, hoaDonDTO.getNGAYTHANHTOAN());
contentValues.put(CreateDatabase.TB_HOADON_TONGTIEN, hoaDonDTO.getTONGTIEN());
long mahoadon = database.insert(CreateDatabase.TB_HOADON, null, contentValues);
return mahoadon;
}
}
| 1,097 | 0.756609 | 0.756609 | 32 | 33.28125 | 30.489992 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.71875 | false | false |
12
|
037c124b514a8fa143c636a7bb7fcb2929c92396
| 10,857,677,385,496 |
fcdcdc1cb6371c741128cb5d3a880f10a901cc9a
|
/src/test/java/com/blablacar/service/MowerServicesTest.java
|
3bc001dc04f7215f81b541f73c04317280eab3e2
|
[] |
no_license
|
jiantangupm/blablacar
|
https://github.com/jiantangupm/blablacar
|
fdc8883e7ef2ec36a468415bb4acea947ac1c9d6
|
5dc5ff9ed8bc5657c3192efed04c1c320dc0c5d2
|
refs/heads/master
| 2022-12-21T08:18:42.173000 | 2020-09-28T11:38:55 | 2020-09-28T11:38:55 | 299,044,076 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.blablacar.service;
import com.blablacar.model.Mower;
import com.blablacar.model.enums.Direction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MowerServicesTest {
private MowerServices mowerServices;
private String initPosition;
private String command;
private int width;
private int length;
@BeforeEach
public void setUp() {
initPosition = "1 2 N";
command = "LFLFLFLFF";
width = 5;
length = 5;
mowerServices = new MowerServices();
}
@Test
public void testMowerCreation() throws Exception {
final Mower mower = mowerServices.mowerCreation(initPosition, command, width, length);
assertEquals(Direction.NORTH, mower.getDirection());
assertEquals(1, mower.getPosition().getX());
}
//String input = "5 5\n1 2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF\n";
@Test
public void testMowerMow() throws Exception {
final Mower mower = mowerServices.mowerCreation(initPosition, command, width, length);
mowerServices.mow(mower);
assertEquals(Direction.NORTH, mower.getDirection());
assertEquals(3, mower.getPosition().getY());
}
}
|
UTF-8
|
Java
| 1,322 |
java
|
MowerServicesTest.java
|
Java
|
[] | null |
[] |
package com.blablacar.service;
import com.blablacar.model.Mower;
import com.blablacar.model.enums.Direction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MowerServicesTest {
private MowerServices mowerServices;
private String initPosition;
private String command;
private int width;
private int length;
@BeforeEach
public void setUp() {
initPosition = "1 2 N";
command = "LFLFLFLFF";
width = 5;
length = 5;
mowerServices = new MowerServices();
}
@Test
public void testMowerCreation() throws Exception {
final Mower mower = mowerServices.mowerCreation(initPosition, command, width, length);
assertEquals(Direction.NORTH, mower.getDirection());
assertEquals(1, mower.getPosition().getX());
}
//String input = "5 5\n1 2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF\n";
@Test
public void testMowerMow() throws Exception {
final Mower mower = mowerServices.mowerCreation(initPosition, command, width, length);
mowerServices.mow(mower);
assertEquals(Direction.NORTH, mower.getDirection());
assertEquals(3, mower.getPosition().getY());
}
}
| 1,322 | 0.695159 | 0.686082 | 45 | 28.4 | 24.655313 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false |
12
|
27215969b7b1afb910a47d82bf7cc68c0ee7da58
| 20,538,533,656,416 |
41cbff549c013bec39380f42f09b257d26dbfac9
|
/app/src/main/java/com/example/administrator/mygaodemap/Bean/Menu.java
|
c624060ffe9c430e66fb0e01fe491966335b5310
|
[] |
no_license
|
1549469775/MyGao
|
https://github.com/1549469775/MyGao
|
38299216a8a281eee24b65a661a948d80650e123
|
f7d3a9457e824413d7326602f1edb289bf692b62
|
refs/heads/master
| 2021-01-19T21:44:04.985000 | 2017-04-19T10:38:06 | 2017-04-19T10:38:06 | 88,693,807 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.administrator.mygaodemap.Bean;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by John on 2017/4/14.
*/
public class Menu {
private int img_menu;
private String tv_name;
private int img_show;
private String tv_show;
private Context context;
private Class aClass;
public Menu(Context context,Class aClass,int img_menu, String tv_name) {
this.img_menu = img_menu;
this.tv_name = tv_name;
this.aClass=aClass;
this.context=context;
}
public Menu(Context context,Class aClass,int img_menu, String tv_name, int img_show, String tv_show) {
this.img_menu = img_menu;
this.tv_name = tv_name;
this.img_show = img_show;
this.tv_show = tv_show;
this.aClass=aClass;
this.context=context;
}
public int getImg_menu() {
return img_menu;
}
public void setImg_menu(int img_menu) {
this.img_menu = img_menu;
}
public String getTv_name() {
return tv_name;
}
public void setTv_name(String tv_name) {
this.tv_name = tv_name;
}
public void toActivity(){
if (aClass==null){
Toast.makeText(context.getApplicationContext(),getTv_name(),Toast.LENGTH_SHORT).show();
}else {
context.startActivity(new Intent(context,aClass));
}
}
public int getImg_show() {
return img_show;
}
public void setImg_show(int img_show) {
this.img_show = img_show;
}
public String getTv_show() {
return tv_show;
}
public void setTv_show(String tv_show) {
this.tv_show = tv_show;
}
}
|
UTF-8
|
Java
| 1,733 |
java
|
Menu.java
|
Java
|
[
{
"context": "t;\nimport android.widget.Toast;\n\n/**\n * Created by John on 2017/4/14.\n */\n\npublic class Menu {\n\n priva",
"end": 167,
"score": 0.9418413043022156,
"start": 163,
"tag": "NAME",
"value": "John"
}
] | null |
[] |
package com.example.administrator.mygaodemap.Bean;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by John on 2017/4/14.
*/
public class Menu {
private int img_menu;
private String tv_name;
private int img_show;
private String tv_show;
private Context context;
private Class aClass;
public Menu(Context context,Class aClass,int img_menu, String tv_name) {
this.img_menu = img_menu;
this.tv_name = tv_name;
this.aClass=aClass;
this.context=context;
}
public Menu(Context context,Class aClass,int img_menu, String tv_name, int img_show, String tv_show) {
this.img_menu = img_menu;
this.tv_name = tv_name;
this.img_show = img_show;
this.tv_show = tv_show;
this.aClass=aClass;
this.context=context;
}
public int getImg_menu() {
return img_menu;
}
public void setImg_menu(int img_menu) {
this.img_menu = img_menu;
}
public String getTv_name() {
return tv_name;
}
public void setTv_name(String tv_name) {
this.tv_name = tv_name;
}
public void toActivity(){
if (aClass==null){
Toast.makeText(context.getApplicationContext(),getTv_name(),Toast.LENGTH_SHORT).show();
}else {
context.startActivity(new Intent(context,aClass));
}
}
public int getImg_show() {
return img_show;
}
public void setImg_show(int img_show) {
this.img_show = img_show;
}
public String getTv_show() {
return tv_show;
}
public void setTv_show(String tv_show) {
this.tv_show = tv_show;
}
}
| 1,733 | 0.601847 | 0.597807 | 78 | 21.217949 | 21.280573 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525641 | false | false |
12
|
6bdb598d576cea9b639251f3a25134cc0ef0b78f
| 30,975,304,188,529 |
8af1164bac943cef64e41bae312223c3c0e38114
|
/results-java/neo4j--neo4j/38a416c51e00198ebdc55364b8de8d59fdf14d0a/before/CacheBean.java
|
37c4013ab597b69c9cc5abdb192ba0e16be33eb9
|
[] |
no_license
|
fracz/refactor-extractor
|
https://github.com/fracz/refactor-extractor
|
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
|
dd5e82bfcc376e74a99e18c2bf54c95676914272
|
refs/heads/master
| 2021-01-19T06:50:08.211000 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.neo4j.kernel.impl.management;
import java.security.AccessControlException;
import javax.management.MBeanOperationInfo;
import javax.management.NotCompliantMBeanException;
import org.neo4j.kernel.impl.core.NodeManager;
import org.neo4j.kernel.management.Cache;
@Description( "Information about the caching in Neo4j" )
class CacheBean extends Neo4jMBean implements Cache
{
private final NodeManager nodeManager;
CacheBean( int instanceId, NodeManager nodeManager ) throws NotCompliantMBeanException
{
super( instanceId, Cache.class );
this.nodeManager = nodeManager;
}
@Description( "The type of cache used by Neo4j" )
public String getCacheType()
{
return nodeManager.isUsingSoftReferenceCache() ? "soft reference cache" : "lru cache";
}
@Description( "The number of Nodes currently in cache" )
public int getNodeCacheSize()
{
return nodeManager.getNodeCacheSize();
}
@Description( "The number of Relationships currently in cache" )
public int getRelationshipCacheSize()
{
return nodeManager.getRelationshipCacheSize();
}
@Description( value = "Clears the Neo4j caches", impact = MBeanOperationInfo.ACTION )
public void clear()
{
if ( true )
throw new AccessControlException( "Clearing cache through JMX not permitted." );
nodeManager.clearCache();
}
}
|
UTF-8
|
Java
| 1,420 |
java
|
CacheBean.java
|
Java
|
[] | null |
[] |
package org.neo4j.kernel.impl.management;
import java.security.AccessControlException;
import javax.management.MBeanOperationInfo;
import javax.management.NotCompliantMBeanException;
import org.neo4j.kernel.impl.core.NodeManager;
import org.neo4j.kernel.management.Cache;
@Description( "Information about the caching in Neo4j" )
class CacheBean extends Neo4jMBean implements Cache
{
private final NodeManager nodeManager;
CacheBean( int instanceId, NodeManager nodeManager ) throws NotCompliantMBeanException
{
super( instanceId, Cache.class );
this.nodeManager = nodeManager;
}
@Description( "The type of cache used by Neo4j" )
public String getCacheType()
{
return nodeManager.isUsingSoftReferenceCache() ? "soft reference cache" : "lru cache";
}
@Description( "The number of Nodes currently in cache" )
public int getNodeCacheSize()
{
return nodeManager.getNodeCacheSize();
}
@Description( "The number of Relationships currently in cache" )
public int getRelationshipCacheSize()
{
return nodeManager.getRelationshipCacheSize();
}
@Description( value = "Clears the Neo4j caches", impact = MBeanOperationInfo.ACTION )
public void clear()
{
if ( true )
throw new AccessControlException( "Clearing cache through JMX not permitted." );
nodeManager.clearCache();
}
}
| 1,420 | 0.71338 | 0.708451 | 47 | 29.234043 | 28.363306 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361702 | false | false |
12
|
f77b96ec2ae272c4096b7bccd2e9564266502a16
| 30,975,304,191,142 |
a6e9ec1d2aac6e905431ce7f40a8bd2aafe986d6
|
/src/jianzhioffer/Test20.java
|
5865d52c2162818a4190ff761d3ad57682230723
|
[] |
no_license
|
zengge6668/AlgorithemCode
|
https://github.com/zengge6668/AlgorithemCode
|
986b59e5aece6691a062c18cf06bb2ea19365420
|
661e9c4f3cc849d3b79a23227ec5d102de365296
|
refs/heads/master
| 2021-05-14T23:53:07.144000 | 2019-11-03T04:27:13 | 2019-11-03T04:27:13 | 104,063,219 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package jianzhioffer;
/**
* Created by admin on 2017/10/5.
*/
public class Test20 {
public void printMatrixClockWisely(int[][] numbers) {
if (numbers == null || numbers.length <= 0 || numbers[0].length <= 0)
return;
;
int x = 0; //记录一圈的开始位置的行
int y = 0; // 记录一圈开始位置的列
int maxrow = (numbers.length - 1) / 2; //圈开始的行号的最大值
int maxcol = (numbers[0].length - 1) / 2; //圈开始的列号的最大值
while (x <= maxrow && y <= maxcol) {
printMatrixInCircle(numbers, x, y);
x++;
y++;
}
}
public void printMatrixInCircle(int[][] numbers, int x, int y) {
int row = numbers.length;
int col = numbers[0].length;
//输出环的上一行
for (int i = y; i <= col - y - 1; i++) {
System.out.print(numbers[x][i] + " ");
}
//环的高度至少为2才输出右边一列
// rows-x-1:表示的是环最下的那一行的行号
if (row - x - 1 > x) {
for (int i = x + 1; i <= row - x - 1; i++) {
System.out.print(numbers[i][col - y - 1] + " ");
}
}
// 环的高度至少是2并且环的宽度至少是2才会输出下面那一行
// cols-1-y:表示的是环最右那一列的列号
if (row - x - 1 > x && col - 1 - y > y) {
for (int i = col - y - 2; i >= y; i--) {
System.out.print(numbers[row - 1 - x][i] + " ");
}
}
// 环的宽度至少是2并且环的高度至少是3才会输出最左边那一列
// rows-x-1:表示的是环最下的那一行的行号
if (col - 1 - y > y && row - 1 - x > x + 1) {
// 因为最左边那一列的第一个和最后一个已经被输出了
for (int i = row - 1 - x - 1; i >= x + 1; i--) {
System.out.print(numbers[i][y] + " ");
}
}
}
}
|
UTF-8
|
Java
| 2,035 |
java
|
Test20.java
|
Java
|
[
{
"context": "package jianzhioffer;\n\n/**\n * Created by admin on 2017/10/5.\n */\npublic class Test20 {\n publi",
"end": 46,
"score": 0.9969694018363953,
"start": 41,
"tag": "USERNAME",
"value": "admin"
}
] | null |
[] |
package jianzhioffer;
/**
* Created by admin on 2017/10/5.
*/
public class Test20 {
public void printMatrixClockWisely(int[][] numbers) {
if (numbers == null || numbers.length <= 0 || numbers[0].length <= 0)
return;
;
int x = 0; //记录一圈的开始位置的行
int y = 0; // 记录一圈开始位置的列
int maxrow = (numbers.length - 1) / 2; //圈开始的行号的最大值
int maxcol = (numbers[0].length - 1) / 2; //圈开始的列号的最大值
while (x <= maxrow && y <= maxcol) {
printMatrixInCircle(numbers, x, y);
x++;
y++;
}
}
public void printMatrixInCircle(int[][] numbers, int x, int y) {
int row = numbers.length;
int col = numbers[0].length;
//输出环的上一行
for (int i = y; i <= col - y - 1; i++) {
System.out.print(numbers[x][i] + " ");
}
//环的高度至少为2才输出右边一列
// rows-x-1:表示的是环最下的那一行的行号
if (row - x - 1 > x) {
for (int i = x + 1; i <= row - x - 1; i++) {
System.out.print(numbers[i][col - y - 1] + " ");
}
}
// 环的高度至少是2并且环的宽度至少是2才会输出下面那一行
// cols-1-y:表示的是环最右那一列的列号
if (row - x - 1 > x && col - 1 - y > y) {
for (int i = col - y - 2; i >= y; i--) {
System.out.print(numbers[row - 1 - x][i] + " ");
}
}
// 环的宽度至少是2并且环的高度至少是3才会输出最左边那一列
// rows-x-1:表示的是环最下的那一行的行号
if (col - 1 - y > y && row - 1 - x > x + 1) {
// 因为最左边那一列的第一个和最后一个已经被输出了
for (int i = row - 1 - x - 1; i >= x + 1; i--) {
System.out.print(numbers[i][y] + " ");
}
}
}
}
| 2,035 | 0.443582 | 0.41791 | 54 | 30.018518 | 21.575441 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false |
12
|
1a4cf3317f2789cba3532518cb43460561e25682
| 12,575,664,304,853 |
343c25d78c83f09c0da412160cce110627ae5ea4
|
/app/src/main/java/pl/edu/pwr/wiz/wzorlaboratorium8/BatteryLevelReceiver.java
|
55e02cb8547b8abdd05e66254941633db56986db
|
[
"Apache-2.0"
] |
permissive
|
AndroidPWR/laboratorium-8-Dargielen
|
https://github.com/AndroidPWR/laboratorium-8-Dargielen
|
e5668d9f9883a48ba0fd8553f991874c1abda723
|
c44ac729a9af1baff691062bbea6d6264d7ee672
|
refs/heads/master
| 2017-12-04T11:48:37.698000 | 2017-02-28T19:36:01 | 2017-02-28T19:36:01 | 83,203,400 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.edu.pwr.wiz.wzorlaboratorium8;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by dargielen on 26.02.2017.
*/
public class BatteryLevelReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BATTERY_LOW")) {
Toast.makeText(context, "Podłącz ładowarkę", Toast.LENGTH_LONG).show();
}
}
}
|
UTF-8
|
Java
| 545 |
java
|
BatteryLevelReceiver.java
|
Java
|
[
{
"context": "t;\nimport android.widget.Toast;\n\n/**\n * Created by dargielen on 26.02.2017.\n */\n\npublic class BatteryLevelRece",
"end": 205,
"score": 0.9905358552932739,
"start": 196,
"tag": "USERNAME",
"value": "dargielen"
}
] | null |
[] |
package pl.edu.pwr.wiz.wzorlaboratorium8;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by dargielen on 26.02.2017.
*/
public class BatteryLevelReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BATTERY_LOW")) {
Toast.makeText(context, "Podłącz ładowarkę", Toast.LENGTH_LONG).show();
}
}
}
| 545 | 0.724584 | 0.707948 | 20 | 26.049999 | 26.380817 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false |
12
|
b8df134a334c330df03d0b2fbb99fe198e94af27
| 28,819,230,616,108 |
ef4c4bcf490910b4127cf912b772779689bb71f1
|
/src/cn/com/pso/dao/impl/BaseDao.java
|
1b1f5dd8cd23dd842e04668f0d24c4e7efa712af
|
[] |
no_license
|
liu412825long/petsonline
|
https://github.com/liu412825long/petsonline
|
143a3488a4ccd08c24285559c04d1086f610f863
|
9a3b1380dc17b1c343907c21dbc03c7902a82037
|
refs/heads/master
| 2021-01-01T05:29:02.896000 | 2016-06-03T05:22:29 | 2016-06-03T05:22:29 | 59,089,409 | 0 | 1 | null | false | 2016-05-24T11:06:49 | 2016-05-18T06:48:32 | 2016-05-18T06:52:36 | 2016-05-18T08:52:03 | 22,322 | 0 | 1 | 1 |
Java
| null | null |
package cn.com.pso.dao.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import cn.com.pso.dao.IBaseDao;
import cn.com.pso.util.PageBean;
public class BaseDao<T> implements IBaseDao<T> {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return sessionFactory.getCurrentSession();
}
public Integer add(Object obj) {
Session session = getSession();
return (Integer) session.save(obj);
}
public void update(Object obj) {
Session session = getSession();
session.update(obj);
}
public Object load(Class<?> clz, Integer id) {
Session session = getSession();
Object obj = session.get(clz, id);
return obj;
}
public void delete(Class<?> clz, Integer id) {
Session session = getSession();
session.delete(this.load(clz, id));
}
/**
* 查询 无条件
* @param hql
* @return
*/
public List<T> list(String hql) {
return this.list(hql, null);
}
/**
* 查询 唯一条件
* @param hql
* @param obj
* @return
*/
public List<T> list(String hql, Object obj) {
return this.list(hql, new Object[]{obj});
}
/**
* 查询 多条件
* @param hql
* @param objs
* @return
*/
@SuppressWarnings("unchecked")
public List<T> list(String hql, Object[] objs) {
Session session = getSession();
Query query = session.createQuery(hql);
this.setParameter(query, objs);
List<T> list = query.list();
return list;
}
/**
* 分页查询 多条件
* @param hql
* @param objs
* @param pageBean
* @return
*/
@SuppressWarnings("unchecked")
public PageBean page(String hql, Object[] objs, PageBean pageBean) {// from UserInfo where u.userName=? and u.sex=?
Session session = getSession();
Query query = session.createQuery(hql);
this.setParameter(query, objs);
query.setFirstResult((pageBean.getCurrentPage() - 1) * pageBean.getPageSize());
query.setMaxResults(pageBean.getPageSize());
pageBean.setList(query.list());
String countHql = getHQLCount(hql);
Integer total = Integer.parseInt(String.valueOf(session.createQuery(countHql).uniqueResult()));
pageBean.setTotal(total);
return pageBean;
}
public int getTotalPage(String hql,int pageSize)
{
String countHql = getHQLCount(hql);
Session session = getSession();
Integer total = Integer.parseInt(String.valueOf(session.createQuery(countHql).uniqueResult()));
int totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
return totalPage;
}
private String getHQLCount(String hql) {
String s = hql.substring(0, hql.indexOf("from")); //select u.userName u.sex
if(s.equals("")) {
hql = "select count(*) " + hql;
} else {
hql = hql.replace(s, "select count(*) ");
}
return hql;
}
private void setParameter(Query query, Object[] objs) {
if(objs != null && objs.length > 0) {
for(int i = 0; i < objs.length; i ++) {
query.setParameter(i, objs[i]);
}
}
}
}
|
UTF-8
|
Java
| 3,356 |
java
|
BaseDao.java
|
Java
|
[] | null |
[] |
package cn.com.pso.dao.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import cn.com.pso.dao.IBaseDao;
import cn.com.pso.util.PageBean;
public class BaseDao<T> implements IBaseDao<T> {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return sessionFactory.getCurrentSession();
}
public Integer add(Object obj) {
Session session = getSession();
return (Integer) session.save(obj);
}
public void update(Object obj) {
Session session = getSession();
session.update(obj);
}
public Object load(Class<?> clz, Integer id) {
Session session = getSession();
Object obj = session.get(clz, id);
return obj;
}
public void delete(Class<?> clz, Integer id) {
Session session = getSession();
session.delete(this.load(clz, id));
}
/**
* 查询 无条件
* @param hql
* @return
*/
public List<T> list(String hql) {
return this.list(hql, null);
}
/**
* 查询 唯一条件
* @param hql
* @param obj
* @return
*/
public List<T> list(String hql, Object obj) {
return this.list(hql, new Object[]{obj});
}
/**
* 查询 多条件
* @param hql
* @param objs
* @return
*/
@SuppressWarnings("unchecked")
public List<T> list(String hql, Object[] objs) {
Session session = getSession();
Query query = session.createQuery(hql);
this.setParameter(query, objs);
List<T> list = query.list();
return list;
}
/**
* 分页查询 多条件
* @param hql
* @param objs
* @param pageBean
* @return
*/
@SuppressWarnings("unchecked")
public PageBean page(String hql, Object[] objs, PageBean pageBean) {// from UserInfo where u.userName=? and u.sex=?
Session session = getSession();
Query query = session.createQuery(hql);
this.setParameter(query, objs);
query.setFirstResult((pageBean.getCurrentPage() - 1) * pageBean.getPageSize());
query.setMaxResults(pageBean.getPageSize());
pageBean.setList(query.list());
String countHql = getHQLCount(hql);
Integer total = Integer.parseInt(String.valueOf(session.createQuery(countHql).uniqueResult()));
pageBean.setTotal(total);
return pageBean;
}
public int getTotalPage(String hql,int pageSize)
{
String countHql = getHQLCount(hql);
Session session = getSession();
Integer total = Integer.parseInt(String.valueOf(session.createQuery(countHql).uniqueResult()));
int totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
return totalPage;
}
private String getHQLCount(String hql) {
String s = hql.substring(0, hql.indexOf("from")); //select u.userName u.sex
if(s.equals("")) {
hql = "select count(*) " + hql;
} else {
hql = hql.replace(s, "select count(*) ");
}
return hql;
}
private void setParameter(Query query, Object[] objs) {
if(objs != null && objs.length > 0) {
for(int i = 0; i < objs.length; i ++) {
query.setParameter(i, objs[i]);
}
}
}
}
| 3,356 | 0.63565 | 0.633837 | 149 | 20.214766 | 22.24439 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.838926 | false | false |
12
|
3c676db897265f5e9f3a658c796a60bfbdb297bb
| 3,624,952,465,123 |
a6ac3b940111f1626cadce7fe2042db68c9145f2
|
/src/apps/window/util/tableModelUtil/WindowTableModelMappingTableModelUtil.java
|
80fcc100bddb4539912611b43f9bd0a58a9af299
|
[] |
no_license
|
yogi15/development
|
https://github.com/yogi15/development
|
fee89cb8b9f3cae35c95b6d00c562de303c5078a
|
d9f38613b6059e7124a3ae80585bcdf9881e790d
|
refs/heads/master
| 2021-01-21T12:58:47.058000 | 2016-04-27T09:18:28 | 2016-04-27T09:18:28 | 55,207,648 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package apps.window.util.tableModelUtil;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import beans.WindowTableModelMapping;
public class WindowTableModelMappingTableModelUtil extends AbstractTableModel {
final String[] columnNames;
String col[] = { "WindowName", "BeanName", "ColumnName", "MethodName","DisplayName","ColumnClassType"};
/**
* @return the col
*/
public String[] getCol() {
return col;
}
/**
* @return the data
*/
public Vector<WindowTableModelMapping> getData() {
return mydata;
}
final Vector<WindowTableModelMapping> mydata;
public WindowTableModelMappingTableModelUtil(
Vector<WindowTableModelMapping> data) {
this.columnNames = col;
this.mydata = data;
}
public WindowTableModelMappingTableModelUtil(
Vector<WindowTableModelMapping> data, String[] col) {
this.columnNames = col;
this.mydata = data;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return mydata.size();
}
public WindowTableModelMapping getRow(int i) {
return mydata.get(i);
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
Object value = null;
WindowTableModelMapping windowtablemodelmapping = (WindowTableModelMapping) mydata
.get(row);
switch (col) {
case 0:
value = windowtablemodelmapping.getWindowName();
break;
case 1:
value = windowtablemodelmapping.getBeanName();
break;
case 2:
value = windowtablemodelmapping.getColumnName();
break;
case 3:
value = windowtablemodelmapping.getMethodName();
break;
case 4:
value = windowtablemodelmapping.getColumnDisplayName();
break;
case 5:
value = windowtablemodelmapping.getColumnDataType();
break;
}
return value;
}
public boolean isCellEditable(int row, int col) {
return false;
}
public void setValueAt(Object value, int row, int col) {
if (value instanceof WindowTableModelMapping) {
mydata.set(row, (WindowTableModelMapping) value);
this.fireTableDataChanged();
}
}
public void clear() {
mydata.clear();
this.fireTableDataChanged();
}
public void addRow(Object value) {
mydata.add((WindowTableModelMapping) value);
this.fireTableDataChanged();
}
public void delRow(int row) {
mydata.remove(row);
this.fireTableDataChanged();
}
public void udpateValueAt(Object value, int row, int col) {
mydata.set(row, (WindowTableModelMapping) value);
fireTableCellUpdated(row, col);
}
}
|
UTF-8
|
Java
| 2,630 |
java
|
WindowTableModelMappingTableModelUtil.java
|
Java
|
[] | null |
[] |
package apps.window.util.tableModelUtil;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import beans.WindowTableModelMapping;
public class WindowTableModelMappingTableModelUtil extends AbstractTableModel {
final String[] columnNames;
String col[] = { "WindowName", "BeanName", "ColumnName", "MethodName","DisplayName","ColumnClassType"};
/**
* @return the col
*/
public String[] getCol() {
return col;
}
/**
* @return the data
*/
public Vector<WindowTableModelMapping> getData() {
return mydata;
}
final Vector<WindowTableModelMapping> mydata;
public WindowTableModelMappingTableModelUtil(
Vector<WindowTableModelMapping> data) {
this.columnNames = col;
this.mydata = data;
}
public WindowTableModelMappingTableModelUtil(
Vector<WindowTableModelMapping> data, String[] col) {
this.columnNames = col;
this.mydata = data;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return mydata.size();
}
public WindowTableModelMapping getRow(int i) {
return mydata.get(i);
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
Object value = null;
WindowTableModelMapping windowtablemodelmapping = (WindowTableModelMapping) mydata
.get(row);
switch (col) {
case 0:
value = windowtablemodelmapping.getWindowName();
break;
case 1:
value = windowtablemodelmapping.getBeanName();
break;
case 2:
value = windowtablemodelmapping.getColumnName();
break;
case 3:
value = windowtablemodelmapping.getMethodName();
break;
case 4:
value = windowtablemodelmapping.getColumnDisplayName();
break;
case 5:
value = windowtablemodelmapping.getColumnDataType();
break;
}
return value;
}
public boolean isCellEditable(int row, int col) {
return false;
}
public void setValueAt(Object value, int row, int col) {
if (value instanceof WindowTableModelMapping) {
mydata.set(row, (WindowTableModelMapping) value);
this.fireTableDataChanged();
}
}
public void clear() {
mydata.clear();
this.fireTableDataChanged();
}
public void addRow(Object value) {
mydata.add((WindowTableModelMapping) value);
this.fireTableDataChanged();
}
public void delRow(int row) {
mydata.remove(row);
this.fireTableDataChanged();
}
public void udpateValueAt(Object value, int row, int col) {
mydata.set(row, (WindowTableModelMapping) value);
fireTableCellUpdated(row, col);
}
}
| 2,630 | 0.695057 | 0.692776 | 113 | 21.274336 | 21.735844 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.884956 | false | false |
12
|
3ab15a16521b3dfab8d5917ba49e747c2c9eed69
| 8,778,913,155,736 |
1ac6921344ecfd1e0c3c237b51953c4123ed29c4
|
/src/main/java/bio/chat/server/Server.java
|
0f2b19186ed8d07d71e67ba280c8cde967e78d0c
|
[] |
no_license
|
EnochStar/BIO_NIO_AIO
|
https://github.com/EnochStar/BIO_NIO_AIO
|
9746d6c04208f1857f970f82ffc01de129694b36
|
aa5e3a6dde2ef35da58453c71d23a1388178d2bd
|
refs/heads/master
| 2023-06-28T12:14:43.174000 | 2021-07-26T10:57:39 | 2021-07-26T10:57:39 | 386,566,792 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bio.chat.server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Package:bio.chat.server
* Description:
* 用于接收用户连接
* @author:鲍嘉鑫
*/
public class Server {
private static final int DEFAULT_PORT = 8888;
private static final String QUIT = "quit";
private ExecutorService executorService;
private static Map<Integer, Writer> clientMap;
private ServerSocket server;
// 初始化
public Server() {
clientMap = new HashMap<Integer, Writer>();
executorService = Executors.newFixedThreadPool(10);
}
// 用户连入
// synchronized 防止map导致的线程不安全
public synchronized void addClient(Socket socket) throws IOException {
int port = socket.getPort();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
clientMap.put(port,writer);
System.out.println("客户端:" + port + "已接入连接" );
}
// 用户退出
public synchronized void removeClient(Socket socket) throws IOException {
if (socket != null) {
int port = socket.getPort();
clientMap.get(port).close();
System.out.println("客户端:" + socket.getRemoteSocketAddress() + "退出");
}
}
// 准备退出
public boolean readyQuit(String msg) {
return Objects.equals(msg,QUIT);
}
public synchronized void close(ServerSocket server) {
try {
if (server != null) {
server.close();
System.out.println("服务器关闭");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
try {
server = new ServerSocket(DEFAULT_PORT);
System.out.println("启动服务器");
while (true) {
Socket client = server.accept();
// ChatHandler 负责对应的客户端并转发
executorService.execute(new ChatHandler(client,this));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(server);
}
}
public synchronized void forwardMsg(Socket socket,String msg) throws IOException {
for (int port : clientMap.keySet()) {
if (port != socket.getPort()) {
Writer writer = clientMap.get(port);
writer.write(msg);
writer.flush();
}
}
}
public static void main(String[] args) {
Server server = new Server();
server.start();
}
}
|
UTF-8
|
Java
| 2,830 |
java
|
Server.java
|
Java
|
[
{
"context": "hat.server\n * Description:\n * 用于接收用户连接\n * @author:鲍嘉鑫\n */\npublic class Server {\n\n private static fin",
"end": 330,
"score": 0.9998389482498169,
"start": 327,
"tag": "NAME",
"value": "鲍嘉鑫"
}
] | null |
[] |
package bio.chat.server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Package:bio.chat.server
* Description:
* 用于接收用户连接
* @author:鲍嘉鑫
*/
public class Server {
private static final int DEFAULT_PORT = 8888;
private static final String QUIT = "quit";
private ExecutorService executorService;
private static Map<Integer, Writer> clientMap;
private ServerSocket server;
// 初始化
public Server() {
clientMap = new HashMap<Integer, Writer>();
executorService = Executors.newFixedThreadPool(10);
}
// 用户连入
// synchronized 防止map导致的线程不安全
public synchronized void addClient(Socket socket) throws IOException {
int port = socket.getPort();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
clientMap.put(port,writer);
System.out.println("客户端:" + port + "已接入连接" );
}
// 用户退出
public synchronized void removeClient(Socket socket) throws IOException {
if (socket != null) {
int port = socket.getPort();
clientMap.get(port).close();
System.out.println("客户端:" + socket.getRemoteSocketAddress() + "退出");
}
}
// 准备退出
public boolean readyQuit(String msg) {
return Objects.equals(msg,QUIT);
}
public synchronized void close(ServerSocket server) {
try {
if (server != null) {
server.close();
System.out.println("服务器关闭");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
try {
server = new ServerSocket(DEFAULT_PORT);
System.out.println("启动服务器");
while (true) {
Socket client = server.accept();
// ChatHandler 负责对应的客户端并转发
executorService.execute(new ChatHandler(client,this));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(server);
}
}
public synchronized void forwardMsg(Socket socket,String msg) throws IOException {
for (int port : clientMap.keySet()) {
if (port != socket.getPort()) {
Writer writer = clientMap.get(port);
writer.write(msg);
writer.flush();
}
}
}
public static void main(String[] args) {
Server server = new Server();
server.start();
}
}
| 2,830 | 0.586746 | 0.584512 | 91 | 28.516483 | 21.536762 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483516 | false | false |
12
|
c685dc080c86e8593a6bf7cef2cf36cf23c75894
| 17,343,077,944,328 |
2f696123046cb0672c303936b99cbb85e0c7dd55
|
/cdi-container-api/src/main/java/com/essaid/cdi/BeanManagerExt.java
|
3e754f167c25c8f74fffe21dcfb25ad2cdac6584
|
[] |
no_license
|
ShahimEssaid/cdi-container
|
https://github.com/ShahimEssaid/cdi-container
|
5700050625c8ba9f798ab930fd1531a913f04dea
|
b950730f8e926d55695095a343c166a67b700b9b
|
HEAD
| 2016-09-15T03:49:34.264000 | 2016-02-29T21:40:03 | 2016-02-29T21:40:03 | 51,662,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*
*/
package com.essaid.cdi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanAttributes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionTargetFactory;
import javax.enterprise.inject.spi.ProducerFactory;
import com.essaid.cdi.bean.BeanFormatter;
import com.essaid.cdi.utils.ObjectFormatter;
import com.essaid.cmc.CCProvider;
/**
* @author "Shahim Essaid"
*
*/
public interface BeanManagerExt extends BeanManager {
/*
* (non-Javadoc)
*
* @see javax.enterprise.inject.spi.BeanManager#createBean(javax.enterprise.
* inject.spi.BeanAttributes, java.lang.Class,
* javax.enterprise.inject.spi.InjectionTargetFactory)
*/
@Override
default <T> BeanExt<T> createBean(BeanAttributes<T> attributes, Class<T> beanClass,
InjectionTargetFactory<T> injectionTargetFactory) {
Bean<T> bean = getWrappedManager().createBean(attributes, beanClass,
injectionTargetFactory);
return CCProvider.instance.wrapBean(bean, this);
}
/*
* (non-Javadoc)
*
* @see javax.enterprise.inject.spi.BeanManager#createBean(javax.enterprise.
* inject.spi.BeanAttributes, java.lang.Class,
* javax.enterprise.inject.spi.ProducerFactory)
*/
@Override
default <T, X> BeanExt<T> createBean(BeanAttributes<T> attributes, Class<X> beanClass,
ProducerFactory<X> producerFactory) {
Bean<T> bean = getWrappedManager().createBean(attributes, beanClass, producerFactory);
return CCProvider.instance.wrapBean(bean, this);
}
default Set<BeanExt<?>> getBeanExts(String name) {
Set<BeanExt<?>> beans = new HashSet<>();
for (Bean<?> bean : getWrappedManager().getBeans(name)) {
beans.add(CCProvider.instance.wrapBean(bean, this));
}
return beans;
}
default Set<BeanExt<?>> getBeanExts(Type beanType, Annotation... qualifiers) {
Set<BeanExt<?>> beans = new HashSet<>();
for (Bean<?> bean : getWrappedManager().getBeans(beanType, qualifiers)) {
beans.add(CCProvider.instance.wrapBean(bean, this));
}
return beans;
}
BeanFormatter getBeanFormatter();
// overrides
ObjectFormatter getObjectFormatter();
/*
* (non-Javadoc)
*
* @see
* javax.enterprise.inject.spi.BeanManager#getPassivationCapableBean(java.
* lang.String)
*/
@Override
default BeanExt<?> getPassivationCapableBean(String id) {
return CCProvider.instance.wrapBean(getWrappedManager().getPassivationCapableBean(id),
this);
}
BeanManager getWrappedManager();
boolean isExtensionBean(BeanExt<?> bean);
boolean isSystemBean(BeanExt<?> bean);
/*
* (non-Javadoc)
*
* @see javax.enterprise.inject.spi.BeanManager#resolve(java.util.Set)
*/
@Override
default <X> BeanExt<? extends X> resolve(Set<Bean<? extends X>> beans) {
return CCProvider.instance.wrapBean(getWrappedManager().resolve(beans), this);
}
void setBeanFormatter(BeanFormatter formatter);
void setObjectFormatter(ObjectFormatter formatter);
}
|
UTF-8
|
Java
| 3,343 |
java
|
BeanManagerExt.java
|
Java
|
[
{
"context": "mport com.essaid.cmc.CCProvider;\n\n/**\n * @author \"Shahim Essaid\"\n *\n */\npublic interface BeanManagerExt extends B",
"end": 560,
"score": 0.9998760223388672,
"start": 547,
"tag": "NAME",
"value": "Shahim Essaid"
}
] | null |
[] |
/**
*
*/
package com.essaid.cdi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanAttributes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionTargetFactory;
import javax.enterprise.inject.spi.ProducerFactory;
import com.essaid.cdi.bean.BeanFormatter;
import com.essaid.cdi.utils.ObjectFormatter;
import com.essaid.cmc.CCProvider;
/**
* @author "<NAME>"
*
*/
public interface BeanManagerExt extends BeanManager {
/*
* (non-Javadoc)
*
* @see javax.enterprise.inject.spi.BeanManager#createBean(javax.enterprise.
* inject.spi.BeanAttributes, java.lang.Class,
* javax.enterprise.inject.spi.InjectionTargetFactory)
*/
@Override
default <T> BeanExt<T> createBean(BeanAttributes<T> attributes, Class<T> beanClass,
InjectionTargetFactory<T> injectionTargetFactory) {
Bean<T> bean = getWrappedManager().createBean(attributes, beanClass,
injectionTargetFactory);
return CCProvider.instance.wrapBean(bean, this);
}
/*
* (non-Javadoc)
*
* @see javax.enterprise.inject.spi.BeanManager#createBean(javax.enterprise.
* inject.spi.BeanAttributes, java.lang.Class,
* javax.enterprise.inject.spi.ProducerFactory)
*/
@Override
default <T, X> BeanExt<T> createBean(BeanAttributes<T> attributes, Class<X> beanClass,
ProducerFactory<X> producerFactory) {
Bean<T> bean = getWrappedManager().createBean(attributes, beanClass, producerFactory);
return CCProvider.instance.wrapBean(bean, this);
}
default Set<BeanExt<?>> getBeanExts(String name) {
Set<BeanExt<?>> beans = new HashSet<>();
for (Bean<?> bean : getWrappedManager().getBeans(name)) {
beans.add(CCProvider.instance.wrapBean(bean, this));
}
return beans;
}
default Set<BeanExt<?>> getBeanExts(Type beanType, Annotation... qualifiers) {
Set<BeanExt<?>> beans = new HashSet<>();
for (Bean<?> bean : getWrappedManager().getBeans(beanType, qualifiers)) {
beans.add(CCProvider.instance.wrapBean(bean, this));
}
return beans;
}
BeanFormatter getBeanFormatter();
// overrides
ObjectFormatter getObjectFormatter();
/*
* (non-Javadoc)
*
* @see
* javax.enterprise.inject.spi.BeanManager#getPassivationCapableBean(java.
* lang.String)
*/
@Override
default BeanExt<?> getPassivationCapableBean(String id) {
return CCProvider.instance.wrapBean(getWrappedManager().getPassivationCapableBean(id),
this);
}
BeanManager getWrappedManager();
boolean isExtensionBean(BeanExt<?> bean);
boolean isSystemBean(BeanExt<?> bean);
/*
* (non-Javadoc)
*
* @see javax.enterprise.inject.spi.BeanManager#resolve(java.util.Set)
*/
@Override
default <X> BeanExt<? extends X> resolve(Set<Bean<? extends X>> beans) {
return CCProvider.instance.wrapBean(getWrappedManager().resolve(beans), this);
}
void setBeanFormatter(BeanFormatter formatter);
void setObjectFormatter(ObjectFormatter formatter);
}
| 3,336 | 0.676638 | 0.676638 | 112 | 28.848215 | 28.207525 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473214 | false | false |
12
|
77fe6e443561add30b4d886d772853eacd82f60d
| 21,345,987,463,509 |
1849c03498aa320c7136c0e71ba4da65eaf9ab3d
|
/atlasdb-impl-shared/src/main/java/com/palantir/atlasdb/sweep/queue/id/SweepTableIndices.java
|
7221c713d3739e9fe4e057e1360ab4d08b5bee6c
|
[
"Apache-2.0"
] |
permissive
|
palantir/atlasdb
|
https://github.com/palantir/atlasdb
|
894f3870337eeaf2408b2c9975a6166764491f4a
|
ad20d4b983edd808737f56d90d2e29a284e7bdd7
|
refs/heads/develop
| 2023-08-30T05:04:58.136000 | 2023-08-23T13:40:22 | 2023-08-23T13:40:22 | 36,960,637 | 914 | 224 |
Apache-2.0
| false | 2023-09-14T15:57:09 | 2015-06-05T23:42:44 | 2023-08-27T17:48:18 | 2023-09-14T15:57:08 | 111,291 | 22 | 1 | 370 |
Java
| false | false |
/*
* (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.sweep.queue.id;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.atlasdb.logging.LoggingArgs;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.util.NoSuchElementException;
import java.util.Optional;
/**
* Creates a dictionary of table references to shorter (integral) identifiers.
* <p>
* Algorithm is slightly more complicated than usual Atlas code because it cannot assume transactions. It works as
* follows.
* <p>
* 1. If table exists in NamesToIds and is 'identified', we are done.
* 2. If table is 'pending', take its id. Otherwise PutUnlessExists in the current highest known id + 1 in IdsToNames
* into the NamesToIds table. In case of failure, take the value that now must exist (and if now 'identified', we
* are done).
* 3. PutUnlessExists that value into IdsToNames. If success or it already existed with the same value, go to 4,
* otherwise 5.
* 4. CAS NamesToIds from 'pending' to 'identified'.
* 5. CAS NamesToIds from its current value to the current highest known id + 1; the current best candidate has been
* already used by a concurrent writer.
* <p>
*/
public final class SweepTableIndices {
private static final SafeLogger log = SafeLoggerFactory.get(SweepTableIndices.class);
private final IdsToNames idToNames;
private final NamesToIds namesToIds;
private final LoadingCache<TableReference, Integer> tableIndices;
private final LoadingCache<Integer, TableReference> tableRefs;
SweepTableIndices(IdsToNames idsToNames, NamesToIds namesToIds) {
this.idToNames = idsToNames;
this.namesToIds = namesToIds;
this.tableIndices = Caffeine.newBuilder().maximumSize(20_000).build(this::loadUncached);
this.tableRefs = Caffeine.newBuilder().maximumSize(20_000).build(this::getTableReferenceUncached);
}
public SweepTableIndices(KeyValueService kvs) {
this(new IdsToNames(kvs), new NamesToIds(kvs));
}
public int getTableId(TableReference table) {
return tableIndices.get(table);
}
public TableReference getTableReference(int tableId) {
return tableRefs.get(tableId);
}
private TableReference getTableReferenceUncached(int tableId) {
return idToNames
.get(tableId)
.orElseThrow(() -> new NoSuchElementException("Id " + tableId + " does not exist"));
}
private int loadUncached(TableReference table) {
while (true) {
Optional<SweepTableIdentifier> identifier = namesToIds.currentMapping(table);
if (identifier.isPresent() && !identifier.get().isPending()) {
return identifier.get().identifier();
}
log.info("Assigning table {} an identifier", LoggingArgs.tableRef(table));
// note - the second time through the loop this will fail, since on those iterations we're
// doing our updates as CAS (at the bottom) not PUE, but it doubles as a get
SweepTableIdentifier afterPendingPut = namesToIds.storeAsPending(table, idToNames.getNextId());
if (!afterPendingPut.isPending()) {
log.info(
"Assigned table {} to id {}",
LoggingArgs.tableRef(table),
SafeArg.of("id", afterPendingPut.identifier()));
return afterPendingPut.identifier();
}
boolean assigmentWasSuccessful = idToNames.storeNewMapping(table, afterPendingPut.identifier());
if (assigmentWasSuccessful) {
namesToIds.moveToComplete(table, afterPendingPut.identifier());
log.info(
"Assigned table {} to id {}",
LoggingArgs.tableRef(table),
SafeArg.of("id", afterPendingPut.identifier()));
return afterPendingPut.identifier();
}
// B
namesToIds.storeAsPending(table, afterPendingPut.identifier(), idToNames.getNextId());
}
}
}
|
UTF-8
|
Java
| 4,970 |
java
|
SweepTableIndices.java
|
Java
|
[
{
"context": "tir.atlasdb.sweep.queue.id;\n\nimport com.github.benmanes.caffeine.cache.Caffeine;\nimport com.github.benm",
"end": 705,
"score": 0.5612472891807556,
"start": 702,
"tag": "USERNAME",
"value": "man"
},
{
"context": "nes.caffeine.cache.Caffeine;\nimport com.github.benmanes.caffeine.cache.LoadingCache;\nimport com.palanti",
"end": 757,
"score": 0.6214200854301453,
"start": 754,
"tag": "USERNAME",
"value": "man"
}
] | null |
[] |
/*
* (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.sweep.queue.id;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.atlasdb.logging.LoggingArgs;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.util.NoSuchElementException;
import java.util.Optional;
/**
* Creates a dictionary of table references to shorter (integral) identifiers.
* <p>
* Algorithm is slightly more complicated than usual Atlas code because it cannot assume transactions. It works as
* follows.
* <p>
* 1. If table exists in NamesToIds and is 'identified', we are done.
* 2. If table is 'pending', take its id. Otherwise PutUnlessExists in the current highest known id + 1 in IdsToNames
* into the NamesToIds table. In case of failure, take the value that now must exist (and if now 'identified', we
* are done).
* 3. PutUnlessExists that value into IdsToNames. If success or it already existed with the same value, go to 4,
* otherwise 5.
* 4. CAS NamesToIds from 'pending' to 'identified'.
* 5. CAS NamesToIds from its current value to the current highest known id + 1; the current best candidate has been
* already used by a concurrent writer.
* <p>
*/
public final class SweepTableIndices {
private static final SafeLogger log = SafeLoggerFactory.get(SweepTableIndices.class);
private final IdsToNames idToNames;
private final NamesToIds namesToIds;
private final LoadingCache<TableReference, Integer> tableIndices;
private final LoadingCache<Integer, TableReference> tableRefs;
SweepTableIndices(IdsToNames idsToNames, NamesToIds namesToIds) {
this.idToNames = idsToNames;
this.namesToIds = namesToIds;
this.tableIndices = Caffeine.newBuilder().maximumSize(20_000).build(this::loadUncached);
this.tableRefs = Caffeine.newBuilder().maximumSize(20_000).build(this::getTableReferenceUncached);
}
public SweepTableIndices(KeyValueService kvs) {
this(new IdsToNames(kvs), new NamesToIds(kvs));
}
public int getTableId(TableReference table) {
return tableIndices.get(table);
}
public TableReference getTableReference(int tableId) {
return tableRefs.get(tableId);
}
private TableReference getTableReferenceUncached(int tableId) {
return idToNames
.get(tableId)
.orElseThrow(() -> new NoSuchElementException("Id " + tableId + " does not exist"));
}
private int loadUncached(TableReference table) {
while (true) {
Optional<SweepTableIdentifier> identifier = namesToIds.currentMapping(table);
if (identifier.isPresent() && !identifier.get().isPending()) {
return identifier.get().identifier();
}
log.info("Assigning table {} an identifier", LoggingArgs.tableRef(table));
// note - the second time through the loop this will fail, since on those iterations we're
// doing our updates as CAS (at the bottom) not PUE, but it doubles as a get
SweepTableIdentifier afterPendingPut = namesToIds.storeAsPending(table, idToNames.getNextId());
if (!afterPendingPut.isPending()) {
log.info(
"Assigned table {} to id {}",
LoggingArgs.tableRef(table),
SafeArg.of("id", afterPendingPut.identifier()));
return afterPendingPut.identifier();
}
boolean assigmentWasSuccessful = idToNames.storeNewMapping(table, afterPendingPut.identifier());
if (assigmentWasSuccessful) {
namesToIds.moveToComplete(table, afterPendingPut.identifier());
log.info(
"Assigned table {} to id {}",
LoggingArgs.tableRef(table),
SafeArg.of("id", afterPendingPut.identifier()));
return afterPendingPut.identifier();
}
// B
namesToIds.storeAsPending(table, afterPendingPut.identifier(), idToNames.getNextId());
}
}
}
| 4,970 | 0.683501 | 0.678068 | 109 | 44.596329 | 33.966557 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.59633 | false | false |
12
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.