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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d5af89ca233322d33e8d0c0eeb743ea4c14e04dc
| 31,421,980,774,824 |
6546b8da3ae1eb029093aef589088c16eb8d5a77
|
/src/math/Math01.java
|
c89f1b4c9d616e399a8bb680178e67d9382a3051
|
[] |
no_license
|
xiongyi1994/java_learning
|
https://github.com/xiongyi1994/java_learning
|
766e88507a3df21b17f016d9473c3d346173880b
|
06341bd1779db7d923b5e3744e9cdd467a495701
|
refs/heads/master
| 2021-07-15T00:20:46.872000 | 2021-07-07T02:43:39 | 2021-07-07T02:43:39 | 89,570,492 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package math;
public class Math01 {
/*
* Math类是数学操作类,提供了一系列的数学操作方法
* */
public static void main(String[] args) {
System.out.println(Math.pow(2, 2));
}
}
|
UTF-8
|
Java
| 205 |
java
|
Math01.java
|
Java
|
[] | null |
[] |
package math;
public class Math01 {
/*
* Math类是数学操作类,提供了一系列的数学操作方法
* */
public static void main(String[] args) {
System.out.println(Math.pow(2, 2));
}
}
| 205 | 0.656442 | 0.631902 | 10 | 15.3 | 14.866405 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
13
|
93076b1ec13ea05bfbd72362155b96fd1a91453f
| 26,362,509,322,145 |
e1a536b8e6545d05af1353f2b94c5b94d2643286
|
/domain/src/main/java/by/corrina/nsm/domain/usecase/BaseUseCase.java
|
9eb38b54bf90238e932d425741d5037f109f6c38
|
[] |
no_license
|
nsmapp/TradehelperforEVEOnline
|
https://github.com/nsmapp/TradehelperforEVEOnline
|
d0606d96212842e499ad0701d4962d54bf2c440e
|
db29a69050a1219d9b7cc67ad59a3be7721c49e2
|
refs/heads/master
| 2018-11-17T01:41:59.955000 | 2018-09-12T16:54:34 | 2018-09-12T16:54:34 | 146,496,023 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package by.corrina.nsm.domain.usecase;
import by.corrina.nsm.domain.executors.ExecutionThread;
import by.corrina.nsm.domain.executors.PostExecutionThread;
import io.reactivex.Scheduler;
import io.reactivex.schedulers.Schedulers;
public abstract class BaseUseCase {
protected Scheduler executionThread;
protected Scheduler postExecutionThread;
public BaseUseCase(Scheduler executionThread, Scheduler postExecutionThread) {
this.executionThread = executionThread;
this.postExecutionThread = postExecutionThread;
}
public BaseUseCase(ExecutionThread executionThread, PostExecutionThread postExecutionThread) {
this.executionThread = Schedulers.from(executionThread);
this.postExecutionThread = postExecutionThread.getScheduler();
}
public BaseUseCase(PostExecutionThread postExecutionThread) {
this.executionThread = Schedulers.io();
this.postExecutionThread = postExecutionThread.getScheduler();
}
}
|
UTF-8
|
Java
| 988 |
java
|
BaseUseCase.java
|
Java
|
[] | null |
[] |
package by.corrina.nsm.domain.usecase;
import by.corrina.nsm.domain.executors.ExecutionThread;
import by.corrina.nsm.domain.executors.PostExecutionThread;
import io.reactivex.Scheduler;
import io.reactivex.schedulers.Schedulers;
public abstract class BaseUseCase {
protected Scheduler executionThread;
protected Scheduler postExecutionThread;
public BaseUseCase(Scheduler executionThread, Scheduler postExecutionThread) {
this.executionThread = executionThread;
this.postExecutionThread = postExecutionThread;
}
public BaseUseCase(ExecutionThread executionThread, PostExecutionThread postExecutionThread) {
this.executionThread = Schedulers.from(executionThread);
this.postExecutionThread = postExecutionThread.getScheduler();
}
public BaseUseCase(PostExecutionThread postExecutionThread) {
this.executionThread = Schedulers.io();
this.postExecutionThread = postExecutionThread.getScheduler();
}
}
| 988 | 0.776316 | 0.776316 | 31 | 30.870968 | 29.94591 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483871 | false | false |
13
|
454b5f37a84d472d9ac4697d847165b69999a763
| 13,881,334,363,475 |
441b16d5861b8239644007c3b64d56bdfd67bb92
|
/plugins/org.eclipse.osee.framework.ui.skynet/src/org/eclipse/osee/framework/ui/skynet/blam/operation/ExampleOutputBlam.java
|
d2a5e117599b5f531cd324479d48d742971ce824
|
[] |
no_license
|
sec00/osee-4
|
https://github.com/sec00/osee-4
|
baf9713306c7bfd6f5a12a153acb083bbdb2ce77
|
4644522f12d0e2a887434d09dffa55d32ed45f15
|
refs/heads/master
| 2021-05-19T04:04:07.608000 | 2018-11-15T23:29:55 | 2018-11-15T23:31:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*******************************************************************************
* Copyright (c) 2014 Boeing.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Boeing - initial API and implementation
*******************************************************************************/
package org.eclipse.osee.framework.ui.skynet.blam.operation;
import java.util.Arrays;
import java.util.Collection;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.osee.framework.ui.skynet.blam.AbstractBlam;
import org.eclipse.osee.framework.ui.skynet.blam.VariableMap;
/**
* @author Donald G. Dunne
*/
public class ExampleOutputBlam extends AbstractBlam {
@Override
public String getName() {
return "Example Blam";
}
@Override
public void runOperation(VariableMap variableMap, IProgressMonitor monitor) throws Exception {
for (int x = 0; x < 100; x++) {
log("line number " + x + "\n");
}
}
@Override
public String getXWidgetsXml() {
// @formatter:off
return "<xWidgets>" +
"<XWidget xwidgetType=\"XCheckBox\" horizontalLabel=\"true\" labelAfter=\"true\" displayName=\"Body is html\" defaultValue=\"true\" />" +
"</xWidgets>";
// @formatter:on
}
@Override
public String getDescriptionUsage() {
return "Send individual emails to everyone in the selected groups with an unsubscribe option";
}
@Override
public Collection<String> getCategories() {
return Arrays.asList("Util");
}
}
|
UTF-8
|
Java
| 1,732 |
java
|
ExampleOutputBlam.java
|
Java
|
[
{
"context": ".org/legal/epl-v10.html\n *\n * Contributors:\n * Boeing - initial API and implementation\n ***************",
"end": 390,
"score": 0.9955868721008301,
"start": 384,
"tag": "NAME",
"value": "Boeing"
},
{
"context": "mework.ui.skynet.blam.VariableMap;\n\n/**\n * @author Donald G. Dunne\n */\npublic class ExampleOutputBlam extends Abstra",
"end": 828,
"score": 0.999768853187561,
"start": 813,
"tag": "NAME",
"value": "Donald G. Dunne"
}
] | null |
[] |
/*******************************************************************************
* Copyright (c) 2014 Boeing.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Boeing - initial API and implementation
*******************************************************************************/
package org.eclipse.osee.framework.ui.skynet.blam.operation;
import java.util.Arrays;
import java.util.Collection;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.osee.framework.ui.skynet.blam.AbstractBlam;
import org.eclipse.osee.framework.ui.skynet.blam.VariableMap;
/**
* @author <NAME>
*/
public class ExampleOutputBlam extends AbstractBlam {
@Override
public String getName() {
return "Example Blam";
}
@Override
public void runOperation(VariableMap variableMap, IProgressMonitor monitor) throws Exception {
for (int x = 0; x < 100; x++) {
log("line number " + x + "\n");
}
}
@Override
public String getXWidgetsXml() {
// @formatter:off
return "<xWidgets>" +
"<XWidget xwidgetType=\"XCheckBox\" horizontalLabel=\"true\" labelAfter=\"true\" displayName=\"Body is html\" defaultValue=\"true\" />" +
"</xWidgets>";
// @formatter:on
}
@Override
public String getDescriptionUsage() {
return "Send individual emails to everyone in the selected groups with an unsubscribe option";
}
@Override
public Collection<String> getCategories() {
return Arrays.asList("Util");
}
}
| 1,723 | 0.626443 | 0.619515 | 55 | 30.50909 | 30.959135 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.345455 | false | false |
13
|
b4c34fe7cae14306e6646cbd41a1176d5a7aadc3
| 22,050,362,167,924 |
61928fc99ec5fd73d083cf381617a28f78d832c3
|
/skysail.server.app.demo/src/io/skysail/server/app/demo/timetable/notifications/resources/PostCourseToNewNotificationRelationResource.java
|
a6d97832be8dd7159219952bbf669cb33fedc28d
|
[
"Apache-2.0"
] |
permissive
|
evandor/skysail
|
https://github.com/evandor/skysail
|
399af3c02449930f9082ffb52bd6fd720e3afc04
|
ca26e9b98e802111aa63a5edf719a331c0f6d062
|
refs/heads/master
| 2021-01-23T14:56:04.522000 | 2017-05-30T09:22:16 | 2017-05-30T09:22:16 | 54,588,839 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.skysail.server.app.demo.timetable.notifications.resources;
import java.util.List;
import io.skysail.api.links.Link;
import io.skysail.server.ResourceContextId;
import io.skysail.server.app.demo.DemoApplication;
import io.skysail.server.app.demo.timetable.course.Course;
import io.skysail.server.app.demo.timetable.course.resources.TimetablesCoursesResource;
import io.skysail.server.app.demo.timetable.notifications.Notification;
import io.skysail.server.app.demo.timetable.repo.TimetableRepository;
import io.skysail.server.app.demo.timetable.timetables.Timetable;
import io.skysail.server.app.demo.timetable.timetables.resources.TimetablesResource;
import io.skysail.server.restlet.resources.PostRelationResource2;
public class PostCourseToNewNotificationRelationResource extends PostRelationResource2<Notification> {
private DemoApplication app;
private String timetableId;
public PostCourseToNewNotificationRelationResource() {
addToContext(ResourceContextId.LINK_TITLE, "create new notification for this course");
}
@Override
protected void doInit() {
app = (DemoApplication) getApplication();
timetableId = getAttribute("id");
}
@Override
public Notification createEntityTemplate() {
return new Notification();
}
@Override
public void addEntity(Notification notification) {
Timetable timetable = app.getTtRepo().findOne(timetableId);
Course course = timetable.getCourse(getAttribute("courseId"));
course.addNotification(notification);
app.getTtRepo().save(timetable, getApplication().getApplicationModel());
}
@Override
public List<Link> getLinks() {
return super.getLinks(TimetablesCoursesResource.class, PostCourseToNewNotificationRelationResource.class);
}
@Override
public String redirectTo() {
return super.redirectTo(TimetablesResource.class);
}
}
|
UTF-8
|
Java
| 1,937 |
java
|
PostCourseToNewNotificationRelationResource.java
|
Java
|
[] | null |
[] |
package io.skysail.server.app.demo.timetable.notifications.resources;
import java.util.List;
import io.skysail.api.links.Link;
import io.skysail.server.ResourceContextId;
import io.skysail.server.app.demo.DemoApplication;
import io.skysail.server.app.demo.timetable.course.Course;
import io.skysail.server.app.demo.timetable.course.resources.TimetablesCoursesResource;
import io.skysail.server.app.demo.timetable.notifications.Notification;
import io.skysail.server.app.demo.timetable.repo.TimetableRepository;
import io.skysail.server.app.demo.timetable.timetables.Timetable;
import io.skysail.server.app.demo.timetable.timetables.resources.TimetablesResource;
import io.skysail.server.restlet.resources.PostRelationResource2;
public class PostCourseToNewNotificationRelationResource extends PostRelationResource2<Notification> {
private DemoApplication app;
private String timetableId;
public PostCourseToNewNotificationRelationResource() {
addToContext(ResourceContextId.LINK_TITLE, "create new notification for this course");
}
@Override
protected void doInit() {
app = (DemoApplication) getApplication();
timetableId = getAttribute("id");
}
@Override
public Notification createEntityTemplate() {
return new Notification();
}
@Override
public void addEntity(Notification notification) {
Timetable timetable = app.getTtRepo().findOne(timetableId);
Course course = timetable.getCourse(getAttribute("courseId"));
course.addNotification(notification);
app.getTtRepo().save(timetable, getApplication().getApplicationModel());
}
@Override
public List<Link> getLinks() {
return super.getLinks(TimetablesCoursesResource.class, PostCourseToNewNotificationRelationResource.class);
}
@Override
public String redirectTo() {
return super.redirectTo(TimetablesResource.class);
}
}
| 1,937 | 0.763036 | 0.762003 | 54 | 34.888889 | 31.748821 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
13
|
2708719279a197924a4eff4fa8ffdaa027d3cbb2
| 16,896,401,363,825 |
978b8276b13eca35ea0773259eb350e5d2baeca5
|
/reactor-core/src/main/java/reactor/core/publisher/BlockingSingleSubscriber.java
|
7adc8b52923e57d74809417c9906970a1eb5528e
|
[
"Apache-2.0"
] |
permissive
|
reactor/reactor-core
|
https://github.com/reactor/reactor-core
|
2ceddf1d7c9f834ed9bc000c778ec7509a53d18a
|
5553aa80137482ec26acb960f4d4f42b8a44da94
|
refs/heads/main
| 2023-08-31T02:58:34.058000 | 2023-08-17T11:11:46 | 2023-08-17T11:12:34 | 45,903,621 | 4,873 | 1,221 |
Apache-2.0
| false | 2023-09-12T14:36:17 | 2015-11-10T10:06:40 | 2023-09-12T09:41:17 | 2023-09-12T14:36:16 | 65,104 | 4,653 | 1,143 | 126 |
Java
| false | false |
/*
* Copyright (c) 2016-2023 VMware Inc. or its affiliates, 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.reactivestreams.Subscription;
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.core.scheduler.Schedulers;
import reactor.util.annotation.Nullable;
import reactor.util.context.Context;
/**
* @see <a href="https://github.com/reactor/reactive-streams-commons">https://github.com/reactor/reactive-streams-commons</a>
*/
abstract class BlockingSingleSubscriber<T> extends CountDownLatch
implements InnerConsumer<T>, Disposable {
T value;
Throwable error;
Subscription s;
final Context context;
volatile boolean cancelled;
BlockingSingleSubscriber(Context context) {
super(1);
this.context = context;
}
@Override
public final void onSubscribe(Subscription s) {
this.s = s;
if (!cancelled) {
s.request(Long.MAX_VALUE);
}
}
@Override
public final void onComplete() {
countDown();
}
@Override
public Context currentContext() {
return this.context;
}
@Override
public final void dispose() {
cancelled = true;
Subscription s = this.s;
if (s != null) {
this.s = null;
s.cancel();
}
}
/**
* Block until the first value arrives and return it, otherwise
* return null for an empty source and rethrow any exception.
*
* @return the first value or null if the source is empty
*/
@Nullable
final T blockingGet() {
if (Schedulers.isInNonBlockingThread()) {
throw new IllegalStateException("block()/blockFirst()/blockLast() are blocking, which is not supported in thread " + Thread.currentThread().getName());
}
if (getCount() != 0) {
try {
await();
}
catch (InterruptedException ex) {
dispose();
Thread.currentThread().interrupt();
throw Exceptions.propagate(ex);
}
}
Throwable e = error;
if (e != null) {
RuntimeException re = Exceptions.propagate(e);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block terminated with an error"));
throw re;
}
return value;
}
/**
* Block until the first value arrives and return it, otherwise
* return null for an empty source and rethrow any exception.
*
* @param timeout the timeout to wait
* @param unit the time unit
*
* @return the first value or null if the source is empty
*/
@Nullable
final T blockingGet(long timeout, TimeUnit unit) {
if (Schedulers.isInNonBlockingThread()) {
throw new IllegalStateException("block()/blockFirst()/blockLast() are blocking, which is not supported in thread " + Thread.currentThread().getName());
}
if (getCount() != 0) {
try {
if (!await(timeout, unit)) {
dispose();
throw new IllegalStateException("Timeout on blocking read for " + timeout + " " + unit);
}
}
catch (InterruptedException ex) {
dispose();
RuntimeException re = Exceptions.propagate(ex);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block has been interrupted"));
Thread.currentThread().interrupt();
throw re;
}
}
Throwable e = error;
if (e != null) {
RuntimeException re = Exceptions.propagate(e);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block terminated with an error"));
throw re;
}
return value;
}
@Override
@Nullable
public Object scanUnsafe(Attr key) {
if (key == Attr.TERMINATED) return getCount() == 0;
if (key == Attr.PARENT) return s;
if (key == Attr.CANCELLED) return cancelled;
if (key == Attr.ERROR) return error;
if (key == Attr.PREFETCH) return Integer.MAX_VALUE;
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
@Override
public boolean isDisposed() {
return cancelled || getCount() == 0;
}
}
|
UTF-8
|
Java
| 4,482 |
java
|
BlockingSingleSubscriber.java
|
Java
|
[] | null |
[] |
/*
* Copyright (c) 2016-2023 VMware Inc. or its affiliates, 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.reactivestreams.Subscription;
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.core.scheduler.Schedulers;
import reactor.util.annotation.Nullable;
import reactor.util.context.Context;
/**
* @see <a href="https://github.com/reactor/reactive-streams-commons">https://github.com/reactor/reactive-streams-commons</a>
*/
abstract class BlockingSingleSubscriber<T> extends CountDownLatch
implements InnerConsumer<T>, Disposable {
T value;
Throwable error;
Subscription s;
final Context context;
volatile boolean cancelled;
BlockingSingleSubscriber(Context context) {
super(1);
this.context = context;
}
@Override
public final void onSubscribe(Subscription s) {
this.s = s;
if (!cancelled) {
s.request(Long.MAX_VALUE);
}
}
@Override
public final void onComplete() {
countDown();
}
@Override
public Context currentContext() {
return this.context;
}
@Override
public final void dispose() {
cancelled = true;
Subscription s = this.s;
if (s != null) {
this.s = null;
s.cancel();
}
}
/**
* Block until the first value arrives and return it, otherwise
* return null for an empty source and rethrow any exception.
*
* @return the first value or null if the source is empty
*/
@Nullable
final T blockingGet() {
if (Schedulers.isInNonBlockingThread()) {
throw new IllegalStateException("block()/blockFirst()/blockLast() are blocking, which is not supported in thread " + Thread.currentThread().getName());
}
if (getCount() != 0) {
try {
await();
}
catch (InterruptedException ex) {
dispose();
Thread.currentThread().interrupt();
throw Exceptions.propagate(ex);
}
}
Throwable e = error;
if (e != null) {
RuntimeException re = Exceptions.propagate(e);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block terminated with an error"));
throw re;
}
return value;
}
/**
* Block until the first value arrives and return it, otherwise
* return null for an empty source and rethrow any exception.
*
* @param timeout the timeout to wait
* @param unit the time unit
*
* @return the first value or null if the source is empty
*/
@Nullable
final T blockingGet(long timeout, TimeUnit unit) {
if (Schedulers.isInNonBlockingThread()) {
throw new IllegalStateException("block()/blockFirst()/blockLast() are blocking, which is not supported in thread " + Thread.currentThread().getName());
}
if (getCount() != 0) {
try {
if (!await(timeout, unit)) {
dispose();
throw new IllegalStateException("Timeout on blocking read for " + timeout + " " + unit);
}
}
catch (InterruptedException ex) {
dispose();
RuntimeException re = Exceptions.propagate(ex);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block has been interrupted"));
Thread.currentThread().interrupt();
throw re;
}
}
Throwable e = error;
if (e != null) {
RuntimeException re = Exceptions.propagate(e);
//this is ok, as re is always a new non-singleton instance
re.addSuppressed(new Exception("#block terminated with an error"));
throw re;
}
return value;
}
@Override
@Nullable
public Object scanUnsafe(Attr key) {
if (key == Attr.TERMINATED) return getCount() == 0;
if (key == Attr.PARENT) return s;
if (key == Attr.CANCELLED) return cancelled;
if (key == Attr.ERROR) return error;
if (key == Attr.PREFETCH) return Integer.MAX_VALUE;
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
@Override
public boolean isDisposed() {
return cancelled || getCount() == 0;
}
}
| 4,482 | 0.695895 | 0.692102 | 169 | 25.52071 | 27.748892 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.852071 | false | false |
13
|
d00ae405f0f845a955db37882b7018820f19ba28
| 29,970,281,843,556 |
3c7d1a1d62c33c5d0f025bc7099f3e7dd89915cf
|
/Servidor/src/models/Conexao.java
|
324c8bb0302bbc57c231799a3bcebfd309cb41c4
|
[] |
no_license
|
marcosfeandrade/RedeSocial
|
https://github.com/marcosfeandrade/RedeSocial
|
7bcc8a31f0300af03658bf4a9c1a2726f4cd4121
|
285ee337713fed5a5ed68b619a1f4b7fb35c5679
|
refs/heads/main
| 2023-06-09T14:36:55.209000 | 2021-06-10T15:13:10 | 2021-06-10T15:13:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package models;
import controllers.ContaController;
import java.io.IOException;
import java.net.Socket;
public class Conexao implements Runnable {
private ConexaoUtils conexaoUtils;
public Conexao(Socket s) throws IOException {
this.conexaoUtils = new ConexaoUtils(s);
}
private void validarRequisicao() throws IOException, ClassNotFoundException {
Protocolo p = (Protocolo) conexaoUtils.receber();
if (p == null) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.INTERNAL_SERVER_ERRROR));
}
if (p.getUrl() == null || p.getUrl().isEmpty()) {
} else {
roteamento(p);
}
}
private void roteamento(Protocolo p) throws IOException {
if (isObjectNull(p)) {
return;
}
if (p.getUrl().equals("conta/cadastrar")) {
if (!(p.getObj() instanceof ContaAbstrata)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaAbstrata c = (ContaAbstrata) p.getObj();
ContaController.getInstance().cadastrar(conexaoUtils, c);
}
} else if (p.getUrl().equals("conta/logar")) {
if (!(p.getObj() instanceof ContaAbstrata)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().logar(conexaoUtils, (ContaAbstrata) p.getObj());
}
} else if (p.getUrl().equals("conta/adicionarAmigos")) {
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().adicionarAmigos(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if (p.getUrl().equals("conta/aceitarSolicitacaoAmigo")) {
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().aceitarSolicitacaoAmizade(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if (p.getUrl().equals("conta/getConvites")) {
if (!(p.getObj() instanceof String)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().getConvites(conexaoUtils,
(String) p.getObj());
}
} else if (p.getUrl().equals("conta/getRecados")) {
if (!(p.getObj() instanceof ContaAbstrata)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().getRecados(conexaoUtils,
(ContaAbstrata) p.getObj());
}
} else if (p.getUrl().equals("conta/enviarRecado")) {
if (!(p.getObj() instanceof EnvioRecado)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().enviarRecado(conexaoUtils,
(EnvioRecado) p.getObj());
}
} else if (p.getUrl().equals("conta/verificarAmigo")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().verificarAmigo(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if (p.getUrl().equals("conta/aceitarRecadoMural")){
if(!(p.getObj() instanceof RecadoMural)){
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().
aceitarRecadosMural(conexaoUtils,
(RecadoMural) p.getObj());
}
} else if (p.getUrl().equals("conta/adicionarMatch")) {
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().adicionarMatch(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/desativarConta")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().desativarConta(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/editarSenha")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().editarSenha(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/editarUsuario")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().editarUsuario(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/reativarConta")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().reativarConta(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/verOutroMural")){
if (!(p.getObj() instanceof String)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().getMural(conexaoUtils,
(String) p.getObj());
}
} /*else if(p.getUrl().equals("conta/getAlgumaCoisa")){
ContaController.getInstance().getAlgumaCoisa(conexaoUtils);
}*/
}
private boolean isObjectNull(Protocolo p) throws IOException {
if (p.getObj() == null) {
System.out.println("Envio de objeto vazio.");
//retorna via socket erro
conexaoUtils.enviar(new Protocolo(null, null, StatusCodigo.BAD_REQUEST));
return true;
}
return false;
}
@Override
public void run() {
try {
while (true) {
validarRequisicao();
}
} catch (IOException e) {
conexaoUtils.fecharConexao();
} catch (ClassNotFoundException e) {
conexaoUtils.fecharConexao();
}
}
}
|
UTF-8
|
Java
| 7,520 |
java
|
Conexao.java
|
Java
|
[] | null |
[] |
package models;
import controllers.ContaController;
import java.io.IOException;
import java.net.Socket;
public class Conexao implements Runnable {
private ConexaoUtils conexaoUtils;
public Conexao(Socket s) throws IOException {
this.conexaoUtils = new ConexaoUtils(s);
}
private void validarRequisicao() throws IOException, ClassNotFoundException {
Protocolo p = (Protocolo) conexaoUtils.receber();
if (p == null) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.INTERNAL_SERVER_ERRROR));
}
if (p.getUrl() == null || p.getUrl().isEmpty()) {
} else {
roteamento(p);
}
}
private void roteamento(Protocolo p) throws IOException {
if (isObjectNull(p)) {
return;
}
if (p.getUrl().equals("conta/cadastrar")) {
if (!(p.getObj() instanceof ContaAbstrata)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaAbstrata c = (ContaAbstrata) p.getObj();
ContaController.getInstance().cadastrar(conexaoUtils, c);
}
} else if (p.getUrl().equals("conta/logar")) {
if (!(p.getObj() instanceof ContaAbstrata)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().logar(conexaoUtils, (ContaAbstrata) p.getObj());
}
} else if (p.getUrl().equals("conta/adicionarAmigos")) {
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().adicionarAmigos(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if (p.getUrl().equals("conta/aceitarSolicitacaoAmigo")) {
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().aceitarSolicitacaoAmizade(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if (p.getUrl().equals("conta/getConvites")) {
if (!(p.getObj() instanceof String)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().getConvites(conexaoUtils,
(String) p.getObj());
}
} else if (p.getUrl().equals("conta/getRecados")) {
if (!(p.getObj() instanceof ContaAbstrata)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().getRecados(conexaoUtils,
(ContaAbstrata) p.getObj());
}
} else if (p.getUrl().equals("conta/enviarRecado")) {
if (!(p.getObj() instanceof EnvioRecado)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().enviarRecado(conexaoUtils,
(EnvioRecado) p.getObj());
}
} else if (p.getUrl().equals("conta/verificarAmigo")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().verificarAmigo(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if (p.getUrl().equals("conta/aceitarRecadoMural")){
if(!(p.getObj() instanceof RecadoMural)){
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().
aceitarRecadosMural(conexaoUtils,
(RecadoMural) p.getObj());
}
} else if (p.getUrl().equals("conta/adicionarMatch")) {
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().adicionarMatch(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/desativarConta")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().desativarConta(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/editarSenha")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().editarSenha(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/editarUsuario")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().editarUsuario(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/reativarConta")){
if (!(p.getObj() instanceof StringsDTO)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().reativarConta(conexaoUtils,
(StringsDTO) p.getObj());
}
} else if(p.getUrl().equals("conta/verOutroMural")){
if (!(p.getObj() instanceof String)) {
conexaoUtils.enviar(new Protocolo(null,
null, StatusCodigo.BAD_REQUEST));
} else {
ContaController.getInstance().getMural(conexaoUtils,
(String) p.getObj());
}
} /*else if(p.getUrl().equals("conta/getAlgumaCoisa")){
ContaController.getInstance().getAlgumaCoisa(conexaoUtils);
}*/
}
private boolean isObjectNull(Protocolo p) throws IOException {
if (p.getObj() == null) {
System.out.println("Envio de objeto vazio.");
//retorna via socket erro
conexaoUtils.enviar(new Protocolo(null, null, StatusCodigo.BAD_REQUEST));
return true;
}
return false;
}
@Override
public void run() {
try {
while (true) {
validarRequisicao();
}
} catch (IOException e) {
conexaoUtils.fecharConexao();
} catch (ClassNotFoundException e) {
conexaoUtils.fecharConexao();
}
}
}
| 7,520 | 0.523537 | 0.523537 | 179 | 41.005585 | 23.154448 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564246 | false | false |
13
|
b03f0c356b2712257cd7fcb2ae087c7130c8750b
| 25,606,595,037,818 |
0c4da2a6e15311fae265f9dce677825d0b19814e
|
/src/main/java/com/lgu/abc/core/plugin/ui/notification/counter/NotificationCounter.java
|
86dbf30359b442f3ba5203d605850fff9f908ef6
|
[] |
no_license
|
12bme/muchine-git
|
https://github.com/12bme/muchine-git
|
429a709ad8e9574d415680e5dfcabadd41081894
|
32cdb15461346e4d27c71b7839a810ded1496af2
|
refs/heads/master
| 2021-05-28T15:30:40.439000 | 2015-02-25T01:37:11 | 2015-02-25T01:37:11 | 107,427,603 | 1 | 0 | null | true | 2017-10-18T15:31:20 | 2017-10-18T15:31:19 | 2015-02-25T01:39:08 | 2015-02-25T01:39:06 | 7,312 | 0 | 0 | 0 | null | null | null |
package com.lgu.abc.core.plugin.ui.notification.counter;
import org.springframework.web.servlet.ModelAndView;
import com.lgu.abc.core.base.plugin.ModulePluggable;
import com.lgu.abc.core.common.vo.Name;
import com.lgu.abc.core.prototype.org.user.User;
/**
* A representation of module notification counter on the top of web page. This interface is used to paint and control the counter
* in notification-counters.jspf page. The module that wants to add its own counters needs to implement this interface and add a registry.
* @author Sejoon Lim
* @since 2014. 3. 19.
* @see com.lgu.abc.core.plugin.ui.notification.counter.NotificationCounterRegistry
*
*/
public interface NotificationCounter extends ModulePluggable {
/**
* Return the title of notification counter. The title is a label of notification list layer which is shown when a user clicks a counter.
* @return the title of notification counter
*/
Name title();
/**
* Return the icon name of notification counter. The icon name is matched with style class of a main <div> tag.
* @return the icon name of notification counter
*/
String icon();
/**
* Return the uri where a user is redirect to when clicking a "more" link. If null value is returned, "more" link is not shown.
* @return the redirection uri of counter
*/
String uri();
/**
* Return the current notification count for the user
* @param actor the actor who requests count
* @return the notification count
*/
int count(User actor);
/**
* Return the model and view for the list of notification content
* @param actor the actor who requests notification content
* @param maxContentCount the max number of notification content to be shown
* @return model and view for the content
*/
ModelAndView content(User actor, int maxContentCount);
}
|
UTF-8
|
Java
| 1,832 |
java
|
NotificationCounter.java
|
Java
|
[
{
"context": "ent this interface and add a registry. \n * @author Sejoon Lim\n * @since 2014. 3. 19.\n * @see com.lgu.abc.core.p",
"end": 551,
"score": 0.9998459815979004,
"start": 541,
"tag": "NAME",
"value": "Sejoon Lim"
}
] | null |
[] |
package com.lgu.abc.core.plugin.ui.notification.counter;
import org.springframework.web.servlet.ModelAndView;
import com.lgu.abc.core.base.plugin.ModulePluggable;
import com.lgu.abc.core.common.vo.Name;
import com.lgu.abc.core.prototype.org.user.User;
/**
* A representation of module notification counter on the top of web page. This interface is used to paint and control the counter
* in notification-counters.jspf page. The module that wants to add its own counters needs to implement this interface and add a registry.
* @author <NAME>
* @since 2014. 3. 19.
* @see com.lgu.abc.core.plugin.ui.notification.counter.NotificationCounterRegistry
*
*/
public interface NotificationCounter extends ModulePluggable {
/**
* Return the title of notification counter. The title is a label of notification list layer which is shown when a user clicks a counter.
* @return the title of notification counter
*/
Name title();
/**
* Return the icon name of notification counter. The icon name is matched with style class of a main <div> tag.
* @return the icon name of notification counter
*/
String icon();
/**
* Return the uri where a user is redirect to when clicking a "more" link. If null value is returned, "more" link is not shown.
* @return the redirection uri of counter
*/
String uri();
/**
* Return the current notification count for the user
* @param actor the actor who requests count
* @return the notification count
*/
int count(User actor);
/**
* Return the model and view for the list of notification content
* @param actor the actor who requests notification content
* @param maxContentCount the max number of notification content to be shown
* @return model and view for the content
*/
ModelAndView content(User actor, int maxContentCount);
}
| 1,828 | 0.742358 | 0.738537 | 52 | 34.23077 | 39.527309 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.942308 | false | false |
13
|
a72450b31b55735da9643c7578729a9fce480ec9
| 25,924,422,650,502 |
a1854d4d08d7bcc3487b0cd68f29a18be1ca8a65
|
/src/com/houlong/pattern/builder/ActorDirect.java
|
9d2c42429d816256f06e5602ffb7680d675aa25a
|
[] |
no_license
|
houlong123/javaKnowledge
|
https://github.com/houlong123/javaKnowledge
|
284261e5d531671d1ef07bf55cb9f9a54b8535de
|
b292d1685aa3ff1cfa61df2229a73c25d68386d3
|
refs/heads/master
| 2020-03-17T17:29:01.692000 | 2018-05-17T09:44:34 | 2018-05-17T09:44:34 | 133,789,933 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.houlong.pattern.builder;
/**
*
* 指挥者
*/
public class ActorDirect {
public Actor construct(ActorBuilder ab)
{
Actor actor;
ab.builderType();
ab.builderSex();
ab.builderFace();
ab.builderCostume();
ab.builderHairStyle();
actor=ab.createActor();
return actor;
}
}
|
UTF-8
|
Java
| 360 |
java
|
ActorDirect.java
|
Java
|
[] | null |
[] |
package com.houlong.pattern.builder;
/**
*
* 指挥者
*/
public class ActorDirect {
public Actor construct(ActorBuilder ab)
{
Actor actor;
ab.builderType();
ab.builderSex();
ab.builderFace();
ab.builderCostume();
ab.builderHairStyle();
actor=ab.createActor();
return actor;
}
}
| 360 | 0.567797 | 0.567797 | 20 | 16.700001 | 13.535509 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false |
13
|
02224dcc22deeba3b25c8ade2688c6d09317740e
| 27,144,193,358,477 |
d1706023b7d1c9193f125b8a1902eb001712feed
|
/app/src/main/java/org/mapuna/daggerandroid/inject/modules/BaseAppCompatActivityModule.java
|
ab148a1559c1f9c10dde886983b13a2309273edc
|
[] |
no_license
|
mapuna/DaggerAndroidExampleB
|
https://github.com/mapuna/DaggerAndroidExampleB
|
17f395bca99f8592e8c73f1a11729e89ee092cc9
|
5f03fe1582992a1b01c07e0305d7248d0521110b
|
refs/heads/master
| 2020-03-28T15:52:41.030000 | 2018-09-13T12:22:19 | 2018-09-13T12:22:19 | 148,634,279 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.mapuna.daggerandroid.inject.modules;
import org.mapuna.daggerandroid.ui.BaseAppCompatActivity;
import dagger.Binds;
import dagger.Module;
@Module
public interface BaseAppCompatActivityModule<A extends BaseAppCompatActivity> {
@Binds
BaseAppCompatActivity activity(A activity);
}
|
UTF-8
|
Java
| 302 |
java
|
BaseAppCompatActivityModule.java
|
Java
|
[] | null |
[] |
package org.mapuna.daggerandroid.inject.modules;
import org.mapuna.daggerandroid.ui.BaseAppCompatActivity;
import dagger.Binds;
import dagger.Module;
@Module
public interface BaseAppCompatActivityModule<A extends BaseAppCompatActivity> {
@Binds
BaseAppCompatActivity activity(A activity);
}
| 302 | 0.821192 | 0.821192 | 12 | 24.166666 | 25.796749 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false |
13
|
e43e7f28553c776189e10e808802ce6c6f1adf0a
| 27,144,193,362,687 |
0b56b437df7e51ef6d0a9c754bf33c61b41f00f9
|
/platform-manager-web/src/main/java/com/cms/controller/user/loginUserController.java
|
c66d0777f77db4afac46afcf2e2df70122d9b7ab
|
[] |
no_license
|
szdksconan/cms
|
https://github.com/szdksconan/cms
|
5374d827f61ebf062f8e7bb3f4c0a791c9b601f7
|
a1a4e2459d88b2ccfc3e3e09a64d7b8822927ae2
|
refs/heads/master
| 2021-01-25T06:30:19.078000 | 2017-06-07T02:28:52 | 2017-06-07T02:28:52 | 93,583,136 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cms.controller.user;
import javax.servlet.http.HttpServletRequest;
import com.cms.model.manager.loginUserBean;
import com.cms.model.util.GlobalConstant;
import com.cms.model.util.SessionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.cms.iservice.manager.cargoods.loginUserService;
/**
* 用户中心
* @author 刘鑫
*
*/
@Controller
@RequestMapping("loginUser")
public class loginUserController {
@Autowired
private loginUserService loginUserService;
@RequestMapping("userCenter")
@ResponseBody
public ModelAndView userCenter(HttpServletRequest request){
JSONObject obj = new JSONObject();
obj.put("id", ((SessionInfo)request.getSession().getAttribute(GlobalConstant.SESSION_INFO)).getUserId());
ModelAndView mode = new ModelAndView("/admin/userCenter");
try{
mode.addObject("info", this.loginUserService.get(obj));
}finally{
}
return mode;
}
/**
* 审核
* @param id
* @return
*/
@RequestMapping("auditPage")
public ModelAndView auditPage(Long id){
ModelAndView model = new ModelAndView("/admin/audit");
model.addObject("id", id);
return model;
}
@RequestMapping("audit")
@ResponseBody
public JSONObject audit(loginUserBean bean){
JSONObject obj = new JSONObject();
try{
obj = (JSONObject) JSONObject.toJSON(bean);
this.loginUserService.updateAudit(obj);
obj = new JSONObject();
obj.put("success", true);
obj.put("msg", "修改成功!");
} catch (Exception e) {
obj.put("msg", e.getMessage());
}
return obj;
}
/**
* 修改
* @param bean
* @param type
* @return
*/
@RequestMapping("update")
@ResponseBody
public JSONObject update(loginUserBean bean,int type){
JSONObject obj = new JSONObject();
try{
obj = (JSONObject) JSONObject.toJSON(bean);
switch (type) {
case 1:
this.loginUserService.updateInfo(obj);
break;
case 2:
this.loginUserService.updateTel(obj);
break;
case 3:
this.loginUserService.updateLoginPwd(obj);
break;
case 4:
this.loginUserService.updatePayPwd(obj);
break;
}
obj = new JSONObject();
obj.put("success", true);
obj.put("msg", "修改成功!");
} catch (Exception e) {
obj.put("msg", e.getMessage());
}
finally {
}
return obj;
}
}
|
UTF-8
|
Java
| 2,564 |
java
|
loginUserController.java
|
Java
|
[
{
"context": "argoods.loginUserService;\n\n/**\n * 用户中心\n * @author 刘鑫\n *\n */\n@Controller\n@RequestMapping(\"loginUser\")\np",
"end": 622,
"score": 0.9998138546943665,
"start": 620,
"tag": "NAME",
"value": "刘鑫"
}
] | null |
[] |
package com.cms.controller.user;
import javax.servlet.http.HttpServletRequest;
import com.cms.model.manager.loginUserBean;
import com.cms.model.util.GlobalConstant;
import com.cms.model.util.SessionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.cms.iservice.manager.cargoods.loginUserService;
/**
* 用户中心
* @author 刘鑫
*
*/
@Controller
@RequestMapping("loginUser")
public class loginUserController {
@Autowired
private loginUserService loginUserService;
@RequestMapping("userCenter")
@ResponseBody
public ModelAndView userCenter(HttpServletRequest request){
JSONObject obj = new JSONObject();
obj.put("id", ((SessionInfo)request.getSession().getAttribute(GlobalConstant.SESSION_INFO)).getUserId());
ModelAndView mode = new ModelAndView("/admin/userCenter");
try{
mode.addObject("info", this.loginUserService.get(obj));
}finally{
}
return mode;
}
/**
* 审核
* @param id
* @return
*/
@RequestMapping("auditPage")
public ModelAndView auditPage(Long id){
ModelAndView model = new ModelAndView("/admin/audit");
model.addObject("id", id);
return model;
}
@RequestMapping("audit")
@ResponseBody
public JSONObject audit(loginUserBean bean){
JSONObject obj = new JSONObject();
try{
obj = (JSONObject) JSONObject.toJSON(bean);
this.loginUserService.updateAudit(obj);
obj = new JSONObject();
obj.put("success", true);
obj.put("msg", "修改成功!");
} catch (Exception e) {
obj.put("msg", e.getMessage());
}
return obj;
}
/**
* 修改
* @param bean
* @param type
* @return
*/
@RequestMapping("update")
@ResponseBody
public JSONObject update(loginUserBean bean,int type){
JSONObject obj = new JSONObject();
try{
obj = (JSONObject) JSONObject.toJSON(bean);
switch (type) {
case 1:
this.loginUserService.updateInfo(obj);
break;
case 2:
this.loginUserService.updateTel(obj);
break;
case 3:
this.loginUserService.updateLoginPwd(obj);
break;
case 4:
this.loginUserService.updatePayPwd(obj);
break;
}
obj = new JSONObject();
obj.put("success", true);
obj.put("msg", "修改成功!");
} catch (Exception e) {
obj.put("msg", e.getMessage());
}
finally {
}
return obj;
}
}
| 2,564 | 0.707211 | 0.705626 | 108 | 22.370371 | 20.273405 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.083333 | false | false |
13
|
a38ad8b05214dc8c247f5cf84483b8241cf4abed
| 24,618,752,557,263 |
8bd33deed7f34bbdb114ed64ceebed4de157c05d
|
/emerald-parser/src/test/java/ca/adampaynter/emerald/collect/Success.java
|
649ceccc0afc9d2b9e2603a4fb19b8d1cf4eb241
|
[] |
no_license
|
AdamPaynter/Emerald-Parser-Generator
|
https://github.com/AdamPaynter/Emerald-Parser-Generator
|
5807d69d8be562732163c9376d98cd6333efd369
|
0f5316e01aa1db1e99ef7393d59b3484065ba7c5
|
refs/heads/master
| 2016-09-05T11:08:26.778000 | 2012-09-03T10:22:26 | 2012-09-03T10:22:26 | 1,439,483 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ca.adampaynter.emerald.collect;
import com.google.common.base.Objects;
public final class Success<T> extends Completion<T> {
private final T result;
public Success(T result) {
this.result = result;
}
@Override
public boolean wasSuccess() {
return true;
}
public boolean wasFailure() {
return false;
}
@Override
public T getReturnedValue() {
return result;
}
@Override
public Class<? extends Exception> getExceptionClass() {
throw new IllegalStateException("Operation did not throw any exception");
}
@Override
public int hashCode() {
return Objects.hashCode(Success.class, result);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Success) {
Success<?> other = (Success<?>) obj;
return Objects.equal(result, other.result);
}
return false;
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("returnedValue", result).toString();
}
}
|
UTF-8
|
Java
| 953 |
java
|
Success.java
|
Java
|
[] | null |
[] |
package ca.adampaynter.emerald.collect;
import com.google.common.base.Objects;
public final class Success<T> extends Completion<T> {
private final T result;
public Success(T result) {
this.result = result;
}
@Override
public boolean wasSuccess() {
return true;
}
public boolean wasFailure() {
return false;
}
@Override
public T getReturnedValue() {
return result;
}
@Override
public Class<? extends Exception> getExceptionClass() {
throw new IllegalStateException("Operation did not throw any exception");
}
@Override
public int hashCode() {
return Objects.hashCode(Success.class, result);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Success) {
Success<?> other = (Success<?>) obj;
return Objects.equal(result, other.result);
}
return false;
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("returnedValue", result).toString();
}
}
| 953 | 0.706191 | 0.706191 | 53 | 16.981133 | 19.918221 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.320755 | false | false |
13
|
b1c4344cf3cfa1462f7345aaacb1b2a4df429eb3
| 19,421,842,139,976 |
644db21312daf583d3687801e3fdfe0364e375bb
|
/app/src/main/java/com/photo/viewpagerandfragments/ContactAdapter.java
|
08118b8f86507ff207f477d4667bfb95088d4550
|
[] |
no_license
|
BaghajyanRuben/ViewPagerAndFragment
|
https://github.com/BaghajyanRuben/ViewPagerAndFragment
|
05be45fc4ac56520fbbd677f6914fa3bf01017c0
|
e8c2a617ab2947d3d393748247736203964e236d
|
refs/heads/master
| 2020-06-29T01:00:42.238000 | 2019-08-24T16:31:46 | 2019-08-24T16:31:46 | 200,393,076 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.photo.viewpagerandfragments;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.photo.viewpagerandfragments.local.entity.Contact;
import java.util.ArrayList;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
private List<Contact> items;
private ListAdapter.ItemClickListener clickListener;
public ContactAdapter(ListAdapter.ItemClickListener clickListener) {
items = new ArrayList<>();
this.clickListener = clickListener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_contact_layout, parent , false);
return new ViewHolder(itemView, clickListener);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.bide(items.get(position));
}
@Override
public int getItemCount() {
return items.size();
}
public void setItems(List<Contact> contacts) {
items.clear();
items.addAll(contacts);
notifyDataSetChanged();
}
public boolean isEmpty() {
return items.isEmpty();
}
public void select(int position) {
if (position >= 0 && position < items.size()){
Contact contact = items.get(position);
contact.setSelected(!contact.isSelected());
notifyItemChanged(position);
}
}
public List<Contact> getSelectedItems() {
List<Contact> selectedItems = new ArrayList<>();
for (Contact item : items) {
if (item.isSelected()){
selectedItems.add(item);
}
}
return selectedItems;
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private TextView phone;
private CheckBox checkBox;
public ViewHolder(@NonNull View itemView, final ListAdapter.ItemClickListener itemClickListener) {
super(itemView);
name = itemView.findViewById(R.id.tv_name);
phone = itemView.findViewById(R.id.tv_phone);
checkBox = itemView.findViewById(R.id.check_box);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
itemClickListener.onItemClicked(getAdapterPosition(), ClickAction.ACTION_ITEM);
}
});
}
public void bide(Contact contact){
name.setText(contact.getName());
phone.setText(contact.getPhone());
checkBox.setChecked(contact.isSelected());
}
}
}
|
UTF-8
|
Java
| 2,584 |
java
|
ContactAdapter.java
|
Java
|
[] | null |
[] |
package com.photo.viewpagerandfragments;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.photo.viewpagerandfragments.local.entity.Contact;
import java.util.ArrayList;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
private List<Contact> items;
private ListAdapter.ItemClickListener clickListener;
public ContactAdapter(ListAdapter.ItemClickListener clickListener) {
items = new ArrayList<>();
this.clickListener = clickListener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_contact_layout, parent , false);
return new ViewHolder(itemView, clickListener);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.bide(items.get(position));
}
@Override
public int getItemCount() {
return items.size();
}
public void setItems(List<Contact> contacts) {
items.clear();
items.addAll(contacts);
notifyDataSetChanged();
}
public boolean isEmpty() {
return items.isEmpty();
}
public void select(int position) {
if (position >= 0 && position < items.size()){
Contact contact = items.get(position);
contact.setSelected(!contact.isSelected());
notifyItemChanged(position);
}
}
public List<Contact> getSelectedItems() {
List<Contact> selectedItems = new ArrayList<>();
for (Contact item : items) {
if (item.isSelected()){
selectedItems.add(item);
}
}
return selectedItems;
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private TextView phone;
private CheckBox checkBox;
public ViewHolder(@NonNull View itemView, final ListAdapter.ItemClickListener itemClickListener) {
super(itemView);
name = itemView.findViewById(R.id.tv_name);
phone = itemView.findViewById(R.id.tv_phone);
checkBox = itemView.findViewById(R.id.check_box);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
itemClickListener.onItemClicked(getAdapterPosition(), ClickAction.ACTION_ITEM);
}
});
}
public void bide(Contact contact){
name.setText(contact.getName());
phone.setText(contact.getPhone());
checkBox.setChecked(contact.isSelected());
}
}
}
| 2,584 | 0.748065 | 0.747678 | 99 | 25.101009 | 23.652149 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.868687 | false | false |
13
|
f75ae446de234dda00c1681efaf22a63dd0a3126
| 18,975,165,546,871 |
ec4e0ed32ed8b566c3ed0d566731c5224220cea3
|
/judo-platform/judo-auth/src/main/java/com/github/judo/auth/config/JudoJwtAccessTokenConverter.java
|
53d95c82eb3a77bd71474f470297fab9029ae11c
|
[] |
no_license
|
Chiangte/judo-mall
|
https://github.com/Chiangte/judo-mall
|
4897470ca876eaf80519061403443285f93ddd4d
|
c1ac62947d5cdddd947e771026e28676463a9666
|
refs/heads/master
| 2020-04-10T20:35:19.338000 | 2018-12-11T03:39:21 | 2018-12-11T03:39:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.judo.auth.config;
import com.github.judo.common.constant.SecurityConstants;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.Map;
/**
* @Auther: xiangjunzhong@qq.com
* @Description: token 声明版权
* @Version: 1.0
*/
public class JudoJwtAccessTokenConverter extends JwtAccessTokenConverter {
@Override
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
Map<String, Object> representation = (Map<String, Object>) super.convertAccessToken(token, authentication);
representation.put("license", SecurityConstants.JUDO_LICENSE);
return representation;
}
@Override
public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
return super.extractAccessToken(value, map);
}
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
return super.extractAuthentication(map);
}
}
|
UTF-8
|
Java
| 1,174 |
java
|
JudoJwtAccessTokenConverter.java
|
Java
|
[
{
"context": "Converter;\n\nimport java.util.Map;\n\n/**\n * @Auther: xiangjunzhong@qq.com\n * @Description: token 声明版权\n * @Version: 1.0\n */\n",
"end": 388,
"score": 0.9999169111251831,
"start": 368,
"tag": "EMAIL",
"value": "xiangjunzhong@qq.com"
}
] | null |
[] |
package com.github.judo.auth.config;
import com.github.judo.common.constant.SecurityConstants;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.Map;
/**
* @Auther: <EMAIL>
* @Description: token 声明版权
* @Version: 1.0
*/
public class JudoJwtAccessTokenConverter extends JwtAccessTokenConverter {
@Override
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
Map<String, Object> representation = (Map<String, Object>) super.convertAccessToken(token, authentication);
representation.put("license", SecurityConstants.JUDO_LICENSE);
return representation;
}
@Override
public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
return super.extractAccessToken(value, map);
}
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
return super.extractAuthentication(map);
}
}
| 1,161 | 0.763293 | 0.753859 | 32 | 35.4375 | 34.818222 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65625 | false | false |
13
|
3c2bb3b52a10ab5182cde0a4720ea47ef78d9944
| 9,259,949,543,388 |
dac0df97fab7c172b5b4edfae20e691901490c69
|
/CodeCon.java
|
acdebc323c720eec454e7ae0417b655126fb22cf
|
[] |
no_license
|
virenkoli/pro
|
https://github.com/virenkoli/pro
|
02c479d9c7dfe71bcd07e2465621b5573689f54e
|
40b55bd4b7541e1351ed87b64ec6d2fdfc8aed2d
|
refs/heads/master
| 2020-08-01T05:50:31.152000 | 2019-09-25T16:30:03 | 2019-09-25T16:30:03 | 210,888,671 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import javax.swing.*;
import java.awt.event.*;
public class CodeCon extends JFrame implements ActionListener ,ItemListener
{
String str;
JCheckBox c1, c2, c3 , c4 ;
JLabel l1, l2, l3, l4, l5, l6, l7 ,l8;
JTextField t1;
JButton b1,b2,b3,b4;
public static void main(String args[])
{
CodeCon a = new CodeCon() ;
}
public CodeCon()
{
super("Code Covertion of Numbers") ;
l1 = new JLabel("Enter Number to Convert") ;
l2 = new JLabel("Select the basetype of Entered Number") ;
t1 = new JTextField(20) ;
b1 = new JButton("BINARY");
b2 = new JButton("DECIMAL");
b3 = new JButton("OCTAL");
b4 = new JButton("HEXADECIMAL");
l3 = new JLabel() ;
l4 = new JLabel() ;
l5 = new JLabel() ;
l6 = new JLabel() ;
l8 = new JLabel("RESULT") ;
c1 = new JCheckBox("DECIMAL") ;
c2 = new JCheckBox("BINARY") ;
c3 = new JCheckBox("HEXADECIMAL") ;
c4 = new JCheckBox("OCTAL") ;
l7 = new JLabel("Select the basetype to Convert") ;
setVisible(true) ;
setSize(600,600) ;
setLayout(null) ;
l1.setBounds(20,40,200,30) ;
l2.setBounds(20,90,300,30) ;
t1.setBounds(230,40,150,30);
b1.setBounds(20,140,150,30) ;
b2.setBounds(20,170,150,30) ;
b3.setBounds(20,200,150,30) ;
b4.setBounds(20,230,150,30) ;
l7.setBounds(20,260,300,30) ;
c1.setBounds(20,290,150,30) ;
c2.setBounds(20,320,150,30) ;
c3.setBounds(20,350,150,30) ;
c4.setBounds(20,380,150,30) ;
l8.setBounds(20,420,150,30) ;
l3.setBounds(20,450,150,30) ;
l4.setBounds(20,480,150,30) ;
l5.setBounds(20,510,150,30);
l6.setBounds(20,540,150,30) ;
add(l8);
add(l1);
add(t1);
add(l2);
add(b1);
add(b2);
add(b3);
add(b4);
add(l3);
add(l4);
add(l5);
add(l6);
add(l7);
add(c1);
add(c2);
add(c3);
add(c4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
str = ae.getActionCommand();
}
public void itemStateChanged(ItemEvent ie)
{
String s="";
if(str.equals("DECIMAL"))
{
int x=Integer.parseInt(t1.getText().trim());
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=t1.getText().trim();
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l6.setText(" ");
}
else if(str.equals("BINARY"))
{
int x=Integer.parseInt(t1.getText().trim(),2);
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=Integer.toString(x);
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l6.setText(" ");
}
else if(str.equals("OCTAL"))
{ int x=Integer.parseInt(t1.getText().trim(),8);
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=Integer.toString(x);
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l6.setText(" ");
}
else if(str.equals("HEXADECIMAL"))
{
int x=Integer.parseInt(t1.getText().trim(),16);
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=Integer.toString(x);
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l4.setText(" ");
}
}
}
|
UTF-8
|
Java
| 5,849 |
java
|
CodeCon.java
|
Java
|
[] | null |
[] |
import javax.swing.*;
import java.awt.event.*;
public class CodeCon extends JFrame implements ActionListener ,ItemListener
{
String str;
JCheckBox c1, c2, c3 , c4 ;
JLabel l1, l2, l3, l4, l5, l6, l7 ,l8;
JTextField t1;
JButton b1,b2,b3,b4;
public static void main(String args[])
{
CodeCon a = new CodeCon() ;
}
public CodeCon()
{
super("Code Covertion of Numbers") ;
l1 = new JLabel("Enter Number to Convert") ;
l2 = new JLabel("Select the basetype of Entered Number") ;
t1 = new JTextField(20) ;
b1 = new JButton("BINARY");
b2 = new JButton("DECIMAL");
b3 = new JButton("OCTAL");
b4 = new JButton("HEXADECIMAL");
l3 = new JLabel() ;
l4 = new JLabel() ;
l5 = new JLabel() ;
l6 = new JLabel() ;
l8 = new JLabel("RESULT") ;
c1 = new JCheckBox("DECIMAL") ;
c2 = new JCheckBox("BINARY") ;
c3 = new JCheckBox("HEXADECIMAL") ;
c4 = new JCheckBox("OCTAL") ;
l7 = new JLabel("Select the basetype to Convert") ;
setVisible(true) ;
setSize(600,600) ;
setLayout(null) ;
l1.setBounds(20,40,200,30) ;
l2.setBounds(20,90,300,30) ;
t1.setBounds(230,40,150,30);
b1.setBounds(20,140,150,30) ;
b2.setBounds(20,170,150,30) ;
b3.setBounds(20,200,150,30) ;
b4.setBounds(20,230,150,30) ;
l7.setBounds(20,260,300,30) ;
c1.setBounds(20,290,150,30) ;
c2.setBounds(20,320,150,30) ;
c3.setBounds(20,350,150,30) ;
c4.setBounds(20,380,150,30) ;
l8.setBounds(20,420,150,30) ;
l3.setBounds(20,450,150,30) ;
l4.setBounds(20,480,150,30) ;
l5.setBounds(20,510,150,30);
l6.setBounds(20,540,150,30) ;
add(l8);
add(l1);
add(t1);
add(l2);
add(b1);
add(b2);
add(b3);
add(b4);
add(l3);
add(l4);
add(l5);
add(l6);
add(l7);
add(c1);
add(c2);
add(c3);
add(c4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
str = ae.getActionCommand();
}
public void itemStateChanged(ItemEvent ie)
{
String s="";
if(str.equals("DECIMAL"))
{
int x=Integer.parseInt(t1.getText().trim());
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=t1.getText().trim();
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l6.setText(" ");
}
else if(str.equals("BINARY"))
{
int x=Integer.parseInt(t1.getText().trim(),2);
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=Integer.toString(x);
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l6.setText(" ");
}
else if(str.equals("OCTAL"))
{ int x=Integer.parseInt(t1.getText().trim(),8);
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=Integer.toString(x);
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l6.setText(" ");
}
else if(str.equals("HEXADECIMAL"))
{
int x=Integer.parseInt(t1.getText().trim(),16);
if (ie.getSource() == c1)
if (ie.getStateChange() == 1)
{
s=Integer.toString(x);
l3.setText("Decimal="+s);
}
else
l3.setText(" ");
if (ie.getSource() == c2)
if (ie.getStateChange() == 1)
{
s=Integer.toBinaryString(x);
l4.setText("Binary="+s);
}
else
l4.setText(" ");
if (ie.getSource() == c3)
if (ie.getStateChange() == 1)
{
s=Integer.toHexString(x);
l5.setText("Hexadecimal="+s);
}
else
l5.setText(" ");
if (ie.getSource() == c4)
if (ie.getStateChange() == 1)
{
s=Integer.toOctalString(x);
l6.setText("Octal="+s);
}
else
l4.setText(" ");
}
}
}
| 5,849 | 0.510344 | 0.454779 | 287 | 18.379791 | 14.289393 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.334495 | false | false |
13
|
921e878c317146f358e006f9c25d9685ac88ade1
| 22,299,470,230,989 |
6dd43280e480926244b0aaedac1a818b7f6cb3ed
|
/src/main/java/seedu/duke/parser/Parser.java
|
5a5eef1b95f1416016cd4b74812f5418d2508c01
|
[] |
no_license
|
weisiong24/tp
|
https://github.com/weisiong24/tp
|
4235aa81665ca06cf182dbca0eec6cd5e673c2ac
|
1208e300f737df2ccee4a430eeec00fae03945af
|
refs/heads/master
| 2023-01-09T06:05:41.495000 | 2020-10-09T08:32:42 | 2020-10-09T08:32:42 | 300,156,996 | 0 | 0 | null | true | 2020-10-01T05:31:18 | 2020-10-01T05:31:17 | 2020-10-01T05:27:32 | 2020-10-01T05:27:30 | 1,393 | 0 | 0 | 0 | null | false | false |
package seedu.duke.parser;
import seedu.duke.command.ByeCommand;
import seedu.duke.command.Command;
import seedu.duke.command.DeleteCommand;
//import seedu.duke.command.DoneCommand;
//import seedu.duke.command.EventCommand;
import seedu.duke.command.FindCommand;
import seedu.duke.command.ListCommand;
import seedu.duke.exception.DukeException;
/**
* Parses the user's input.
*/
public class Parser {
//private static final String COMMAND_DEADLINE = "deadline";
//private static final String COMMAND_EVENT = "event";
private static final String COMMAND_LIST = "list";
//private static final String COMMAND_DONE = "done";
private static final String COMMAND_DELETE = "delete";
private static final String COMMAND_FIND = "find";
private static final String COMMAND_BYE = "bye";
/**
* Returns a Command object based on user's string input.
*
* @param input user's string input.
* @return a new Command object based on user's input.
* @throws DukeException if user's input does not match any of the command.
*/
public static Command parse(String input) throws DukeException {
String[] parsedInputs = input.split(" ", 2);
switch (parsedInputs[0]) {
/*case COMMAND_DEADLINE:
checkDeadlineValidity(parsedInputs);
return new DeadlineCommand(parsedInputs[1]);
case COMMAND_EVENT:
checkEventValidity(parsedInputs);
return new EventCommand(parsedInputs[1]);*/
case COMMAND_LIST:
return new ListCommand();
/*case COMMAND_DONE:
checkTaskIndexValidity(parsedInputs);
return new DoneCommand(parsedInputs[1]);*/
case COMMAND_DELETE:
checkTaskIndexValidity(parsedInputs);
return new DeleteCommand(parsedInputs[1]);
case COMMAND_FIND:
verifyFind(parsedInputs);
return new FindCommand(parsedInputs[1]);
case COMMAND_BYE:
return new ByeCommand();
default:
throw new DukeException("Sorry! I don't know what that means :-(");
}
}
/**
* Checks the index's validity.
*
* @param input user's string input.
* @throws DukeException if the index is not a number or within valid range.
*/
private static void checkTaskIndexValidity(String[] input) throws DukeException {
try {
Integer.parseInt(input[1]);
} catch (NumberFormatException e) {
throw new DukeException("Please enter the task number you want to mark as done!");
} catch (IndexOutOfBoundsException e) {
throw new DukeException("You've entered an invalid task number!");
}
}
/**
* Checks the validity of the description for todo.
*
* @param input user's string input.
* @throws DukeException if the description for todo is an empty field.
*/
private static void checkTodoValidity(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("There is no description in your todo command!");
}
}
/**
* Checks the validity of the description for deadline.
*
* @param input user's string input.
* @throws DukeException if the description for deadline is an empty field.
*/
private static void checkDeadlineValidity(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("There is no description in your deadline command!");
} else if (!input[1].contains("/by")) {
throw new DukeException("A deadline task requires a '/by' to indicate time frame!");
}
int byPosition = input[1].indexOf("/by");
if (input[1].substring(0, byPosition).isBlank()) {
throw new DukeException("There is no description in your deadline command!");
} else if (input[1].substring(byPosition + 3).isBlank()) {
throw new DukeException("Please indicate time frame!");
}
}
/**
* Checks the validity of the description for event.
*
* @param input user's string input.
* @throws DukeException if the description for event is an empty field.
*/
private static void checkEventValidity(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("There is no description in your event command!");
} else if (!input[1].contains("/at")) {
throw new DukeException("An event task requires an '/at' to indicate location!");
}
int atPosition = input[1].indexOf("/at");
if (input[1].substring(0, atPosition).isBlank()) {
throw new DukeException("There is no description in your event command!");
} else if (input[1].substring(atPosition + 3).isBlank()) {
throw new DukeException("An event task requires an '/at' to indicate location!");
}
}
/**
* Checks the validity of the KEYWORD for find.
*
* @param input user's string input.
* @throws DukeException if the KEYWORD is an empty field.
*/
private static void verifyFind(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("Search description is empty");
}
}
}
|
UTF-8
|
Java
| 5,358 |
java
|
Parser.java
|
Java
|
[] | null |
[] |
package seedu.duke.parser;
import seedu.duke.command.ByeCommand;
import seedu.duke.command.Command;
import seedu.duke.command.DeleteCommand;
//import seedu.duke.command.DoneCommand;
//import seedu.duke.command.EventCommand;
import seedu.duke.command.FindCommand;
import seedu.duke.command.ListCommand;
import seedu.duke.exception.DukeException;
/**
* Parses the user's input.
*/
public class Parser {
//private static final String COMMAND_DEADLINE = "deadline";
//private static final String COMMAND_EVENT = "event";
private static final String COMMAND_LIST = "list";
//private static final String COMMAND_DONE = "done";
private static final String COMMAND_DELETE = "delete";
private static final String COMMAND_FIND = "find";
private static final String COMMAND_BYE = "bye";
/**
* Returns a Command object based on user's string input.
*
* @param input user's string input.
* @return a new Command object based on user's input.
* @throws DukeException if user's input does not match any of the command.
*/
public static Command parse(String input) throws DukeException {
String[] parsedInputs = input.split(" ", 2);
switch (parsedInputs[0]) {
/*case COMMAND_DEADLINE:
checkDeadlineValidity(parsedInputs);
return new DeadlineCommand(parsedInputs[1]);
case COMMAND_EVENT:
checkEventValidity(parsedInputs);
return new EventCommand(parsedInputs[1]);*/
case COMMAND_LIST:
return new ListCommand();
/*case COMMAND_DONE:
checkTaskIndexValidity(parsedInputs);
return new DoneCommand(parsedInputs[1]);*/
case COMMAND_DELETE:
checkTaskIndexValidity(parsedInputs);
return new DeleteCommand(parsedInputs[1]);
case COMMAND_FIND:
verifyFind(parsedInputs);
return new FindCommand(parsedInputs[1]);
case COMMAND_BYE:
return new ByeCommand();
default:
throw new DukeException("Sorry! I don't know what that means :-(");
}
}
/**
* Checks the index's validity.
*
* @param input user's string input.
* @throws DukeException if the index is not a number or within valid range.
*/
private static void checkTaskIndexValidity(String[] input) throws DukeException {
try {
Integer.parseInt(input[1]);
} catch (NumberFormatException e) {
throw new DukeException("Please enter the task number you want to mark as done!");
} catch (IndexOutOfBoundsException e) {
throw new DukeException("You've entered an invalid task number!");
}
}
/**
* Checks the validity of the description for todo.
*
* @param input user's string input.
* @throws DukeException if the description for todo is an empty field.
*/
private static void checkTodoValidity(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("There is no description in your todo command!");
}
}
/**
* Checks the validity of the description for deadline.
*
* @param input user's string input.
* @throws DukeException if the description for deadline is an empty field.
*/
private static void checkDeadlineValidity(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("There is no description in your deadline command!");
} else if (!input[1].contains("/by")) {
throw new DukeException("A deadline task requires a '/by' to indicate time frame!");
}
int byPosition = input[1].indexOf("/by");
if (input[1].substring(0, byPosition).isBlank()) {
throw new DukeException("There is no description in your deadline command!");
} else if (input[1].substring(byPosition + 3).isBlank()) {
throw new DukeException("Please indicate time frame!");
}
}
/**
* Checks the validity of the description for event.
*
* @param input user's string input.
* @throws DukeException if the description for event is an empty field.
*/
private static void checkEventValidity(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("There is no description in your event command!");
} else if (!input[1].contains("/at")) {
throw new DukeException("An event task requires an '/at' to indicate location!");
}
int atPosition = input[1].indexOf("/at");
if (input[1].substring(0, atPosition).isBlank()) {
throw new DukeException("There is no description in your event command!");
} else if (input[1].substring(atPosition + 3).isBlank()) {
throw new DukeException("An event task requires an '/at' to indicate location!");
}
}
/**
* Checks the validity of the KEYWORD for find.
*
* @param input user's string input.
* @throws DukeException if the KEYWORD is an empty field.
*/
private static void verifyFind(String[] input) throws DukeException {
if (input.length < 2) {
throw new DukeException("Search description is empty");
}
}
}
| 5,358 | 0.634938 | 0.630459 | 138 | 37.826088 | 27.985998 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false |
13
|
cba5d918dc6d809d50a93e70680b03f9e7f79f8a
| 18,313,740,569,819 |
ec21affdd4764bf53ddff3a2ba034d6b8f3e5cdb
|
/fictionLife/src/main/java/condition/RankCondition.java
|
fffacfe84be66f92f0cf3257982d3f644bd2e750
|
[] |
no_license
|
lenagend/portfolio
|
https://github.com/lenagend/portfolio
|
404e15b5b36b0954862c6be9b877473f5a3e5f97
|
42c64cc56f7369f1333b4bd803d329004bddd151
|
refs/heads/master
| 2022-07-27T19:46:43.838000 | 2019-12-24T09:56:10 | 2019-12-24T09:56:10 | 227,076,965 | 0 | 0 | null | false | 2022-07-15T21:03:45 | 2019-12-10T09:22:01 | 2019-12-24T09:56:18 | 2022-07-15T21:03:42 | 5,730 | 0 | 0 | 23 |
Java
| false | false |
package condition;
import model.Icon;
import model.User_rank;
public class RankCondition {
private User_rank ur;
private Icon wicon;
private Icon ricon;
public User_rank getUr() {
return ur;
}
public void setUr(User_rank ur) {
this.ur = ur;
}
public void setWicon(Icon wicon) {
this.wicon = wicon;
}
public Icon getWicon() {
return wicon;
}
public Icon getRicon() {
return ricon;
}
public void setRicon(Icon ricon) {
this.ricon = ricon;
}
}
|
UTF-8
|
Java
| 489 |
java
|
RankCondition.java
|
Java
|
[] | null |
[] |
package condition;
import model.Icon;
import model.User_rank;
public class RankCondition {
private User_rank ur;
private Icon wicon;
private Icon ricon;
public User_rank getUr() {
return ur;
}
public void setUr(User_rank ur) {
this.ur = ur;
}
public void setWicon(Icon wicon) {
this.wicon = wicon;
}
public Icon getWicon() {
return wicon;
}
public Icon getRicon() {
return ricon;
}
public void setRicon(Icon ricon) {
this.ricon = ricon;
}
}
| 489 | 0.660532 | 0.660532 | 34 | 12.382353 | 11.702224 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false |
13
|
af03e76c899e315b1a9779e63a5f02263d98b7ae
| 2,757,369,067,431 |
3c898e9be6a78c04433063116dd3237fbb002d07
|
/src/main/java/fr/frogdevelopment/assoplus/core/controller/AbstractCustomController.java
|
4421f254220389ff85f6e549445110933e820d8b
|
[] |
no_license
|
FrogDevelopment/AssoPlus
|
https://github.com/FrogDevelopment/AssoPlus
|
78608c88cee92194086a9cc3600063fc8f6d63d7
|
4bd0b84f03a324c6fccb5c0490e42607fdee589d
|
refs/heads/master
| 2021-01-17T17:55:25.448000 | 2018-05-03T13:00:27 | 2018-05-03T13:00:27 | 36,559,525 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (c) Frog Development 2015.
*/
package fr.frogdevelopment.assoplus.core.controller;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.layout.Region;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import fr.frogdevelopment.assoplus.core.utils.SpringFXMLLoader;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import static fr.frogdevelopment.assoplus.core.utils.ApplicationUtils.ICON_16;
import static fr.frogdevelopment.assoplus.core.utils.ApplicationUtils.ICON_32;
import static fr.frogdevelopment.assoplus.core.utils.ApplicationUtils.ICON_48;
import static javafx.scene.control.Alert.AlertType.CONFIRMATION;
import static javafx.scene.control.Alert.AlertType.ERROR;
import static javafx.scene.control.Alert.AlertType.INFORMATION;
import static javafx.scene.control.Alert.AlertType.WARNING;
public abstract class AbstractCustomController implements Initializable {
@FXML
protected Region child;
private ResourceBundle resources;
@Override
public void initialize(URL location, ResourceBundle resources) {
this.resources = resources;
this.initialize();
}
protected String getMessage(String key) {
return resources.getString(key);
}
protected Window getParent() {
return child.getScene().getWindow();
}
protected abstract void initialize();
protected Stage openDialog(String url) {
return openDialog(url, null);
}
protected <T> Stage openDialog(String url, Consumer<T> controllerConsumer) {
Stage dialog = new Stage();
dialog.initModality(Modality.WINDOW_MODAL);
// dialog.initStyle(StageStyle.UTILITY);
dialog.initOwner(getParent());
dialog.getIcons().addAll(ICON_16, ICON_32, ICON_48);
Parent root = SpringFXMLLoader.load(url, controllerConsumer);
dialog.setScene(new Scene(root));
return dialog;
}
// TODO http://ux.stackexchange.com/questions/9946/should-i-use-yes-no-or-ok-cancel-on-my-message-box
protected void showInformation(String headerKey) {
showInformation(headerKey, null);
}
protected void showInformation(String headerKey, String message) {
Alert alert = new Alert(INFORMATION);
alert.setHeaderText(getMessage(headerKey));
if (StringUtils.isNotBlank(message)) {
alert.setContentText(message);
}
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-information_16.png"));
alert.show();
}
protected void showYesNoDialog(String message, Consumer<? super ButtonType> onYes) {
showYesNoDialog(null, message, onYes);
}
protected void showYesNoDialog(String headerKey, String message, Consumer<? super ButtonType> onYes) {
Alert alert = new Alert(CONFIRMATION);
if (StringUtils.isNotBlank(headerKey)) {
alert.setHeaderText(getMessage(headerKey));
}
alert.setContentText(message);
alert.getButtonTypes().clear();
ButtonType[] buttons = {ButtonType.YES, ButtonType.NO};
alert.getButtonTypes().addAll(buttons);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-confirm_16.png"));
alert.showAndWait()
.filter(response -> response == ButtonType.YES)
.ifPresent(onYes);
}
protected void showConfirmation(String message, Consumer<? super ButtonType> onOK) {
showConfirmation(null, message, onOK);
}
protected void showConfirmation(String headerKey, String message, Consumer<? super ButtonType> onOK) {
Alert alert = new Alert(CONFIRMATION);
if (StringUtils.isNotBlank(headerKey)) {
alert.setHeaderText(getMessage(headerKey));
}
alert.setContentText(message);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-confirm_16.png"));
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(onOK);
}
protected void showWarning(String headerKey) {
showWarning(headerKey, null);
}
protected void showWarning(String headerKey, String message) {
Alert alert = new Alert(WARNING);
alert.setHeaderText(getMessage(headerKey));
if (StringUtils.isNotBlank(message)) {
alert.setContentText(message);
}
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-warning_16.png"));
alert.show();
}
protected void showError(Throwable th) {
Alert alert = new Alert(ERROR);
alert.setHeaderText(getMessage("global.error.header"));
alert.setContentText(ExceptionUtils.getRootCauseMessage(th));
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-error_16.png"));
alert.show();
}
protected void showError(String headerKey, Throwable th) {
Alert alert = new Alert(ERROR);
alert.setHeaderText(getMessage(headerKey));
alert.setContentText(ExceptionUtils.getMessage(th));
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-error_16.png"));
alert.show();
}
protected void showError(String headerKey, String messageKey) {
Alert alert = new Alert(ERROR);
alert.setHeaderText(getMessage(headerKey));
alert.setContentText(getMessage(messageKey));
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-error_16.png"));
alert.show();
}
protected Optional<ButtonType> showCustomConfirmation(String headerKey, String contentKey, ButtonType overrideBtn, ButtonType ignoreBtn) {
Alert alert = new Alert(CONFIRMATION);
alert.setHeaderText(getMessage(headerKey));
alert.setContentText(getMessage(contentKey));
alert.getButtonTypes().clear();
alert.getButtonTypes().add(overrideBtn);
alert.getButtonTypes().add(ignoreBtn);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-confirm_16.png"));
return alert.showAndWait();
}
}
|
UTF-8
|
Java
| 6,924 |
java
|
AbstractCustomController.java
|
Java
|
[
{
"context": "/*\n * Copyright (c) Frog Development 2015.\n */\n\npackage fr.frogdevelopment.assoplus.co",
"end": 36,
"score": 0.9860963821411133,
"start": 20,
"tag": "NAME",
"value": "Frog Development"
}
] | null |
[] |
/*
* Copyright (c) <NAME> 2015.
*/
package fr.frogdevelopment.assoplus.core.controller;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.layout.Region;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import fr.frogdevelopment.assoplus.core.utils.SpringFXMLLoader;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import static fr.frogdevelopment.assoplus.core.utils.ApplicationUtils.ICON_16;
import static fr.frogdevelopment.assoplus.core.utils.ApplicationUtils.ICON_32;
import static fr.frogdevelopment.assoplus.core.utils.ApplicationUtils.ICON_48;
import static javafx.scene.control.Alert.AlertType.CONFIRMATION;
import static javafx.scene.control.Alert.AlertType.ERROR;
import static javafx.scene.control.Alert.AlertType.INFORMATION;
import static javafx.scene.control.Alert.AlertType.WARNING;
public abstract class AbstractCustomController implements Initializable {
@FXML
protected Region child;
private ResourceBundle resources;
@Override
public void initialize(URL location, ResourceBundle resources) {
this.resources = resources;
this.initialize();
}
protected String getMessage(String key) {
return resources.getString(key);
}
protected Window getParent() {
return child.getScene().getWindow();
}
protected abstract void initialize();
protected Stage openDialog(String url) {
return openDialog(url, null);
}
protected <T> Stage openDialog(String url, Consumer<T> controllerConsumer) {
Stage dialog = new Stage();
dialog.initModality(Modality.WINDOW_MODAL);
// dialog.initStyle(StageStyle.UTILITY);
dialog.initOwner(getParent());
dialog.getIcons().addAll(ICON_16, ICON_32, ICON_48);
Parent root = SpringFXMLLoader.load(url, controllerConsumer);
dialog.setScene(new Scene(root));
return dialog;
}
// TODO http://ux.stackexchange.com/questions/9946/should-i-use-yes-no-or-ok-cancel-on-my-message-box
protected void showInformation(String headerKey) {
showInformation(headerKey, null);
}
protected void showInformation(String headerKey, String message) {
Alert alert = new Alert(INFORMATION);
alert.setHeaderText(getMessage(headerKey));
if (StringUtils.isNotBlank(message)) {
alert.setContentText(message);
}
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-information_16.png"));
alert.show();
}
protected void showYesNoDialog(String message, Consumer<? super ButtonType> onYes) {
showYesNoDialog(null, message, onYes);
}
protected void showYesNoDialog(String headerKey, String message, Consumer<? super ButtonType> onYes) {
Alert alert = new Alert(CONFIRMATION);
if (StringUtils.isNotBlank(headerKey)) {
alert.setHeaderText(getMessage(headerKey));
}
alert.setContentText(message);
alert.getButtonTypes().clear();
ButtonType[] buttons = {ButtonType.YES, ButtonType.NO};
alert.getButtonTypes().addAll(buttons);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-confirm_16.png"));
alert.showAndWait()
.filter(response -> response == ButtonType.YES)
.ifPresent(onYes);
}
protected void showConfirmation(String message, Consumer<? super ButtonType> onOK) {
showConfirmation(null, message, onOK);
}
protected void showConfirmation(String headerKey, String message, Consumer<? super ButtonType> onOK) {
Alert alert = new Alert(CONFIRMATION);
if (StringUtils.isNotBlank(headerKey)) {
alert.setHeaderText(getMessage(headerKey));
}
alert.setContentText(message);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-confirm_16.png"));
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(onOK);
}
protected void showWarning(String headerKey) {
showWarning(headerKey, null);
}
protected void showWarning(String headerKey, String message) {
Alert alert = new Alert(WARNING);
alert.setHeaderText(getMessage(headerKey));
if (StringUtils.isNotBlank(message)) {
alert.setContentText(message);
}
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-warning_16.png"));
alert.show();
}
protected void showError(Throwable th) {
Alert alert = new Alert(ERROR);
alert.setHeaderText(getMessage("global.error.header"));
alert.setContentText(ExceptionUtils.getRootCauseMessage(th));
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-error_16.png"));
alert.show();
}
protected void showError(String headerKey, Throwable th) {
Alert alert = new Alert(ERROR);
alert.setHeaderText(getMessage(headerKey));
alert.setContentText(ExceptionUtils.getMessage(th));
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-error_16.png"));
alert.show();
}
protected void showError(String headerKey, String messageKey) {
Alert alert = new Alert(ERROR);
alert.setHeaderText(getMessage(headerKey));
alert.setContentText(getMessage(messageKey));
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-error_16.png"));
alert.show();
}
protected Optional<ButtonType> showCustomConfirmation(String headerKey, String contentKey, ButtonType overrideBtn, ButtonType ignoreBtn) {
Alert alert = new Alert(CONFIRMATION);
alert.setHeaderText(getMessage(headerKey));
alert.setContentText(getMessage(contentKey));
alert.getButtonTypes().clear();
alert.getButtonTypes().add(overrideBtn);
alert.getButtonTypes().add(ignoreBtn);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/img/dialog-confirm_16.png"));
return alert.showAndWait();
}
}
| 6,914 | 0.683709 | 0.678221 | 209 | 32.129185 | 29.021648 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602871 | false | false |
13
|
aa5d80303fd6cb3997ee7daf82237304547d35c5
| 25,812,753,514,318 |
fe40b1cbc9647b2f0563877ce7f4ee423af997b8
|
/de.tudarmstadt.ukp.uby.integration.ontowiktionary-asl/src/main/java/de/tudarmstadt/ukp/lmf/transform/ontowiktionary/OntoWiktionaryTransformer.java
|
3ba401df6190ddec3f9123401b717b15aa822660
|
[
"Apache-2.0"
] |
permissive
|
Ningyo/diplom
|
https://github.com/Ningyo/diplom
|
004bb16646cbcf12e3ec1e0506c8e789a018f36b
|
15df1eae4528ab71dea899e88f554288ce85bc91
|
refs/heads/master
| 2021-07-09T08:36:44.999000 | 2017-10-07T11:04:05 | 2017-10-07T11:04:05 | 106,090,990 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*******************************************************************************
* Copyright 2016
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.lmf.transform.ontowiktionary;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import de.tudarmstadt.ukp.jwktl.api.IPronunciation;
import de.tudarmstadt.ukp.jwktl.api.IPronunciation.PronunciationType;
import de.tudarmstadt.ukp.jwktl.api.IQuotation;
import de.tudarmstadt.ukp.jwktl.api.IWikiString;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEdition;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEntry;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryRelation;
import de.tudarmstadt.ukp.jwktl.api.IWiktionarySense;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryTranslation;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryWordForm;
import de.tudarmstadt.ukp.jwktl.api.PartOfSpeech;
import de.tudarmstadt.ukp.jwktl.api.entry.WikiString;
import de.tudarmstadt.ukp.jwktl.api.util.ILanguage;
import de.tudarmstadt.ukp.jwktl.api.util.IWiktionaryIterator;
import de.tudarmstadt.ukp.jwktl.api.util.TemplateParser;
import de.tudarmstadt.ukp.jwktl.api.util.TemplateParser.EtymologyTemplateHandler;
import de.tudarmstadt.ukp.lmf.model.core.Definition;
import de.tudarmstadt.ukp.lmf.model.core.GlobalInformation;
import de.tudarmstadt.ukp.lmf.model.core.LexicalEntry;
import de.tudarmstadt.ukp.lmf.model.core.LexicalResource;
import de.tudarmstadt.ukp.lmf.model.core.Lexicon;
import de.tudarmstadt.ukp.lmf.model.core.Sense;
import de.tudarmstadt.ukp.lmf.model.core.Statement;
import de.tudarmstadt.ukp.lmf.model.core.TextRepresentation;
import de.tudarmstadt.ukp.lmf.model.enums.EAuxiliary;
import de.tudarmstadt.ukp.lmf.model.enums.ECase;
import de.tudarmstadt.ukp.lmf.model.enums.EContextType;
import de.tudarmstadt.ukp.lmf.model.enums.EDefinitionType;
import de.tudarmstadt.ukp.lmf.model.enums.EDegree;
import de.tudarmstadt.ukp.lmf.model.enums.EExampleType;
import de.tudarmstadt.ukp.lmf.model.enums.EGrammaticalGender;
import de.tudarmstadt.ukp.lmf.model.enums.EGrammaticalNumber;
import de.tudarmstadt.ukp.lmf.model.enums.ELabelNameSemantics;
import de.tudarmstadt.ukp.lmf.model.enums.ELabelTypeSemantics;
import de.tudarmstadt.ukp.lmf.model.enums.EPartOfSpeech;
import de.tudarmstadt.ukp.lmf.model.enums.EPerson;
import de.tudarmstadt.ukp.lmf.model.enums.ERelTypeMorphology;
import de.tudarmstadt.ukp.lmf.model.enums.ERelTypeSemantics;
import de.tudarmstadt.ukp.lmf.model.enums.EStatementType;
import de.tudarmstadt.ukp.lmf.model.enums.ESyntacticProperty;
import de.tudarmstadt.ukp.lmf.model.enums.ETense;
import de.tudarmstadt.ukp.lmf.model.enums.EVerbFormMood;
import de.tudarmstadt.ukp.lmf.model.meta.SemanticLabel;
import de.tudarmstadt.ukp.lmf.model.miscellaneous.ConstraintSet;
import de.tudarmstadt.ukp.lmf.model.morphology.FormRepresentation;
import de.tudarmstadt.ukp.lmf.model.morphology.Lemma;
import de.tudarmstadt.ukp.lmf.model.morphology.RelatedForm;
import de.tudarmstadt.ukp.lmf.model.morphology.WordForm;
import de.tudarmstadt.ukp.lmf.model.mrd.Context;
import de.tudarmstadt.ukp.lmf.model.mrd.Equivalent;
import de.tudarmstadt.ukp.lmf.model.multilingual.SenseAxis;
import de.tudarmstadt.ukp.lmf.model.semantics.MonolingualExternalRef;
import de.tudarmstadt.ukp.lmf.model.semantics.SemanticPredicate;
import de.tudarmstadt.ukp.lmf.model.semantics.SenseExample;
import de.tudarmstadt.ukp.lmf.model.semantics.SenseRelation;
import de.tudarmstadt.ukp.lmf.model.semantics.SynSemCorrespondence;
import de.tudarmstadt.ukp.lmf.model.semantics.Synset;
import de.tudarmstadt.ukp.lmf.model.semantics.SynsetRelation;
import de.tudarmstadt.ukp.lmf.model.syntax.LexemeProperty;
import de.tudarmstadt.ukp.lmf.model.syntax.SubcategorizationFrame;
import de.tudarmstadt.ukp.lmf.model.syntax.SubcategorizationFrameSet;
import de.tudarmstadt.ukp.lmf.model.syntax.SyntacticBehaviour;
import de.tudarmstadt.ukp.lmf.transform.DBConfig;
import de.tudarmstadt.ukp.lmf.transform.LMFDBTransformer;
import de.tudarmstadt.ukp.lmf.transform.StringUtils;
import de.tudarmstadt.ukp.lmf.transform.ontowiktionary.WiktionaryLabelManager.PragmaticLabel;
/**
* Converts OntoWiktionary into UBY-LMF.
*/
public class OntoWiktionaryTransformer extends LMFDBTransformer {
// The embracing lexicon instance.
protected Lexicon lexicon;
// JWKTL Wiktionary object
protected final IWiktionaryEdition wkt;
// Language of Wiktionary edition that should be transformed
protected final ILanguage wktLang;
// A string representation (YYYY-MM-DD) of the dump date.
protected final String wktDate;
// JWKTL Entry iterator
protected final IWiktionaryIterator<IWiktionaryEntry> entryIterator;
// Current entry number
protected int currentEntryNr = 0;
// Handler for Wiktionary's pragmatic labels.
protected WiktionaryLabelManager labelManager;
// Cache of unsaved word forms defined by Wiktionary word form labels.
protected final Map<String, List<WordForm>> wordForms;
// Cache of unsaved subcategorization frames.
protected final SortedMap<String, SubcategorizationFrame> subcatFrames;
protected OntoWiktionary ontoWiktionary;
protected Iterator<OntoWiktionaryConcept> synsetIter;
protected final String jwktlVersion;
protected final String dtd_version;
static int exampleIdx = 1;
static int subcatFrameIdx = 1;
static int syntacticBehaviourIdx = 1;
/**
* @param dbConfig - Database configuration of LMF database
* @param wkt - JWKTL Wiktionary Object
* @throws FileNotFoundException
*/
public OntoWiktionaryTransformer(final DBConfig dbConfig,
final OntoWiktionary ontoWiktionary,
final IWiktionaryEdition wkt, final ILanguage wktLang,
final String wktDate, final String dtd) throws IOException {
super(dbConfig);
this.ontoWiktionary = ontoWiktionary;
this.wkt = wkt;
this.wktLang = wktLang;
this.wktDate = wktDate;
this.entryIterator = wkt.getAllEntries();
this.wordForms = new TreeMap<String, List<WordForm>>();
this.subcatFrames = new TreeMap<String, SubcategorizationFrame>();
this.labelManager = WiktionaryLMFMap.createLabelManager();
jwktlVersion = /*JWKTL.getVersion() - version clash!*/ "1.0.0";
dtd_version = dtd;
}
@Override
protected String getResourceAlias() {
return "OntoWkt" + wktLang.getISO639_1().toUpperCase();
};
@Override
protected LexicalResource createLexicalResource() {
LexicalResource resource = new LexicalResource();
GlobalInformation glInformation = new GlobalInformation();
glInformation.setLabel("OntoWiktionary " + wktLang.getName()
+ " edition, dump of 2013/02, JWKTL "
+ jwktlVersion);
resource.setGlobalInformation(glInformation);
resource.setName("OntoWiktionary" + wktLang.getISO639_1().toUpperCase());
resource.setDtdVersion(dtd_version);
return resource;
}
@Override
protected Lexicon createNextLexicon() {
if (lexicon != null)
return null;
lexicon = new Lexicon();
String lmfLang = WiktionaryLMFMap.mapLanguage(wktLang);
lexicon.setId(getLmfId(Lexicon.class, "lexiconWkt" + lmfLang));
lexicon.setLanguageIdentifier(lmfLang);
lexicon.setName("OntoWiktionary" + wktLang.getISO639_1().toUpperCase());
return lexicon;
}
@Override
protected LexicalEntry getNextLexicalEntry() {
/*if (!entryIterator.hasNext() || currentEntryNr > 100000) {
return null;
}*/
// If we're finished, convert the semantic relations and free resources.
if (!entryIterator.hasNext()) {
System.out.println("PROCESS SENSE RELATIONS");
convertSemanticRelations();
return null;
}
if (currentEntryNr % 1000 == 0) {
System.out.println("PROCESSED " + currentEntryNr + " ENTRIES");
}
IWiktionaryEntry wktEntry = null;
while (entryIterator.hasNext()){
wktEntry = entryIterator.next();
if (wktLang.equals(wktEntry.getWordLanguage()))
break;
}
// Lexical entry.
LexicalEntry entry = new LexicalEntry();
entry.setId(getLmfId(LexicalEntry.class, getEntryId(wktEntry)));
EPartOfSpeech pos = WiktionaryLMFMap.mapPos(wktEntry);
entry.setPartOfSpeech(pos);
// Lemma
String word = convert(wktEntry.getWord(), 1000);
Lemma lemma = new Lemma();
lemma.setFormRepresentations(createFormRepresentationList(word, wktEntry.getWordLanguage()));
entry.setLemma(lemma);
// Senses.
List<Sense> senses = new ArrayList<Sense>();
for (IWiktionarySense wktSense : wktEntry.getSenses()) {
if (considerSense(wktSense)) {
Sense sense = wktSenseToLMFSense(wktSense, wktEntry, entry);
senses.add(sense);
}
wktSense = null;
}
entry.setSenses(senses);
// Related forms.
List<IWiktionaryRelation> relations = wktEntry.getRelations();
if (relations != null) {
List<RelatedForm> relatedForms = new ArrayList<RelatedForm>();
for (IWiktionaryRelation relation : relations) {
ERelTypeMorphology relType = WiktionaryLMFMap.mapMorphologicalRelation(relation.getRelationType());
if (relType == null)
continue;
RelatedForm form = new RelatedForm();
form.setRelType(relType);
form.setFormRepresentations(createFormRepresentationList(relation.getTarget(), wktEntry.getWordLanguage()));
relatedForms.add(form);
}
entry.setRelatedForms(relatedForms);
}
// Word forms.
convertWordForms(wktEntry, entry);
wktEntry = null;
currentEntryNr++;
return entry;
}
protected Set<String> unknownPronunciationNotes;
protected void convertWordForms(final IWiktionaryEntry wktEntry,
final LexicalEntry entry) {
boolean isNoun = false;
boolean isVerb = false;
boolean isAdjAd = false;
for (PartOfSpeech pos : wktEntry.getPartsOfSpeech())
if (pos == PartOfSpeech.NOUN || pos == PartOfSpeech.PROPER_NOUN
|| pos == PartOfSpeech.FIRST_NAME || pos == PartOfSpeech.LAST_NAME
|| pos == PartOfSpeech.TOPONYM
|| pos == PartOfSpeech.SINGULARE_TANTUM
|| pos == PartOfSpeech.PLURALE_TANTUM
|| pos == PartOfSpeech.PRONOUN
|| pos == PartOfSpeech.PERSONAL_PRONOUN
|| pos == PartOfSpeech.REFLEXIVE_PRONOUN
|| pos == PartOfSpeech.DEMONSTRATIVE_PRONOUN
|| pos == PartOfSpeech.INDEFINITE_PRONOUN
|| pos == PartOfSpeech.POSSESSIVE_PRONOUN
|| pos == PartOfSpeech.RELATIVE_PRONOUN
|| pos == PartOfSpeech.INTERROGATIVE_ADVERB
|| pos == PartOfSpeech.INTERROGATIVE_PRONOUN)
isNoun = true;
else
if (pos == PartOfSpeech.VERB || pos == PartOfSpeech.AUXILIARY_VERB)
isVerb = true;
else
if (pos == PartOfSpeech.ADJECTIVE || pos == PartOfSpeech.ADVERB)
isAdjAd = true;
List<WordForm> wordForms = new ArrayList<WordForm>();
// Add lemma form (for inflectable word forms).
WordForm lemmaForm = new WordForm();
lemmaForm.setFormRepresentations(createFormRepresentationList(wktEntry.getWord(), wktEntry.getWordLanguage()));
if (isNoun) {
lemmaForm.setCase(ECase.nominative);
lemmaForm.setGrammaticalNumber(EGrammaticalNumber.singular);
} else
if (isVerb) {
lemmaForm.setVerbFormMood(EVerbFormMood.infinitive);
} else
if (isAdjAd) {
lemmaForm.setDegree(EDegree.positive);
} else {
lemmaForm = null;
}
if (lemmaForm != null)
wordForms.add(lemmaForm);
// Add inflected word forms.
List<IWiktionaryWordForm> wktWordForms = wktEntry.getWordForms();
if (wktWordForms != null) {
for (IWiktionaryWordForm wktWordForm : wktWordForms) {
String writtenForm = convert(wktWordForm.getWordForm(), 255);
if (writtenForm == null || writtenForm.isEmpty())
continue;
if (writtenForm.contains("[")) {
// System.err.println("Skipping word form: " + writtenForm);
continue;
}
WordForm newWordForm = new WordForm();
newWordForm.setCase(WiktionaryLMFMap.mapCase(wktWordForm));
newWordForm.setDegree(WiktionaryLMFMap.mapDegree(wktWordForm));
newWordForm.setPerson(WiktionaryLMFMap.mapPerson(wktWordForm));
//newWordForm.setGrammaticalGender(WiktionaryLMFMap.mapGender(wktWordForm.get));
newWordForm.setGrammaticalNumber(WiktionaryLMFMap.mapGrammaticalNumber(wktWordForm));
newWordForm.setVerbFormMood(WiktionaryLMFMap.mapVerbFormMood(wktWordForm));
newWordForm.setTense(WiktionaryLMFMap.mapTense(wktWordForm));
if (newWordForm.getVerbFormMood() == null && isVerb)
newWordForm.setVerbFormMood(EVerbFormMood.indicative);
if (newWordForm.getVerbFormMood() == EVerbFormMood.subjunctive)
newWordForm.setTense(null);
// Check if a similar word form exists.
WordForm wordForm = null;
for (WordForm wf : wordForms) {
if (newWordForm.getCase() != null && wf.getCase() != null
&& newWordForm.getCase() != wf.getCase())
continue;
if (newWordForm.getDegree() != null && wf.getDegree() != null
&& newWordForm.getDegree() != wf.getDegree())
continue;
if (newWordForm.getPerson() != null && wf.getPerson() != null
&& newWordForm.getPerson() != wf.getPerson())
continue;
if (newWordForm.getGrammaticalGender() != null && wf.getGrammaticalGender() != null
&& newWordForm.getGrammaticalGender() != wf.getGrammaticalGender())
continue;
if (newWordForm.getGrammaticalNumber() != null && wf.getGrammaticalNumber() != null
&& newWordForm.getGrammaticalNumber() != wf.getGrammaticalNumber())
continue;
if (newWordForm.getVerbFormMood() != null && wf.getVerbFormMood() != null
&& newWordForm.getVerbFormMood() != wf.getVerbFormMood())
continue;
if (newWordForm.getTense() != null && wf.getTense() != null
&& newWordForm.getTense() != wf.getTense())
continue;
String key1 = newWordForm.getCase() + " " + newWordForm.getDegree()
+ " " + newWordForm.getPerson() + " " + newWordForm.getGrammaticalNumber()
+ " " + newWordForm.getVerbFormMood() + " " + newWordForm.getTense();
String key2 = wf.getCase() + " " + wf.getDegree()
+ " " + wf.getPerson() + " " + wf.getGrammaticalNumber()
+ " " + wf.getVerbFormMood() + " " + wf.getTense();
if (key1.equals(key2)) {
wordForm = wf;
break;
}
// else
// System.err.println(wktEntry.getWord() + " " + key1 + "\n"
// + wktEntry.getWord() + " " + key2 + "\n");
}
if (wordForm == null) {
wordForm = newWordForm;
wordForm.setFormRepresentations(new ArrayList<FormRepresentation>());
wordForms.add(wordForm);
}
// If this is a noun, remove the determiner and identify the gender.
if (isNoun) {
int idx = writtenForm.indexOf(' ');
if (idx >= 0) {
EGrammaticalGender gender = null;
String determiner = writtenForm.substring(0, idx);
if ("der".equals(determiner) || "(der)".equals(determiner))
gender = EGrammaticalGender.masculine;
else
if ("die".equals(determiner) || "(die)".equals(determiner))
gender = EGrammaticalGender.feminine;
else
if ("das".equals(determiner) || "(das)".equals(determiner))
gender = EGrammaticalGender.neuter;
else
if (!"des".equals(determiner) && !"(des)".equals(determiner)
&& !"dem".equals(determiner) && !"(dem)".equals(determiner)
&& !"den".equals(determiner) && !"(den)".equals(determiner))
idx = -1;
if (idx >= 0) {
writtenForm = writtenForm.substring(idx + 1);
if (wordForm == lemmaForm && gender != null)
wordForm.setGrammaticalGender(gender);
}
}
}
// Add a new form representation if the written form does not yet exist.
boolean found = false;
for (FormRepresentation fp : wordForm.getFormRepresentations())
if (fp.getWrittenForm().equals(writtenForm)) {
found = true;
break;
}
if (!found) {
FormRepresentation fp = new FormRepresentation();
fp.setWrittenForm(writtenForm);
fp.setLanguageIdentifier(lexicon.getLanguageIdentifier());
wordForm.getFormRepresentations().add(fp);
}
}
}
// Add phonetic forms.
List<IPronunciation> pronunciations = wktEntry.getPronunciations();
if (pronunciations != null) {
for (IPronunciation pronunciation : pronunciations) {
// Only save IPA pronunciations.
if (pronunciation.getType() != PronunciationType.IPA)
continue;
// Don't save empty pronunciations.
String phoneticForm = pronunciation.getText();
if (phoneticForm == null || phoneticForm.isEmpty()
|| "...".equals(phoneticForm) || "…".equals(phoneticForm))
continue;
// Don't save pronunciations containing a dash or a wiki link.
if (phoneticForm.startsWith("[")) {
phoneticForm = phoneticForm.substring(1);
int idx = phoneticForm.indexOf(']');
if (idx >= 0)
phoneticForm = phoneticForm.substring(0, idx);
}
if (phoneticForm.startsWith("/")) {
phoneticForm = phoneticForm.substring(1);
int idx = phoneticForm.indexOf('/');
if (idx >= 0)
phoneticForm = phoneticForm.substring(0, idx);
}
if (phoneticForm.contains("–") || phoneticForm.contains("|")
|| phoneticForm.contains("[") || phoneticForm.contains("]")) {
// System.err.println("Skipping phonetic form: " + phoneticForm);
continue;
}
WordForm newWordForm = new WordForm();
if (lemmaForm != null) {
newWordForm.setCase(lemmaForm.getCase());
newWordForm.setDegree(lemmaForm.getDegree());
newWordForm.setPerson(lemmaForm.getPerson());
newWordForm.setGrammaticalGender(lemmaForm.getGrammaticalGender());
newWordForm.setGrammaticalNumber(lemmaForm.getGrammaticalNumber());
newWordForm.setVerbFormMood(lemmaForm.getVerbFormMood());
newWordForm.setTense(lemmaForm.getTense());
}
String note = pronunciation.getNote();
String geographicalVariant = null;
if (note != null && !note.isEmpty()) {
if (note.contains("Sg."))
newWordForm.setGrammaticalNumber(EGrammaticalNumber.singular);
else
if (note.contains("Pl."))
newWordForm.setGrammaticalNumber(EGrammaticalNumber.plural);
else
if ("Gen.".equals(note))
newWordForm.setCase(ECase.genitive);
else
if ("Dat.".equals(note))
newWordForm.setCase(ECase.dative);
else
if ("Akk.".equals(note))
newWordForm.setCase(ECase.accusative);
else
if ("Prät.".equals(note)) {
newWordForm.setPerson(EPerson.first);
newWordForm.setGrammaticalNumber(EGrammaticalNumber.singular);
newWordForm.setTense(ETense.past);
newWordForm.setVerbFormMood(EVerbFormMood.indicative);
}
else
if ("Komp.".equals(note))
newWordForm.setDegree(EDegree.comparative);
else
if ("Sup.".equals(note))
newWordForm.setDegree(EDegree.superlative);
else
if ("Part.".equals(note)) // Partizip II
newWordForm.setVerbFormMood(EVerbFormMood.participle);
//newWordForm.setTense(ETense.past);
else
if ("UK".equals(note) || "RP".equals(note)
|| note.startsWith("RP ") || "Received Pronunciation".equals(note)
|| note.contains("British") || note.contains("England")
|| note.contains("English") || note.contains("Scotland")
|| note.contains("Scots") || "GB".equals(note)) {
geographicalVariant = "UK";
} else
if ("US".equals(note) || note.startsWith("US ") || "U.S.".equals(note)
|| note.endsWith(" US") || note.toUpperCase().contains("GENAM")
|| note.equals("GAm")
|| note.contains("Southern US") || note.contains("Northern US")
|| note.contains("New York") || "NYC".equals(note) || "NY".equals(note)
|| note.contains("St. Louis") || "STL".equals(note))
geographicalVariant = "US";
else
if ("CA".equals(note) || "Canada".equals(note)
|| "Canadian".equals(note) || "CanE".equals(note)
|| "CaE".equals(note))
geographicalVariant = "CA";
else
if ("AU".equals(note) || "AUSE".equals(note.toUpperCase())
|| "AUSEN".equals(note.toUpperCase())
|| "Australia".equals(note))
geographicalVariant = "AU";
else
if ("NZ".equals(note) || "New Zealand".equals(note))
geographicalVariant = "NZ";
else
if ("IE".equals(note) || "Ireland".equals(note) || "Irish".equals(note))
geographicalVariant = "IE";
else
if ("Deutschland".equals(note))
geographicalVariant = "DE";
else
if ("Österreich".equals(note) || note.contains("österr."))
geographicalVariant = "AT";
else
if ("Schweiz".equals(note))
geographicalVariant = "CH";
else
if (note.contains("South Africa") || "S Africa".equals(note)
|| "SAE".equals(note))
geographicalVariant = "RSA";
else
if (note.contains("North America") || "Puerto Rican".equals(note)
|| note.contains("American"))
geographicalVariant = note;
else
if (!"letter name".equals(note) && !"phoneme".equals(note)) {
// Save a new empty word form.
newWordForm.setCase(null);
newWordForm.setDegree(null);
newWordForm.setPerson(null);
newWordForm.setGrammaticalGender(null);
newWordForm.setGrammaticalNumber(null);
newWordForm.setVerbFormMood(null);
newWordForm.setTense(null);
/*if (unknownPronunciationNotes == null)
unknownPronunciationNotes = new TreeSet<String>();
if (unknownPronunciationNotes.add(note))
System.err.println("PRONUNCIATION: >" + note + "<");*/
}
}
// Check if a similar word form exists.
WordForm wordForm = null;
for (WordForm wf : wordForms) {
if (newWordForm.getCase() != null && wf.getCase() != null
&& newWordForm.getCase() != wf.getCase())
continue;
if (newWordForm.getDegree() != null && wf.getDegree() != null
&& newWordForm.getDegree() != wf.getDegree())
continue;
if (newWordForm.getPerson() != null && wf.getPerson() != null
&& newWordForm.getPerson() != wf.getPerson())
continue;
if (newWordForm.getGrammaticalGender() != null && wf.getGrammaticalGender() != null
&& newWordForm.getGrammaticalGender() != wf.getGrammaticalGender())
continue;
if (newWordForm.getGrammaticalNumber() != null && wf.getGrammaticalNumber() != null
&& newWordForm.getGrammaticalNumber() != wf.getGrammaticalNumber())
continue;
if (newWordForm.getVerbFormMood() != null && wf.getVerbFormMood() != null
&& newWordForm.getVerbFormMood() != wf.getVerbFormMood())
continue;
if (newWordForm.getTense() != null && wf.getTense() != null
&& newWordForm.getTense() != wf.getTense())
continue;
String key1 = newWordForm.getCase() + " " + newWordForm.getDegree()
+ " " + newWordForm.getPerson() + " " + newWordForm.getGrammaticalNumber()
+ " " + newWordForm.getVerbFormMood() + " " + newWordForm.getTense();
String key2 = wf.getCase() + " " + wf.getDegree()
+ " " + wf.getPerson() + " " + wf.getGrammaticalNumber()
+ " " + wf.getVerbFormMood() + " " + wf.getTense();
if (key1.equals(key2)) {
wordForm = wf;
break;
} /*else
if (newWordForm.getCase() != null
|| newWordForm.getDegree() != null
|| newWordForm.getGrammaticalGender() != null
|| newWordForm.getGrammaticalNumber() != null
|| newWordForm.getPerson() != null
|| newWordForm.getTense() != null
|| newWordForm.getVerbFormMood() != null)
System.err.println("* " + wktEntry.getWord() + " " + key1 + "\n"
+ "* "+ wktEntry.getWord() + " " + key2 + "\n");*/
}
if (wordForm == null) {
wordForm = newWordForm;
wordForm.setFormRepresentations(new ArrayList<FormRepresentation>());
wordForms.add(wordForm);
}
// Add the phonetic form if there's only one written form.
String writtenForm = null;
List<FormRepresentation> fps = wordForm.getFormRepresentations();
for (FormRepresentation fp : fps)
if (writtenForm == null)
writtenForm = fp.getWrittenForm();
else
if (fp.getWrittenForm() != null && !fp.getWrittenForm().equals(writtenForm)) {
writtenForm = null;
break;
}
if (fps.size() == 1 && fps.get(0).getPhoneticForm() == null) {
FormRepresentation fp = wordForm.getFormRepresentations().get(0);
fp.setPhoneticForm(phoneticForm);
fp.setGeographicalVariant(geographicalVariant);
} else {
FormRepresentation fp = new FormRepresentation();
fp.setWrittenForm(writtenForm);
fp.setPhoneticForm(phoneticForm);
fp.setGeographicalVariant(geographicalVariant);
fp.setLanguageIdentifier(lexicon.getLanguageIdentifier());
fps.add(fp);
}
}
}
if (!wordForms.isEmpty())
entry.setWordForms(wordForms);
}
protected void convertSemanticRelations() {
int senseCount = 0;
for (IWiktionaryEntry wktEntry : wkt.getAllEntries()) {
if (!wktLang.equals(wktEntry.getWordLanguage()))
continue;
for (IWiktionarySense wktSense : wktEntry.getSenses()) {
if (!considerSense(wktSense))
continue;
String sourceId = getLmfId(Sense.class, getSenseId(wktSense.getKey()));
Sense source = (Sense) getLmfObjectById(Sense.class, sourceId);
if (source != null)
convertSemanticRelations(source, wktSense, wktEntry);
source = null;
wktSense = null;
if (++senseCount % 500 == 0) {
System.out.println("SAVING RELATIONS / PROCESSED " + senseCount + " SENSES");
tx.commit();
session.close();
session = sessionFactory.openSession();
tx = session.beginTransaction();
}
}
wktEntry = null;
}
ontoWiktionary.freeSemanticRelations();
}
protected void convertSemanticRelations(final Sense source,
final IWiktionarySense wktSense,
final IWiktionaryEntry wktEntry) {
// Sense relations (SenseRelation class).
List<OntoWiktionarySemanticRelation> owktRelations;
try {
owktRelations = ontoWiktionary.getSemanticRelations(wktSense.getKey());
} catch (IOException e) {
throw new RuntimeException(e);
}
List<SenseRelation> senseRelations = new ArrayList<SenseRelation>();
if (wktSense.getRelations() != null) {
for (IWiktionaryRelation wktRelation : wktSense.getRelations()) {
if (wktRelation.getRelationType() == null || wktRelation.getTarget().isEmpty()) {
continue;
}
SenseRelation senseRelation = new SenseRelation();
senseRelation.setRelType(WiktionaryLMFMap.mapRelationType(wktRelation.getRelationType()));
senseRelation.setRelName(WiktionaryLMFMap.mapRelationName(wktRelation.getRelationType()));
if (senseRelation.getRelType() == null) {
continue;
}
// Find a suitable relation in OntoWiktionary.
if (owktRelations != null) {
Iterator<OntoWiktionarySemanticRelation> owktRelationIter = owktRelations.iterator();
while (owktRelationIter.hasNext()) {
OntoWiktionarySemanticRelation owktRelation = owktRelationIter.next();
if (!wktRelation.getRelationType().equals(owktRelation.getRelationType())
|| !wktRelation.getTarget().equals(owktRelation.getTargetWordForm()))
continue;
owktRelationIter.remove();
String targetId = getLmfId(Sense.class, getSenseId(owktRelation.getTargetSenseId()));
if (!"???".equals(targetId)) {
Sense target = (Sense) getLmfObjectById(Sense.class, targetId);
if (target != null)
senseRelation.setTarget(target);
// else
// System.err.println("SenseRelation.Target not found: " + owktRelation.getTargetSenseId());
target = null;
}
break;
}
}
// Save target word as targetFormRepresentation.
FormRepresentation targetFormRepresentation = new FormRepresentation();
targetFormRepresentation.setWrittenForm(convert(wktRelation.getTarget(), 255));
targetFormRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(wktEntry.getWordLanguage()));
senseRelation.setFormRepresentation(targetFormRepresentation);
senseRelations.add(senseRelation);
}
}
// Save inferred relations.
if (owktRelations != null) {
for (OntoWiktionarySemanticRelation owktRelation : owktRelations) {
SenseRelation senseRelation = new SenseRelation();
senseRelation.setRelType(WiktionaryLMFMap.mapRelationType(owktRelation.getRelationType()));
senseRelation.setRelName(WiktionaryLMFMap.mapRelationName(owktRelation.getRelationType()) + "-AUTO");
if (senseRelation.getRelType() == null)
continue;
String targetId = getLmfId(Sense.class, getSenseId(owktRelation.getTargetSenseId()));
if (!"???".equals(targetId)) {
Sense target = (Sense) getLmfObjectById(Sense.class, targetId);
if (target != null)
senseRelation.setTarget(target);
// else
// System.err.println("SenseRelation.Target not found: " + owktRelation.getTargetSenseId());
target = null;
}
// Save target word as targetFormRepresentation.
FormRepresentation targetFormRepresentation = new FormRepresentation();
targetFormRepresentation.setWrittenForm(convert(owktRelation.getTargetWordForm(), 255));
targetFormRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(wktEntry.getWordLanguage()));
senseRelation.setFormRepresentation(targetFormRepresentation);
senseRelations.add(senseRelation);
}
}
source.setSenseRelations(senseRelations);
saveList(source, senseRelations);
}
/** Returns true if this sense should be used for the UBY database. */
protected boolean considerSense(final IWiktionarySense wktSense) {
return wktSense.getGloss() != null;
}
/** Converts Wiktionary Sense to LMF Sense. */
protected Sense wktSenseToLMFSense(IWiktionarySense wktSense, IWiktionaryEntry wktEntry, LexicalEntry entry){
// Sense and identifier.
Sense sense = new Sense();
sense.setId(getLmfId(Sense.class, getSenseId(wktSense)));
sense.setIndex(wktSense.getIndex());
// Monolingual external reference.
MonolingualExternalRef monolingualExternalRef = new MonolingualExternalRef();
monolingualExternalRef.setExternalSystem("Wiktionary_"
+ jwktlVersion + "_" + wktDate + "_"
+ wktLang.getISO639_2T() + "_sense");
monolingualExternalRef.setExternalReference(wktSense.getKey());
List<MonolingualExternalRef> monolingualExternalRefs = new LinkedList<MonolingualExternalRef>();
monolingualExternalRefs.add(monolingualExternalRef);
sense.setMonolingualExternalRefs(monolingualExternalRefs);
// Sense Definition (Definition class; type intensionalDefinition).
List<Definition> definitions = new ArrayList<Definition>();
Definition definition = new Definition();
definition.setDefinitionType(EDefinitionType.intensionalDefinition);
definition.setTextRepresentations(createTextRepresentationList(
wktSense.getGloss().getPlainText(), wktEntry.getPage().getEntryLanguage()
));
definitions.add(definition);
sense.setDefinitions(definitions);
// Semantic Labels.
List<SemanticLabel> semanticLabels = createSemanticLabels(entry, sense, wktSense);
if (semanticLabels != null && semanticLabels.size() > 0)
sense.setSemanticLabels(semanticLabels);
// Etymology (Statement class; type etymology).
IWikiString etymology = null;
if (wktEntry.getWordEtymology() != null)
etymology = wktEntry.getWordEtymology();
String etymologyText = convertEtymology(etymology);
if (etymologyText != null && !etymologyText.isEmpty()) {
List<Statement> statements = new LinkedList<Statement>();
Statement statement = new Statement();
statement.setStatementType(EStatementType.etymology);
statement.setTextRepresentations(createTextRepresentationList(
convertEtymology(etymology), wktEntry.getPage().getEntryLanguage()));
statements.add(statement);
definition.setStatements(statements);
}
// Sense examples (SenseExample class; type senseInstance).
List<SenseExample> examples = new ArrayList<SenseExample>();
if (wktSense.getExamples() != null) {
for (IWikiString example : wktSense.getExamples()) {
SenseExample senseExample = new SenseExample();
senseExample.setId(getResourceAlias() + "_SenseExample_" + (exampleIdx++));
senseExample.setExampleType(EExampleType.senseInstance);
senseExample.setTextRepresentations(createTextRepresentationList(
example.getPlainText(), wktEntry.getWordLanguage()
));
examples.add(senseExample);
}
}
sense.setSenseExamples(examples);
// Quotations (Context class; type citation).
List<Context> contexts = new ArrayList<Context>();
if (wktSense.getQuotations() != null) {
for (IQuotation quotation : wktSense.getQuotations()) {
Context context = new Context();
context.setContextType(EContextType.citation);
StringBuilder quotationText = new StringBuilder();
for (IWikiString line : quotation.getLines()) {
quotationText.append(quotationText.length() == 0 ? "" : " ")
.append(line.getPlainText());
}
context.setTextRepresentations(createTextRepresentationList(
quotationText.toString(), wktEntry.getWordLanguage()
));
if (quotation.getSource() != null) {
String source = quotation.getSource().getPlainText();
if (source.length() > 255)
source = source.substring(0, 255);
context.setSource(source);
}
contexts.add(context);
}
}
sense.setContexts(contexts);
// Sense relations (SenseRelation class)
// -- skip (will be done in a separate step!
// Translations (Equivalent class).
if (wktSense.getTranslations() != null) {
List<Equivalent> equivalents = new ArrayList<Equivalent>();
for (IWiktionaryTranslation trans : wktSense.getTranslations()) {
String targetForm = convert(trans.getTranslation(), 255);
if (targetForm == null || targetForm.isEmpty()) {
continue; // Do not save empty translations.
}
String language = WiktionaryLMFMap.mapLanguage(trans.getLanguage());
if (language == null) {
continue; // Do not save translations to unknown languages.
}
Equivalent equivalent = new Equivalent();
equivalent.setWrittenForm(targetForm);
equivalent.setLanguageIdentifier(language);
String transliteration = trans.getTransliteration();
if (transliteration != null && !transliteration.isEmpty()) {
transliteration = convert(transliteration, 255);
equivalent.setTransliteration(transliteration);
}
String additionalInformation = trans.getAdditionalInformation();
if (additionalInformation != null && !additionalInformation.isEmpty()) {
additionalInformation = additionalInformation.replace("{{m}}", "masculine");
additionalInformation = additionalInformation.replace("{{f}}", "feminine");
additionalInformation = additionalInformation.replace("{{n}}", "neuter");
additionalInformation = convert(additionalInformation, 255);
equivalent.setUsage(additionalInformation);
}
equivalents.add(equivalent);
}
sense.setEquivalents(equivalents);
}
return sense;
}
protected List<SemanticLabel> createSemanticLabels(
final LexicalEntry entry, final Sense sense,
final IWiktionarySense wktSense) {
List<SemanticLabel> result = new ArrayList<SemanticLabel>();
// Create semantic labels from part of speech tags.
for (PartOfSpeech p : wktSense.getEntry().getPartsOfSpeech()) {
if (p == null)
continue;
ELabelTypeSemantics semanticLabelType;
String semanticLabelName;
switch (p) {
case TOPONYM:
semanticLabelType = ELabelTypeSemantics.semanticNounClass;
semanticLabelName = ELabelNameSemantics.SEMANTIC_NOUN_CLASS_TOPONYM;
break;
case SINGULARE_TANTUM:
semanticLabelType = ELabelTypeSemantics.semanticNounClass;
semanticLabelName = ELabelNameSemantics.SEMANTIC_NOUN_CLASS_ONLY_SINGULAR;
break;
case PLURALE_TANTUM:
semanticLabelType = ELabelTypeSemantics.semanticNounClass;
semanticLabelName = ELabelNameSemantics.SEMANTIC_NOUN_CLASS_ONLY_PLURAL;
break;
case SALUTATION:
semanticLabelType = ELabelTypeSemantics.interjectionClass;
semanticLabelName = ELabelNameSemantics.INTERJECTION_SALUTATION;
break;
case ONOMATOPOEIA:
semanticLabelType = ELabelTypeSemantics.interjectionClass;
semanticLabelName = ELabelNameSemantics.INTERJECTION_ONOMATOPOEIA;
break;
case IDIOM:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_IDIOM;
break;
case COLLOCATION:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_COLLOCATION;
break;
case PROVERB:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_PROVERB;
break;
case MNEMONIC:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_MNEMONIC;
break;
case MODAL_PARTICLE:
semanticLabelType = ELabelTypeSemantics.discourseFunction;
semanticLabelName = ELabelNameSemantics.DISCOURSE_FUNCTION_MODAL_PARTICLE;
break;
case FOCUS_PARTICLE:
semanticLabelType = ELabelTypeSemantics.discourseFunction;
semanticLabelName = ELabelNameSemantics.DISCOURSE_FUNCTION_FOCUS_PARTICLE;
break;
case INTENSIFYING_PARTICLE:
semanticLabelType = ELabelTypeSemantics.discourseFunction;
semanticLabelName = ELabelNameSemantics.DISCOURSE_FUNCTION_INTENSIFYING_PARTICLE;
break;
default:
continue;
}
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setType(semanticLabelType);
semanticLabel.setLabel(semanticLabelName);
result.add(semanticLabel);
}
// Process labels encoded in the sense definition.
IWikiString senseDefinition = wktSense.getGloss();
List<PragmaticLabel> labels = labelManager.parseLabels(
senseDefinition.getText(), wktSense.getEntry().getWord());
if (labels != null) {
List<String> subcatLabels = new LinkedList<String>();
EAuxiliary auxiliary = null;
ESyntacticProperty syntacticProperty = null;
for (PragmaticLabel label : labels) {
String labelGroup = label.getLabelGroup();
if (labelGroup == null || labelGroup.length() == 0)
continue;
String[] labelInfo = labelManager.getWordFormLabel(label);
if (labelInfo != null) {
// WordForm.
/* if (!labelInfo[0].equals("WordForm"))
continue;
String targetWord = labelManager.extractTargetWordForm(senseDefinition.getText());
IWiktionaryEntry wktEntry = wktSense.getEntry();
// System.err.println("WORD FORM: " + targetWord + " -> " + wktEntry.getWord());
WordForm wordForm = new WordForm();
if (!labelInfo[1].isEmpty())
wordForm.setCase(ECase.valueOf(labelInfo[1]));
if (!labelInfo[2].isEmpty())
wordForm.setGrammaticalNumber(EGrammaticalNumber.valueOf(labelInfo[2]));
if (!labelInfo[3].isEmpty())
wordForm.setVerbFormMood(EVerbFormMood.valueOf(labelInfo[3]));
if (!labelInfo[4].isEmpty())
wordForm.setTense(ETense.valueOf(labelInfo[4]));
if (!labelInfo[5].isEmpty())
wordForm.setGrammaticalGender(EGrammaticalGender.valueOf(labelInfo[5]));
if (!labelInfo[6].isEmpty())
wordForm.setDegree(EDegree.valueOf(labelInfo[6]));
wordForm.setFormRepresentations(createFormRepresentationList(
wktEntry.getWord(), wktEntry.getWordLanguage()));
for (IWiktionaryEntry targetEntry : wkt.getEntriesForWord(targetWord)) {
// Ignore entries of a different language.
if (targetEntry.getWordLanguage() == null
|| !targetEntry.getWordLanguage().equals(wktEntry.getWordLanguage()))
continue;
// Ignore entries of a different part of speech.
if (targetEntry.getPartOfSpeech() == null
|| !targetEntry.getPartOfSpeech().equals(wktEntry.getPartOfSpeech()))
continue;
String entryId = getLmfId(LexicalEntry.class, getEntryId(targetEntry)); // this only works if the entire resource is converted!
LexicalEntry lexEntry = (LexicalEntry) getLmfObjectById(LexicalEntry.class, entryId);
if (lexEntry != null) {
// If the entry already exists then save directly to it
List<WordForm> wordFormList = lexEntry.getWordForms();
if (wordFormList == null) {
wordFormList = new ArrayList<WordForm>();
lexEntry.setWordForms(wordFormList);
}
wordFormList.add(wordForm);
saveList(lexEntry, lexEntry.getWordForms());
} else {
// If the lexical entry does not yet exist, then
// save the wordForms temporarily.
List<WordForm> wordFormList = wordForms.get(entryId);
if (wordFormList == null) {
wordFormList = new ArrayList<WordForm>();
wordForms.put(entryId, wordFormList);
}
wordFormList.add(wordForm);
}
}*/
} else
if ("syntax:gram:auxiliary".equals(labelGroup)) {
// LexemeProperty:auxiliary.
if ("habenSein".equals(label.getStandardizedLabel()))
continue; //TODO: Add enum value!
auxiliary = EAuxiliary.valueOf(label.getStandardizedLabel());
} else
if ("syntax:gram:synprop".equals(labelGroup)) {
// LexemeProperty:syntacticProperty.
syntacticProperty = ESyntacticProperty.valueOf(label.getStandardizedLabel());
} else
if ("syntax:gram:subcat".equals(labelGroup)) {
// SubcategorizationFrame.
subcatLabels.add(label.getStandardizedLabel());
} else
if ("syntax:gram:nounClass".equals(labelGroup)) {
// SemanticLabel:semanticNounClass.
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setLabel(StringUtils.replaceNonUtf8(label.getStandardizedLabel()));
semanticLabel.setType(ELabelTypeSemantics.semanticNounClass);
result.add(semanticLabel);
} else
if ("syntax:gram:usage".equals(labelGroup)) {
// SemanticLabel:usage.
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setLabel(StringUtils.replaceNonUtf8(label.getStandardizedLabel()));
semanticLabel.setType(ELabelTypeSemantics.usage);
result.add(semanticLabel);
} else {
// Semantic labels.
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setLabel(StringUtils.replaceNonUtf8(label.getLabel()));
if (labelGroup.startsWith("dom"))
semanticLabel.setType(ELabelTypeSemantics.domain);
else
if (labelGroup.startsWith("reg") || labelGroup.startsWith("dia"))
semanticLabel.setType(ELabelTypeSemantics.regionOfUsage);
else
if (labelGroup.startsWith("phas") || labelGroup.startsWith("strat") || labelGroup.startsWith("eval"))
semanticLabel.setType(ELabelTypeSemantics.register);
else
if (labelGroup.startsWith("temp"))
semanticLabel.setType(ELabelTypeSemantics.timePeriodOfUsage);
else
if (labelGroup.startsWith("freq") || labelGroup.startsWith("norm"))
semanticLabel.setType(ELabelTypeSemantics.usage);
else
continue;
result.add(semanticLabel); //TODO: standardize
}
// TODO: Additional labels: etym request syntax:form syntax:pos syntax:gram
}
// Create a subcategorization frame if no syntactic label exists.
String lpKey = (auxiliary != null ? auxiliary.ordinal() : "")
+ "_" + (syntacticProperty != null ? syntacticProperty.ordinal() : "");
if (subcatLabels.isEmpty() && !"_".equals(lpKey))
subcatLabels.add("");
for (String subcatLabel : subcatLabels) {
// Create subcategorization frame.
String scfKey = subcatLabel + ":" + lpKey;
SubcategorizationFrame subcatFrame = subcatFrames.get(scfKey);
if (subcatFrame == null) {
LexemeProperty lexemeProperty = new LexemeProperty();
lexemeProperty.setAuxiliary(auxiliary);
lexemeProperty.setSyntacticProperty(syntacticProperty);
subcatFrame = new SubcategorizationFrame();
subcatFrame.setId(getResourceAlias() + "_SubcatFrame_" + (subcatFrameIdx++));
subcatFrame.setSubcatLabel(subcatLabel);
subcatFrame.setLexemeProperty(lexemeProperty);
subcatFrames.put(scfKey, subcatFrame);
}
// Create syntactic behavior.
SyntacticBehaviour sb = new SyntacticBehaviour();
sb.setSubcategorizationFrame(subcatFrame);
sb.setId(getResourceAlias() + "_SyntacticBehaviour_" + (syntacticBehaviourIdx++));
sb.setSense(sense);
if (entry.getSyntacticBehaviours() == null)
entry.setSyntacticBehaviours(new LinkedList<SyntacticBehaviour>());
entry.getSyntacticBehaviours().add(sb);
}
}
return result;
}
protected List<TextRepresentation> createTextRepresentationList(
final String writtenText, final ILanguage language) {
List<TextRepresentation> result = new ArrayList<TextRepresentation>();
TextRepresentation textRepresentation = new TextRepresentation();
textRepresentation.setWrittenText(convert(writtenText));
textRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(language));
result.add(textRepresentation);
return result;
}
protected List<FormRepresentation> createFormRepresentationList(
final String writtenForm, final ILanguage language) {
List<FormRepresentation> result = new ArrayList<FormRepresentation>();
FormRepresentation formRepresentation = new FormRepresentation();
formRepresentation.setWrittenForm(convert(writtenForm, 255));
formRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(language));
result.add(formRepresentation);
return result;
}
@Override
protected SubcategorizationFrame getNextSubcategorizationFrame() {
return (subcatFrames.isEmpty() ? null : subcatFrames.remove(subcatFrames.firstKey()));
}
@Override
protected Synset getNextSynset() {
// If we haven't started yet, initialize the iterator.
if (synsetIter == null)
try {
synsetIter = ontoWiktionary.getStreamedConcepts().iterator();
} catch (Exception e) {
throw new RuntimeException(e);
}
// If we're finished, convert the synset relations and free resources.
if (!synsetIter.hasNext()) {
synsetIter = null;
convertSynsetRelations();
ontoWiktionary.freeConcepts();
return null;
}
// Check if at least one sense exists.
OntoWiktionaryConcept owktSynset = synsetIter.next();
List<Sense> senses = new LinkedList<Sense>();
for (String lexicalization : owktSynset.getLexicalizations()) {
String senseId = getLmfId(Sense.class, getSenseId(lexicalization));
Sense sense = (Sense) getLmfObjectById(Sense.class, senseId);
if (sense == null) {
// Caused by different sense selection (e.g., inflected forms)
// System.err.println("Sense not found: " + lexicalization);
continue;
}
if (sense.getSynset() != null) {
System.err.println("Inconsistent synset structure for " + lexicalization);
}
senses.add(sense);
}
if (senses.size() == 0)
return getNextSynset();
// Synset.
Synset synset = new Synset();
synset.setId(getLmfId(Synset.class, getSynsetId(owktSynset.getConceptId())));
// MonolingualExternalRef.
List<MonolingualExternalRef> monolingualExternalRefs = new LinkedList<MonolingualExternalRef>();
MonolingualExternalRef monolingualExternalRef = new MonolingualExternalRef();
monolingualExternalRef.setExternalSystem("OntoWiktionary" + wktLang.getISO639_1().toUpperCase() + "_ConceptID");
monolingualExternalRef.setExternalReference(owktSynset.getConceptId());
monolingualExternalRefs.add(monolingualExternalRef);
synset.setMonolingualExternalRefs(monolingualExternalRefs);
// Senses.
for (Sense sense : senses)
sense.setSynset(synset);
synset.setSenses(senses);
return synset;
}
protected void convertSynsetRelations() {
try {
synsetIter = ontoWiktionary.getConcepts().iterator();
} catch (Exception e) {
throw new RuntimeException(e);
}
int conceptCount = 0;
while (synsetIter.hasNext()) {
OntoWiktionaryConcept owktSynset = synsetIter.next();
Synset source = (Synset) getLmfObjectById(Synset.class,
getLmfId(Synset.class, getSynsetId(owktSynset.getConceptId())));
if (source == null) {
// System.err.println("Source concept not found: " + owktSynset.getConceptId());
continue;
}
// SynsetRelation.
List<SynsetRelation> synsetRelations = new LinkedList<SynsetRelation>();
addSynsetRelations(synsetRelations, owktSynset.getSubsumesRelations(),
ERelTypeSemantics.taxonomic, "subsumes", source);
addSynsetRelations(synsetRelations, owktSynset.getSubsumedByRelations(),
ERelTypeSemantics.taxonomic, "subsumedBy", source);
addSynsetRelations(synsetRelations, owktSynset.getRelatedConcepts(),
ERelTypeSemantics.association, "related", source);
source.setSynsetRelations(synsetRelations);
saveCascade(source);
if (++conceptCount % 1000 == 0) {
System.out.println("SAVING RELATIONS / PROCESSED " + conceptCount + " SYNSETS");
tx.commit();
session.close();
session = sessionFactory.openSession();
tx = session.beginTransaction();
}
}
synsetIter = null;
}
protected void addSynsetRelations(final List<SynsetRelation> synsetRelations,
final Iterable<String> relationTargets,
final ERelTypeSemantics relType, final String relName,
final Synset source) {
for (String targetID : relationTargets) {
Synset target = (Synset) getLmfObjectById(Synset.class,
getLmfId(Synset.class, getSynsetId(targetID)));
if (target == null) {
// System.err.println("Target concept not found: " + targetID);
continue;
}
SynsetRelation synsetRelation = new SynsetRelation();
synsetRelation.setRelType(relType);
synsetRelation.setRelName(relName);
synsetRelation.setSource(source);
synsetRelation.setTarget(target);
synsetRelations.add(synsetRelation);
}
}
@Override
protected ConstraintSet getNextConstraintSet() { return null;}
@Override
protected SemanticPredicate getNextSemanticPredicate() { return null;}
@Override
protected SenseAxis getNextSenseAxis() { return null;}
@Override
protected SubcategorizationFrameSet getNextSubcategorizationFrameSet() {return null;}
@Override
protected SynSemCorrespondence getNextSynSemCorrespondence() { return null;}
@Override
protected void finish() {
commit();
// Save all unsaved word froms from the cache.
int size = wordForms.size();
System.out.println("Finishing WORD FORMS... " + size);
for (Entry<String, List<WordForm>> entry : wordForms.entrySet()) {
if (size % 1000 == 0)
System.out.println("SAVING WORD FORMS: " + size + " LEFT");
LexicalEntry lexEntry = (LexicalEntry)getLmfObjectById(LexicalEntry.class, entry.getKey());
if (lexEntry != null) {
if (lexEntry.getWordForms() == null) {
lexEntry.setWordForms(entry.getValue());
} else {
lexEntry.getWordForms().addAll(entry.getValue());
}
// Save word forms and update lexEntry.
saveList(lexEntry, lexEntry.getWordForms());
}
size--;
}
}
/** Returns unique entry ID for a WiktionaryEntry. */
protected String getEntryId(IWiktionaryEntry entry){
return "e" + entry.getKey();
}
/** Returns unique sense ID for a WiktionarySense. */
protected String getSenseId(IWiktionarySense sense){
return getSenseId(sense.getKey());
}
protected String getSenseId(final String senseKey){
return "s" + senseKey;
}
protected String getSynsetId(final String conceptId) {
return "c" + conceptId;
}
private static String convert(final String text) {
return StringUtils.replaceNonUtf8(
StringUtils.replaceHtmlEntities(text));
}
private static String convert(final String text, int maxLength) {
if (text == null)
return null;
else
return StringUtils.replaceNonUtf8(
StringUtils.replaceHtmlEntities(text), maxLength);
}
protected String convertEtymology(final IWikiString etymology) {
if (etymology == null)
return null;
try {
String result = TemplateParser.parse(etymology.getText(), new EtymologyTemplateHandler());
return WikiString.makePlainText(result);
} catch (Exception e) {
return WikiString.makePlainText(etymology.getText());
}
}
}
|
UTF-8
|
Java
| 52,716 |
java
|
OntoWiktionaryTransformer.java
|
Java
|
[] | null |
[] |
/*******************************************************************************
* Copyright 2016
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.lmf.transform.ontowiktionary;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import de.tudarmstadt.ukp.jwktl.api.IPronunciation;
import de.tudarmstadt.ukp.jwktl.api.IPronunciation.PronunciationType;
import de.tudarmstadt.ukp.jwktl.api.IQuotation;
import de.tudarmstadt.ukp.jwktl.api.IWikiString;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEdition;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEntry;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryRelation;
import de.tudarmstadt.ukp.jwktl.api.IWiktionarySense;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryTranslation;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryWordForm;
import de.tudarmstadt.ukp.jwktl.api.PartOfSpeech;
import de.tudarmstadt.ukp.jwktl.api.entry.WikiString;
import de.tudarmstadt.ukp.jwktl.api.util.ILanguage;
import de.tudarmstadt.ukp.jwktl.api.util.IWiktionaryIterator;
import de.tudarmstadt.ukp.jwktl.api.util.TemplateParser;
import de.tudarmstadt.ukp.jwktl.api.util.TemplateParser.EtymologyTemplateHandler;
import de.tudarmstadt.ukp.lmf.model.core.Definition;
import de.tudarmstadt.ukp.lmf.model.core.GlobalInformation;
import de.tudarmstadt.ukp.lmf.model.core.LexicalEntry;
import de.tudarmstadt.ukp.lmf.model.core.LexicalResource;
import de.tudarmstadt.ukp.lmf.model.core.Lexicon;
import de.tudarmstadt.ukp.lmf.model.core.Sense;
import de.tudarmstadt.ukp.lmf.model.core.Statement;
import de.tudarmstadt.ukp.lmf.model.core.TextRepresentation;
import de.tudarmstadt.ukp.lmf.model.enums.EAuxiliary;
import de.tudarmstadt.ukp.lmf.model.enums.ECase;
import de.tudarmstadt.ukp.lmf.model.enums.EContextType;
import de.tudarmstadt.ukp.lmf.model.enums.EDefinitionType;
import de.tudarmstadt.ukp.lmf.model.enums.EDegree;
import de.tudarmstadt.ukp.lmf.model.enums.EExampleType;
import de.tudarmstadt.ukp.lmf.model.enums.EGrammaticalGender;
import de.tudarmstadt.ukp.lmf.model.enums.EGrammaticalNumber;
import de.tudarmstadt.ukp.lmf.model.enums.ELabelNameSemantics;
import de.tudarmstadt.ukp.lmf.model.enums.ELabelTypeSemantics;
import de.tudarmstadt.ukp.lmf.model.enums.EPartOfSpeech;
import de.tudarmstadt.ukp.lmf.model.enums.EPerson;
import de.tudarmstadt.ukp.lmf.model.enums.ERelTypeMorphology;
import de.tudarmstadt.ukp.lmf.model.enums.ERelTypeSemantics;
import de.tudarmstadt.ukp.lmf.model.enums.EStatementType;
import de.tudarmstadt.ukp.lmf.model.enums.ESyntacticProperty;
import de.tudarmstadt.ukp.lmf.model.enums.ETense;
import de.tudarmstadt.ukp.lmf.model.enums.EVerbFormMood;
import de.tudarmstadt.ukp.lmf.model.meta.SemanticLabel;
import de.tudarmstadt.ukp.lmf.model.miscellaneous.ConstraintSet;
import de.tudarmstadt.ukp.lmf.model.morphology.FormRepresentation;
import de.tudarmstadt.ukp.lmf.model.morphology.Lemma;
import de.tudarmstadt.ukp.lmf.model.morphology.RelatedForm;
import de.tudarmstadt.ukp.lmf.model.morphology.WordForm;
import de.tudarmstadt.ukp.lmf.model.mrd.Context;
import de.tudarmstadt.ukp.lmf.model.mrd.Equivalent;
import de.tudarmstadt.ukp.lmf.model.multilingual.SenseAxis;
import de.tudarmstadt.ukp.lmf.model.semantics.MonolingualExternalRef;
import de.tudarmstadt.ukp.lmf.model.semantics.SemanticPredicate;
import de.tudarmstadt.ukp.lmf.model.semantics.SenseExample;
import de.tudarmstadt.ukp.lmf.model.semantics.SenseRelation;
import de.tudarmstadt.ukp.lmf.model.semantics.SynSemCorrespondence;
import de.tudarmstadt.ukp.lmf.model.semantics.Synset;
import de.tudarmstadt.ukp.lmf.model.semantics.SynsetRelation;
import de.tudarmstadt.ukp.lmf.model.syntax.LexemeProperty;
import de.tudarmstadt.ukp.lmf.model.syntax.SubcategorizationFrame;
import de.tudarmstadt.ukp.lmf.model.syntax.SubcategorizationFrameSet;
import de.tudarmstadt.ukp.lmf.model.syntax.SyntacticBehaviour;
import de.tudarmstadt.ukp.lmf.transform.DBConfig;
import de.tudarmstadt.ukp.lmf.transform.LMFDBTransformer;
import de.tudarmstadt.ukp.lmf.transform.StringUtils;
import de.tudarmstadt.ukp.lmf.transform.ontowiktionary.WiktionaryLabelManager.PragmaticLabel;
/**
* Converts OntoWiktionary into UBY-LMF.
*/
public class OntoWiktionaryTransformer extends LMFDBTransformer {
// The embracing lexicon instance.
protected Lexicon lexicon;
// JWKTL Wiktionary object
protected final IWiktionaryEdition wkt;
// Language of Wiktionary edition that should be transformed
protected final ILanguage wktLang;
// A string representation (YYYY-MM-DD) of the dump date.
protected final String wktDate;
// JWKTL Entry iterator
protected final IWiktionaryIterator<IWiktionaryEntry> entryIterator;
// Current entry number
protected int currentEntryNr = 0;
// Handler for Wiktionary's pragmatic labels.
protected WiktionaryLabelManager labelManager;
// Cache of unsaved word forms defined by Wiktionary word form labels.
protected final Map<String, List<WordForm>> wordForms;
// Cache of unsaved subcategorization frames.
protected final SortedMap<String, SubcategorizationFrame> subcatFrames;
protected OntoWiktionary ontoWiktionary;
protected Iterator<OntoWiktionaryConcept> synsetIter;
protected final String jwktlVersion;
protected final String dtd_version;
static int exampleIdx = 1;
static int subcatFrameIdx = 1;
static int syntacticBehaviourIdx = 1;
/**
* @param dbConfig - Database configuration of LMF database
* @param wkt - JWKTL Wiktionary Object
* @throws FileNotFoundException
*/
public OntoWiktionaryTransformer(final DBConfig dbConfig,
final OntoWiktionary ontoWiktionary,
final IWiktionaryEdition wkt, final ILanguage wktLang,
final String wktDate, final String dtd) throws IOException {
super(dbConfig);
this.ontoWiktionary = ontoWiktionary;
this.wkt = wkt;
this.wktLang = wktLang;
this.wktDate = wktDate;
this.entryIterator = wkt.getAllEntries();
this.wordForms = new TreeMap<String, List<WordForm>>();
this.subcatFrames = new TreeMap<String, SubcategorizationFrame>();
this.labelManager = WiktionaryLMFMap.createLabelManager();
jwktlVersion = /*JWKTL.getVersion() - version clash!*/ "1.0.0";
dtd_version = dtd;
}
@Override
protected String getResourceAlias() {
return "OntoWkt" + wktLang.getISO639_1().toUpperCase();
};
@Override
protected LexicalResource createLexicalResource() {
LexicalResource resource = new LexicalResource();
GlobalInformation glInformation = new GlobalInformation();
glInformation.setLabel("OntoWiktionary " + wktLang.getName()
+ " edition, dump of 2013/02, JWKTL "
+ jwktlVersion);
resource.setGlobalInformation(glInformation);
resource.setName("OntoWiktionary" + wktLang.getISO639_1().toUpperCase());
resource.setDtdVersion(dtd_version);
return resource;
}
@Override
protected Lexicon createNextLexicon() {
if (lexicon != null)
return null;
lexicon = new Lexicon();
String lmfLang = WiktionaryLMFMap.mapLanguage(wktLang);
lexicon.setId(getLmfId(Lexicon.class, "lexiconWkt" + lmfLang));
lexicon.setLanguageIdentifier(lmfLang);
lexicon.setName("OntoWiktionary" + wktLang.getISO639_1().toUpperCase());
return lexicon;
}
@Override
protected LexicalEntry getNextLexicalEntry() {
/*if (!entryIterator.hasNext() || currentEntryNr > 100000) {
return null;
}*/
// If we're finished, convert the semantic relations and free resources.
if (!entryIterator.hasNext()) {
System.out.println("PROCESS SENSE RELATIONS");
convertSemanticRelations();
return null;
}
if (currentEntryNr % 1000 == 0) {
System.out.println("PROCESSED " + currentEntryNr + " ENTRIES");
}
IWiktionaryEntry wktEntry = null;
while (entryIterator.hasNext()){
wktEntry = entryIterator.next();
if (wktLang.equals(wktEntry.getWordLanguage()))
break;
}
// Lexical entry.
LexicalEntry entry = new LexicalEntry();
entry.setId(getLmfId(LexicalEntry.class, getEntryId(wktEntry)));
EPartOfSpeech pos = WiktionaryLMFMap.mapPos(wktEntry);
entry.setPartOfSpeech(pos);
// Lemma
String word = convert(wktEntry.getWord(), 1000);
Lemma lemma = new Lemma();
lemma.setFormRepresentations(createFormRepresentationList(word, wktEntry.getWordLanguage()));
entry.setLemma(lemma);
// Senses.
List<Sense> senses = new ArrayList<Sense>();
for (IWiktionarySense wktSense : wktEntry.getSenses()) {
if (considerSense(wktSense)) {
Sense sense = wktSenseToLMFSense(wktSense, wktEntry, entry);
senses.add(sense);
}
wktSense = null;
}
entry.setSenses(senses);
// Related forms.
List<IWiktionaryRelation> relations = wktEntry.getRelations();
if (relations != null) {
List<RelatedForm> relatedForms = new ArrayList<RelatedForm>();
for (IWiktionaryRelation relation : relations) {
ERelTypeMorphology relType = WiktionaryLMFMap.mapMorphologicalRelation(relation.getRelationType());
if (relType == null)
continue;
RelatedForm form = new RelatedForm();
form.setRelType(relType);
form.setFormRepresentations(createFormRepresentationList(relation.getTarget(), wktEntry.getWordLanguage()));
relatedForms.add(form);
}
entry.setRelatedForms(relatedForms);
}
// Word forms.
convertWordForms(wktEntry, entry);
wktEntry = null;
currentEntryNr++;
return entry;
}
protected Set<String> unknownPronunciationNotes;
protected void convertWordForms(final IWiktionaryEntry wktEntry,
final LexicalEntry entry) {
boolean isNoun = false;
boolean isVerb = false;
boolean isAdjAd = false;
for (PartOfSpeech pos : wktEntry.getPartsOfSpeech())
if (pos == PartOfSpeech.NOUN || pos == PartOfSpeech.PROPER_NOUN
|| pos == PartOfSpeech.FIRST_NAME || pos == PartOfSpeech.LAST_NAME
|| pos == PartOfSpeech.TOPONYM
|| pos == PartOfSpeech.SINGULARE_TANTUM
|| pos == PartOfSpeech.PLURALE_TANTUM
|| pos == PartOfSpeech.PRONOUN
|| pos == PartOfSpeech.PERSONAL_PRONOUN
|| pos == PartOfSpeech.REFLEXIVE_PRONOUN
|| pos == PartOfSpeech.DEMONSTRATIVE_PRONOUN
|| pos == PartOfSpeech.INDEFINITE_PRONOUN
|| pos == PartOfSpeech.POSSESSIVE_PRONOUN
|| pos == PartOfSpeech.RELATIVE_PRONOUN
|| pos == PartOfSpeech.INTERROGATIVE_ADVERB
|| pos == PartOfSpeech.INTERROGATIVE_PRONOUN)
isNoun = true;
else
if (pos == PartOfSpeech.VERB || pos == PartOfSpeech.AUXILIARY_VERB)
isVerb = true;
else
if (pos == PartOfSpeech.ADJECTIVE || pos == PartOfSpeech.ADVERB)
isAdjAd = true;
List<WordForm> wordForms = new ArrayList<WordForm>();
// Add lemma form (for inflectable word forms).
WordForm lemmaForm = new WordForm();
lemmaForm.setFormRepresentations(createFormRepresentationList(wktEntry.getWord(), wktEntry.getWordLanguage()));
if (isNoun) {
lemmaForm.setCase(ECase.nominative);
lemmaForm.setGrammaticalNumber(EGrammaticalNumber.singular);
} else
if (isVerb) {
lemmaForm.setVerbFormMood(EVerbFormMood.infinitive);
} else
if (isAdjAd) {
lemmaForm.setDegree(EDegree.positive);
} else {
lemmaForm = null;
}
if (lemmaForm != null)
wordForms.add(lemmaForm);
// Add inflected word forms.
List<IWiktionaryWordForm> wktWordForms = wktEntry.getWordForms();
if (wktWordForms != null) {
for (IWiktionaryWordForm wktWordForm : wktWordForms) {
String writtenForm = convert(wktWordForm.getWordForm(), 255);
if (writtenForm == null || writtenForm.isEmpty())
continue;
if (writtenForm.contains("[")) {
// System.err.println("Skipping word form: " + writtenForm);
continue;
}
WordForm newWordForm = new WordForm();
newWordForm.setCase(WiktionaryLMFMap.mapCase(wktWordForm));
newWordForm.setDegree(WiktionaryLMFMap.mapDegree(wktWordForm));
newWordForm.setPerson(WiktionaryLMFMap.mapPerson(wktWordForm));
//newWordForm.setGrammaticalGender(WiktionaryLMFMap.mapGender(wktWordForm.get));
newWordForm.setGrammaticalNumber(WiktionaryLMFMap.mapGrammaticalNumber(wktWordForm));
newWordForm.setVerbFormMood(WiktionaryLMFMap.mapVerbFormMood(wktWordForm));
newWordForm.setTense(WiktionaryLMFMap.mapTense(wktWordForm));
if (newWordForm.getVerbFormMood() == null && isVerb)
newWordForm.setVerbFormMood(EVerbFormMood.indicative);
if (newWordForm.getVerbFormMood() == EVerbFormMood.subjunctive)
newWordForm.setTense(null);
// Check if a similar word form exists.
WordForm wordForm = null;
for (WordForm wf : wordForms) {
if (newWordForm.getCase() != null && wf.getCase() != null
&& newWordForm.getCase() != wf.getCase())
continue;
if (newWordForm.getDegree() != null && wf.getDegree() != null
&& newWordForm.getDegree() != wf.getDegree())
continue;
if (newWordForm.getPerson() != null && wf.getPerson() != null
&& newWordForm.getPerson() != wf.getPerson())
continue;
if (newWordForm.getGrammaticalGender() != null && wf.getGrammaticalGender() != null
&& newWordForm.getGrammaticalGender() != wf.getGrammaticalGender())
continue;
if (newWordForm.getGrammaticalNumber() != null && wf.getGrammaticalNumber() != null
&& newWordForm.getGrammaticalNumber() != wf.getGrammaticalNumber())
continue;
if (newWordForm.getVerbFormMood() != null && wf.getVerbFormMood() != null
&& newWordForm.getVerbFormMood() != wf.getVerbFormMood())
continue;
if (newWordForm.getTense() != null && wf.getTense() != null
&& newWordForm.getTense() != wf.getTense())
continue;
String key1 = newWordForm.getCase() + " " + newWordForm.getDegree()
+ " " + newWordForm.getPerson() + " " + newWordForm.getGrammaticalNumber()
+ " " + newWordForm.getVerbFormMood() + " " + newWordForm.getTense();
String key2 = wf.getCase() + " " + wf.getDegree()
+ " " + wf.getPerson() + " " + wf.getGrammaticalNumber()
+ " " + wf.getVerbFormMood() + " " + wf.getTense();
if (key1.equals(key2)) {
wordForm = wf;
break;
}
// else
// System.err.println(wktEntry.getWord() + " " + key1 + "\n"
// + wktEntry.getWord() + " " + key2 + "\n");
}
if (wordForm == null) {
wordForm = newWordForm;
wordForm.setFormRepresentations(new ArrayList<FormRepresentation>());
wordForms.add(wordForm);
}
// If this is a noun, remove the determiner and identify the gender.
if (isNoun) {
int idx = writtenForm.indexOf(' ');
if (idx >= 0) {
EGrammaticalGender gender = null;
String determiner = writtenForm.substring(0, idx);
if ("der".equals(determiner) || "(der)".equals(determiner))
gender = EGrammaticalGender.masculine;
else
if ("die".equals(determiner) || "(die)".equals(determiner))
gender = EGrammaticalGender.feminine;
else
if ("das".equals(determiner) || "(das)".equals(determiner))
gender = EGrammaticalGender.neuter;
else
if (!"des".equals(determiner) && !"(des)".equals(determiner)
&& !"dem".equals(determiner) && !"(dem)".equals(determiner)
&& !"den".equals(determiner) && !"(den)".equals(determiner))
idx = -1;
if (idx >= 0) {
writtenForm = writtenForm.substring(idx + 1);
if (wordForm == lemmaForm && gender != null)
wordForm.setGrammaticalGender(gender);
}
}
}
// Add a new form representation if the written form does not yet exist.
boolean found = false;
for (FormRepresentation fp : wordForm.getFormRepresentations())
if (fp.getWrittenForm().equals(writtenForm)) {
found = true;
break;
}
if (!found) {
FormRepresentation fp = new FormRepresentation();
fp.setWrittenForm(writtenForm);
fp.setLanguageIdentifier(lexicon.getLanguageIdentifier());
wordForm.getFormRepresentations().add(fp);
}
}
}
// Add phonetic forms.
List<IPronunciation> pronunciations = wktEntry.getPronunciations();
if (pronunciations != null) {
for (IPronunciation pronunciation : pronunciations) {
// Only save IPA pronunciations.
if (pronunciation.getType() != PronunciationType.IPA)
continue;
// Don't save empty pronunciations.
String phoneticForm = pronunciation.getText();
if (phoneticForm == null || phoneticForm.isEmpty()
|| "...".equals(phoneticForm) || "…".equals(phoneticForm))
continue;
// Don't save pronunciations containing a dash or a wiki link.
if (phoneticForm.startsWith("[")) {
phoneticForm = phoneticForm.substring(1);
int idx = phoneticForm.indexOf(']');
if (idx >= 0)
phoneticForm = phoneticForm.substring(0, idx);
}
if (phoneticForm.startsWith("/")) {
phoneticForm = phoneticForm.substring(1);
int idx = phoneticForm.indexOf('/');
if (idx >= 0)
phoneticForm = phoneticForm.substring(0, idx);
}
if (phoneticForm.contains("–") || phoneticForm.contains("|")
|| phoneticForm.contains("[") || phoneticForm.contains("]")) {
// System.err.println("Skipping phonetic form: " + phoneticForm);
continue;
}
WordForm newWordForm = new WordForm();
if (lemmaForm != null) {
newWordForm.setCase(lemmaForm.getCase());
newWordForm.setDegree(lemmaForm.getDegree());
newWordForm.setPerson(lemmaForm.getPerson());
newWordForm.setGrammaticalGender(lemmaForm.getGrammaticalGender());
newWordForm.setGrammaticalNumber(lemmaForm.getGrammaticalNumber());
newWordForm.setVerbFormMood(lemmaForm.getVerbFormMood());
newWordForm.setTense(lemmaForm.getTense());
}
String note = pronunciation.getNote();
String geographicalVariant = null;
if (note != null && !note.isEmpty()) {
if (note.contains("Sg."))
newWordForm.setGrammaticalNumber(EGrammaticalNumber.singular);
else
if (note.contains("Pl."))
newWordForm.setGrammaticalNumber(EGrammaticalNumber.plural);
else
if ("Gen.".equals(note))
newWordForm.setCase(ECase.genitive);
else
if ("Dat.".equals(note))
newWordForm.setCase(ECase.dative);
else
if ("Akk.".equals(note))
newWordForm.setCase(ECase.accusative);
else
if ("Prät.".equals(note)) {
newWordForm.setPerson(EPerson.first);
newWordForm.setGrammaticalNumber(EGrammaticalNumber.singular);
newWordForm.setTense(ETense.past);
newWordForm.setVerbFormMood(EVerbFormMood.indicative);
}
else
if ("Komp.".equals(note))
newWordForm.setDegree(EDegree.comparative);
else
if ("Sup.".equals(note))
newWordForm.setDegree(EDegree.superlative);
else
if ("Part.".equals(note)) // Partizip II
newWordForm.setVerbFormMood(EVerbFormMood.participle);
//newWordForm.setTense(ETense.past);
else
if ("UK".equals(note) || "RP".equals(note)
|| note.startsWith("RP ") || "Received Pronunciation".equals(note)
|| note.contains("British") || note.contains("England")
|| note.contains("English") || note.contains("Scotland")
|| note.contains("Scots") || "GB".equals(note)) {
geographicalVariant = "UK";
} else
if ("US".equals(note) || note.startsWith("US ") || "U.S.".equals(note)
|| note.endsWith(" US") || note.toUpperCase().contains("GENAM")
|| note.equals("GAm")
|| note.contains("Southern US") || note.contains("Northern US")
|| note.contains("New York") || "NYC".equals(note) || "NY".equals(note)
|| note.contains("St. Louis") || "STL".equals(note))
geographicalVariant = "US";
else
if ("CA".equals(note) || "Canada".equals(note)
|| "Canadian".equals(note) || "CanE".equals(note)
|| "CaE".equals(note))
geographicalVariant = "CA";
else
if ("AU".equals(note) || "AUSE".equals(note.toUpperCase())
|| "AUSEN".equals(note.toUpperCase())
|| "Australia".equals(note))
geographicalVariant = "AU";
else
if ("NZ".equals(note) || "New Zealand".equals(note))
geographicalVariant = "NZ";
else
if ("IE".equals(note) || "Ireland".equals(note) || "Irish".equals(note))
geographicalVariant = "IE";
else
if ("Deutschland".equals(note))
geographicalVariant = "DE";
else
if ("Österreich".equals(note) || note.contains("österr."))
geographicalVariant = "AT";
else
if ("Schweiz".equals(note))
geographicalVariant = "CH";
else
if (note.contains("South Africa") || "S Africa".equals(note)
|| "SAE".equals(note))
geographicalVariant = "RSA";
else
if (note.contains("North America") || "Puerto Rican".equals(note)
|| note.contains("American"))
geographicalVariant = note;
else
if (!"letter name".equals(note) && !"phoneme".equals(note)) {
// Save a new empty word form.
newWordForm.setCase(null);
newWordForm.setDegree(null);
newWordForm.setPerson(null);
newWordForm.setGrammaticalGender(null);
newWordForm.setGrammaticalNumber(null);
newWordForm.setVerbFormMood(null);
newWordForm.setTense(null);
/*if (unknownPronunciationNotes == null)
unknownPronunciationNotes = new TreeSet<String>();
if (unknownPronunciationNotes.add(note))
System.err.println("PRONUNCIATION: >" + note + "<");*/
}
}
// Check if a similar word form exists.
WordForm wordForm = null;
for (WordForm wf : wordForms) {
if (newWordForm.getCase() != null && wf.getCase() != null
&& newWordForm.getCase() != wf.getCase())
continue;
if (newWordForm.getDegree() != null && wf.getDegree() != null
&& newWordForm.getDegree() != wf.getDegree())
continue;
if (newWordForm.getPerson() != null && wf.getPerson() != null
&& newWordForm.getPerson() != wf.getPerson())
continue;
if (newWordForm.getGrammaticalGender() != null && wf.getGrammaticalGender() != null
&& newWordForm.getGrammaticalGender() != wf.getGrammaticalGender())
continue;
if (newWordForm.getGrammaticalNumber() != null && wf.getGrammaticalNumber() != null
&& newWordForm.getGrammaticalNumber() != wf.getGrammaticalNumber())
continue;
if (newWordForm.getVerbFormMood() != null && wf.getVerbFormMood() != null
&& newWordForm.getVerbFormMood() != wf.getVerbFormMood())
continue;
if (newWordForm.getTense() != null && wf.getTense() != null
&& newWordForm.getTense() != wf.getTense())
continue;
String key1 = newWordForm.getCase() + " " + newWordForm.getDegree()
+ " " + newWordForm.getPerson() + " " + newWordForm.getGrammaticalNumber()
+ " " + newWordForm.getVerbFormMood() + " " + newWordForm.getTense();
String key2 = wf.getCase() + " " + wf.getDegree()
+ " " + wf.getPerson() + " " + wf.getGrammaticalNumber()
+ " " + wf.getVerbFormMood() + " " + wf.getTense();
if (key1.equals(key2)) {
wordForm = wf;
break;
} /*else
if (newWordForm.getCase() != null
|| newWordForm.getDegree() != null
|| newWordForm.getGrammaticalGender() != null
|| newWordForm.getGrammaticalNumber() != null
|| newWordForm.getPerson() != null
|| newWordForm.getTense() != null
|| newWordForm.getVerbFormMood() != null)
System.err.println("* " + wktEntry.getWord() + " " + key1 + "\n"
+ "* "+ wktEntry.getWord() + " " + key2 + "\n");*/
}
if (wordForm == null) {
wordForm = newWordForm;
wordForm.setFormRepresentations(new ArrayList<FormRepresentation>());
wordForms.add(wordForm);
}
// Add the phonetic form if there's only one written form.
String writtenForm = null;
List<FormRepresentation> fps = wordForm.getFormRepresentations();
for (FormRepresentation fp : fps)
if (writtenForm == null)
writtenForm = fp.getWrittenForm();
else
if (fp.getWrittenForm() != null && !fp.getWrittenForm().equals(writtenForm)) {
writtenForm = null;
break;
}
if (fps.size() == 1 && fps.get(0).getPhoneticForm() == null) {
FormRepresentation fp = wordForm.getFormRepresentations().get(0);
fp.setPhoneticForm(phoneticForm);
fp.setGeographicalVariant(geographicalVariant);
} else {
FormRepresentation fp = new FormRepresentation();
fp.setWrittenForm(writtenForm);
fp.setPhoneticForm(phoneticForm);
fp.setGeographicalVariant(geographicalVariant);
fp.setLanguageIdentifier(lexicon.getLanguageIdentifier());
fps.add(fp);
}
}
}
if (!wordForms.isEmpty())
entry.setWordForms(wordForms);
}
protected void convertSemanticRelations() {
int senseCount = 0;
for (IWiktionaryEntry wktEntry : wkt.getAllEntries()) {
if (!wktLang.equals(wktEntry.getWordLanguage()))
continue;
for (IWiktionarySense wktSense : wktEntry.getSenses()) {
if (!considerSense(wktSense))
continue;
String sourceId = getLmfId(Sense.class, getSenseId(wktSense.getKey()));
Sense source = (Sense) getLmfObjectById(Sense.class, sourceId);
if (source != null)
convertSemanticRelations(source, wktSense, wktEntry);
source = null;
wktSense = null;
if (++senseCount % 500 == 0) {
System.out.println("SAVING RELATIONS / PROCESSED " + senseCount + " SENSES");
tx.commit();
session.close();
session = sessionFactory.openSession();
tx = session.beginTransaction();
}
}
wktEntry = null;
}
ontoWiktionary.freeSemanticRelations();
}
protected void convertSemanticRelations(final Sense source,
final IWiktionarySense wktSense,
final IWiktionaryEntry wktEntry) {
// Sense relations (SenseRelation class).
List<OntoWiktionarySemanticRelation> owktRelations;
try {
owktRelations = ontoWiktionary.getSemanticRelations(wktSense.getKey());
} catch (IOException e) {
throw new RuntimeException(e);
}
List<SenseRelation> senseRelations = new ArrayList<SenseRelation>();
if (wktSense.getRelations() != null) {
for (IWiktionaryRelation wktRelation : wktSense.getRelations()) {
if (wktRelation.getRelationType() == null || wktRelation.getTarget().isEmpty()) {
continue;
}
SenseRelation senseRelation = new SenseRelation();
senseRelation.setRelType(WiktionaryLMFMap.mapRelationType(wktRelation.getRelationType()));
senseRelation.setRelName(WiktionaryLMFMap.mapRelationName(wktRelation.getRelationType()));
if (senseRelation.getRelType() == null) {
continue;
}
// Find a suitable relation in OntoWiktionary.
if (owktRelations != null) {
Iterator<OntoWiktionarySemanticRelation> owktRelationIter = owktRelations.iterator();
while (owktRelationIter.hasNext()) {
OntoWiktionarySemanticRelation owktRelation = owktRelationIter.next();
if (!wktRelation.getRelationType().equals(owktRelation.getRelationType())
|| !wktRelation.getTarget().equals(owktRelation.getTargetWordForm()))
continue;
owktRelationIter.remove();
String targetId = getLmfId(Sense.class, getSenseId(owktRelation.getTargetSenseId()));
if (!"???".equals(targetId)) {
Sense target = (Sense) getLmfObjectById(Sense.class, targetId);
if (target != null)
senseRelation.setTarget(target);
// else
// System.err.println("SenseRelation.Target not found: " + owktRelation.getTargetSenseId());
target = null;
}
break;
}
}
// Save target word as targetFormRepresentation.
FormRepresentation targetFormRepresentation = new FormRepresentation();
targetFormRepresentation.setWrittenForm(convert(wktRelation.getTarget(), 255));
targetFormRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(wktEntry.getWordLanguage()));
senseRelation.setFormRepresentation(targetFormRepresentation);
senseRelations.add(senseRelation);
}
}
// Save inferred relations.
if (owktRelations != null) {
for (OntoWiktionarySemanticRelation owktRelation : owktRelations) {
SenseRelation senseRelation = new SenseRelation();
senseRelation.setRelType(WiktionaryLMFMap.mapRelationType(owktRelation.getRelationType()));
senseRelation.setRelName(WiktionaryLMFMap.mapRelationName(owktRelation.getRelationType()) + "-AUTO");
if (senseRelation.getRelType() == null)
continue;
String targetId = getLmfId(Sense.class, getSenseId(owktRelation.getTargetSenseId()));
if (!"???".equals(targetId)) {
Sense target = (Sense) getLmfObjectById(Sense.class, targetId);
if (target != null)
senseRelation.setTarget(target);
// else
// System.err.println("SenseRelation.Target not found: " + owktRelation.getTargetSenseId());
target = null;
}
// Save target word as targetFormRepresentation.
FormRepresentation targetFormRepresentation = new FormRepresentation();
targetFormRepresentation.setWrittenForm(convert(owktRelation.getTargetWordForm(), 255));
targetFormRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(wktEntry.getWordLanguage()));
senseRelation.setFormRepresentation(targetFormRepresentation);
senseRelations.add(senseRelation);
}
}
source.setSenseRelations(senseRelations);
saveList(source, senseRelations);
}
/** Returns true if this sense should be used for the UBY database. */
protected boolean considerSense(final IWiktionarySense wktSense) {
return wktSense.getGloss() != null;
}
/** Converts Wiktionary Sense to LMF Sense. */
protected Sense wktSenseToLMFSense(IWiktionarySense wktSense, IWiktionaryEntry wktEntry, LexicalEntry entry){
// Sense and identifier.
Sense sense = new Sense();
sense.setId(getLmfId(Sense.class, getSenseId(wktSense)));
sense.setIndex(wktSense.getIndex());
// Monolingual external reference.
MonolingualExternalRef monolingualExternalRef = new MonolingualExternalRef();
monolingualExternalRef.setExternalSystem("Wiktionary_"
+ jwktlVersion + "_" + wktDate + "_"
+ wktLang.getISO639_2T() + "_sense");
monolingualExternalRef.setExternalReference(wktSense.getKey());
List<MonolingualExternalRef> monolingualExternalRefs = new LinkedList<MonolingualExternalRef>();
monolingualExternalRefs.add(monolingualExternalRef);
sense.setMonolingualExternalRefs(monolingualExternalRefs);
// Sense Definition (Definition class; type intensionalDefinition).
List<Definition> definitions = new ArrayList<Definition>();
Definition definition = new Definition();
definition.setDefinitionType(EDefinitionType.intensionalDefinition);
definition.setTextRepresentations(createTextRepresentationList(
wktSense.getGloss().getPlainText(), wktEntry.getPage().getEntryLanguage()
));
definitions.add(definition);
sense.setDefinitions(definitions);
// Semantic Labels.
List<SemanticLabel> semanticLabels = createSemanticLabels(entry, sense, wktSense);
if (semanticLabels != null && semanticLabels.size() > 0)
sense.setSemanticLabels(semanticLabels);
// Etymology (Statement class; type etymology).
IWikiString etymology = null;
if (wktEntry.getWordEtymology() != null)
etymology = wktEntry.getWordEtymology();
String etymologyText = convertEtymology(etymology);
if (etymologyText != null && !etymologyText.isEmpty()) {
List<Statement> statements = new LinkedList<Statement>();
Statement statement = new Statement();
statement.setStatementType(EStatementType.etymology);
statement.setTextRepresentations(createTextRepresentationList(
convertEtymology(etymology), wktEntry.getPage().getEntryLanguage()));
statements.add(statement);
definition.setStatements(statements);
}
// Sense examples (SenseExample class; type senseInstance).
List<SenseExample> examples = new ArrayList<SenseExample>();
if (wktSense.getExamples() != null) {
for (IWikiString example : wktSense.getExamples()) {
SenseExample senseExample = new SenseExample();
senseExample.setId(getResourceAlias() + "_SenseExample_" + (exampleIdx++));
senseExample.setExampleType(EExampleType.senseInstance);
senseExample.setTextRepresentations(createTextRepresentationList(
example.getPlainText(), wktEntry.getWordLanguage()
));
examples.add(senseExample);
}
}
sense.setSenseExamples(examples);
// Quotations (Context class; type citation).
List<Context> contexts = new ArrayList<Context>();
if (wktSense.getQuotations() != null) {
for (IQuotation quotation : wktSense.getQuotations()) {
Context context = new Context();
context.setContextType(EContextType.citation);
StringBuilder quotationText = new StringBuilder();
for (IWikiString line : quotation.getLines()) {
quotationText.append(quotationText.length() == 0 ? "" : " ")
.append(line.getPlainText());
}
context.setTextRepresentations(createTextRepresentationList(
quotationText.toString(), wktEntry.getWordLanguage()
));
if (quotation.getSource() != null) {
String source = quotation.getSource().getPlainText();
if (source.length() > 255)
source = source.substring(0, 255);
context.setSource(source);
}
contexts.add(context);
}
}
sense.setContexts(contexts);
// Sense relations (SenseRelation class)
// -- skip (will be done in a separate step!
// Translations (Equivalent class).
if (wktSense.getTranslations() != null) {
List<Equivalent> equivalents = new ArrayList<Equivalent>();
for (IWiktionaryTranslation trans : wktSense.getTranslations()) {
String targetForm = convert(trans.getTranslation(), 255);
if (targetForm == null || targetForm.isEmpty()) {
continue; // Do not save empty translations.
}
String language = WiktionaryLMFMap.mapLanguage(trans.getLanguage());
if (language == null) {
continue; // Do not save translations to unknown languages.
}
Equivalent equivalent = new Equivalent();
equivalent.setWrittenForm(targetForm);
equivalent.setLanguageIdentifier(language);
String transliteration = trans.getTransliteration();
if (transliteration != null && !transliteration.isEmpty()) {
transliteration = convert(transliteration, 255);
equivalent.setTransliteration(transliteration);
}
String additionalInformation = trans.getAdditionalInformation();
if (additionalInformation != null && !additionalInformation.isEmpty()) {
additionalInformation = additionalInformation.replace("{{m}}", "masculine");
additionalInformation = additionalInformation.replace("{{f}}", "feminine");
additionalInformation = additionalInformation.replace("{{n}}", "neuter");
additionalInformation = convert(additionalInformation, 255);
equivalent.setUsage(additionalInformation);
}
equivalents.add(equivalent);
}
sense.setEquivalents(equivalents);
}
return sense;
}
protected List<SemanticLabel> createSemanticLabels(
final LexicalEntry entry, final Sense sense,
final IWiktionarySense wktSense) {
List<SemanticLabel> result = new ArrayList<SemanticLabel>();
// Create semantic labels from part of speech tags.
for (PartOfSpeech p : wktSense.getEntry().getPartsOfSpeech()) {
if (p == null)
continue;
ELabelTypeSemantics semanticLabelType;
String semanticLabelName;
switch (p) {
case TOPONYM:
semanticLabelType = ELabelTypeSemantics.semanticNounClass;
semanticLabelName = ELabelNameSemantics.SEMANTIC_NOUN_CLASS_TOPONYM;
break;
case SINGULARE_TANTUM:
semanticLabelType = ELabelTypeSemantics.semanticNounClass;
semanticLabelName = ELabelNameSemantics.SEMANTIC_NOUN_CLASS_ONLY_SINGULAR;
break;
case PLURALE_TANTUM:
semanticLabelType = ELabelTypeSemantics.semanticNounClass;
semanticLabelName = ELabelNameSemantics.SEMANTIC_NOUN_CLASS_ONLY_PLURAL;
break;
case SALUTATION:
semanticLabelType = ELabelTypeSemantics.interjectionClass;
semanticLabelName = ELabelNameSemantics.INTERJECTION_SALUTATION;
break;
case ONOMATOPOEIA:
semanticLabelType = ELabelTypeSemantics.interjectionClass;
semanticLabelName = ELabelNameSemantics.INTERJECTION_ONOMATOPOEIA;
break;
case IDIOM:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_IDIOM;
break;
case COLLOCATION:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_COLLOCATION;
break;
case PROVERB:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_PROVERB;
break;
case MNEMONIC:
semanticLabelType = ELabelTypeSemantics.phrasemeClass;
semanticLabelName = ELabelNameSemantics.PHRASEME_CLASS_MNEMONIC;
break;
case MODAL_PARTICLE:
semanticLabelType = ELabelTypeSemantics.discourseFunction;
semanticLabelName = ELabelNameSemantics.DISCOURSE_FUNCTION_MODAL_PARTICLE;
break;
case FOCUS_PARTICLE:
semanticLabelType = ELabelTypeSemantics.discourseFunction;
semanticLabelName = ELabelNameSemantics.DISCOURSE_FUNCTION_FOCUS_PARTICLE;
break;
case INTENSIFYING_PARTICLE:
semanticLabelType = ELabelTypeSemantics.discourseFunction;
semanticLabelName = ELabelNameSemantics.DISCOURSE_FUNCTION_INTENSIFYING_PARTICLE;
break;
default:
continue;
}
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setType(semanticLabelType);
semanticLabel.setLabel(semanticLabelName);
result.add(semanticLabel);
}
// Process labels encoded in the sense definition.
IWikiString senseDefinition = wktSense.getGloss();
List<PragmaticLabel> labels = labelManager.parseLabels(
senseDefinition.getText(), wktSense.getEntry().getWord());
if (labels != null) {
List<String> subcatLabels = new LinkedList<String>();
EAuxiliary auxiliary = null;
ESyntacticProperty syntacticProperty = null;
for (PragmaticLabel label : labels) {
String labelGroup = label.getLabelGroup();
if (labelGroup == null || labelGroup.length() == 0)
continue;
String[] labelInfo = labelManager.getWordFormLabel(label);
if (labelInfo != null) {
// WordForm.
/* if (!labelInfo[0].equals("WordForm"))
continue;
String targetWord = labelManager.extractTargetWordForm(senseDefinition.getText());
IWiktionaryEntry wktEntry = wktSense.getEntry();
// System.err.println("WORD FORM: " + targetWord + " -> " + wktEntry.getWord());
WordForm wordForm = new WordForm();
if (!labelInfo[1].isEmpty())
wordForm.setCase(ECase.valueOf(labelInfo[1]));
if (!labelInfo[2].isEmpty())
wordForm.setGrammaticalNumber(EGrammaticalNumber.valueOf(labelInfo[2]));
if (!labelInfo[3].isEmpty())
wordForm.setVerbFormMood(EVerbFormMood.valueOf(labelInfo[3]));
if (!labelInfo[4].isEmpty())
wordForm.setTense(ETense.valueOf(labelInfo[4]));
if (!labelInfo[5].isEmpty())
wordForm.setGrammaticalGender(EGrammaticalGender.valueOf(labelInfo[5]));
if (!labelInfo[6].isEmpty())
wordForm.setDegree(EDegree.valueOf(labelInfo[6]));
wordForm.setFormRepresentations(createFormRepresentationList(
wktEntry.getWord(), wktEntry.getWordLanguage()));
for (IWiktionaryEntry targetEntry : wkt.getEntriesForWord(targetWord)) {
// Ignore entries of a different language.
if (targetEntry.getWordLanguage() == null
|| !targetEntry.getWordLanguage().equals(wktEntry.getWordLanguage()))
continue;
// Ignore entries of a different part of speech.
if (targetEntry.getPartOfSpeech() == null
|| !targetEntry.getPartOfSpeech().equals(wktEntry.getPartOfSpeech()))
continue;
String entryId = getLmfId(LexicalEntry.class, getEntryId(targetEntry)); // this only works if the entire resource is converted!
LexicalEntry lexEntry = (LexicalEntry) getLmfObjectById(LexicalEntry.class, entryId);
if (lexEntry != null) {
// If the entry already exists then save directly to it
List<WordForm> wordFormList = lexEntry.getWordForms();
if (wordFormList == null) {
wordFormList = new ArrayList<WordForm>();
lexEntry.setWordForms(wordFormList);
}
wordFormList.add(wordForm);
saveList(lexEntry, lexEntry.getWordForms());
} else {
// If the lexical entry does not yet exist, then
// save the wordForms temporarily.
List<WordForm> wordFormList = wordForms.get(entryId);
if (wordFormList == null) {
wordFormList = new ArrayList<WordForm>();
wordForms.put(entryId, wordFormList);
}
wordFormList.add(wordForm);
}
}*/
} else
if ("syntax:gram:auxiliary".equals(labelGroup)) {
// LexemeProperty:auxiliary.
if ("habenSein".equals(label.getStandardizedLabel()))
continue; //TODO: Add enum value!
auxiliary = EAuxiliary.valueOf(label.getStandardizedLabel());
} else
if ("syntax:gram:synprop".equals(labelGroup)) {
// LexemeProperty:syntacticProperty.
syntacticProperty = ESyntacticProperty.valueOf(label.getStandardizedLabel());
} else
if ("syntax:gram:subcat".equals(labelGroup)) {
// SubcategorizationFrame.
subcatLabels.add(label.getStandardizedLabel());
} else
if ("syntax:gram:nounClass".equals(labelGroup)) {
// SemanticLabel:semanticNounClass.
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setLabel(StringUtils.replaceNonUtf8(label.getStandardizedLabel()));
semanticLabel.setType(ELabelTypeSemantics.semanticNounClass);
result.add(semanticLabel);
} else
if ("syntax:gram:usage".equals(labelGroup)) {
// SemanticLabel:usage.
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setLabel(StringUtils.replaceNonUtf8(label.getStandardizedLabel()));
semanticLabel.setType(ELabelTypeSemantics.usage);
result.add(semanticLabel);
} else {
// Semantic labels.
SemanticLabel semanticLabel = new SemanticLabel();
semanticLabel.setLabel(StringUtils.replaceNonUtf8(label.getLabel()));
if (labelGroup.startsWith("dom"))
semanticLabel.setType(ELabelTypeSemantics.domain);
else
if (labelGroup.startsWith("reg") || labelGroup.startsWith("dia"))
semanticLabel.setType(ELabelTypeSemantics.regionOfUsage);
else
if (labelGroup.startsWith("phas") || labelGroup.startsWith("strat") || labelGroup.startsWith("eval"))
semanticLabel.setType(ELabelTypeSemantics.register);
else
if (labelGroup.startsWith("temp"))
semanticLabel.setType(ELabelTypeSemantics.timePeriodOfUsage);
else
if (labelGroup.startsWith("freq") || labelGroup.startsWith("norm"))
semanticLabel.setType(ELabelTypeSemantics.usage);
else
continue;
result.add(semanticLabel); //TODO: standardize
}
// TODO: Additional labels: etym request syntax:form syntax:pos syntax:gram
}
// Create a subcategorization frame if no syntactic label exists.
String lpKey = (auxiliary != null ? auxiliary.ordinal() : "")
+ "_" + (syntacticProperty != null ? syntacticProperty.ordinal() : "");
if (subcatLabels.isEmpty() && !"_".equals(lpKey))
subcatLabels.add("");
for (String subcatLabel : subcatLabels) {
// Create subcategorization frame.
String scfKey = subcatLabel + ":" + lpKey;
SubcategorizationFrame subcatFrame = subcatFrames.get(scfKey);
if (subcatFrame == null) {
LexemeProperty lexemeProperty = new LexemeProperty();
lexemeProperty.setAuxiliary(auxiliary);
lexemeProperty.setSyntacticProperty(syntacticProperty);
subcatFrame = new SubcategorizationFrame();
subcatFrame.setId(getResourceAlias() + "_SubcatFrame_" + (subcatFrameIdx++));
subcatFrame.setSubcatLabel(subcatLabel);
subcatFrame.setLexemeProperty(lexemeProperty);
subcatFrames.put(scfKey, subcatFrame);
}
// Create syntactic behavior.
SyntacticBehaviour sb = new SyntacticBehaviour();
sb.setSubcategorizationFrame(subcatFrame);
sb.setId(getResourceAlias() + "_SyntacticBehaviour_" + (syntacticBehaviourIdx++));
sb.setSense(sense);
if (entry.getSyntacticBehaviours() == null)
entry.setSyntacticBehaviours(new LinkedList<SyntacticBehaviour>());
entry.getSyntacticBehaviours().add(sb);
}
}
return result;
}
protected List<TextRepresentation> createTextRepresentationList(
final String writtenText, final ILanguage language) {
List<TextRepresentation> result = new ArrayList<TextRepresentation>();
TextRepresentation textRepresentation = new TextRepresentation();
textRepresentation.setWrittenText(convert(writtenText));
textRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(language));
result.add(textRepresentation);
return result;
}
protected List<FormRepresentation> createFormRepresentationList(
final String writtenForm, final ILanguage language) {
List<FormRepresentation> result = new ArrayList<FormRepresentation>();
FormRepresentation formRepresentation = new FormRepresentation();
formRepresentation.setWrittenForm(convert(writtenForm, 255));
formRepresentation.setLanguageIdentifier(WiktionaryLMFMap.mapLanguage(language));
result.add(formRepresentation);
return result;
}
@Override
protected SubcategorizationFrame getNextSubcategorizationFrame() {
return (subcatFrames.isEmpty() ? null : subcatFrames.remove(subcatFrames.firstKey()));
}
@Override
protected Synset getNextSynset() {
// If we haven't started yet, initialize the iterator.
if (synsetIter == null)
try {
synsetIter = ontoWiktionary.getStreamedConcepts().iterator();
} catch (Exception e) {
throw new RuntimeException(e);
}
// If we're finished, convert the synset relations and free resources.
if (!synsetIter.hasNext()) {
synsetIter = null;
convertSynsetRelations();
ontoWiktionary.freeConcepts();
return null;
}
// Check if at least one sense exists.
OntoWiktionaryConcept owktSynset = synsetIter.next();
List<Sense> senses = new LinkedList<Sense>();
for (String lexicalization : owktSynset.getLexicalizations()) {
String senseId = getLmfId(Sense.class, getSenseId(lexicalization));
Sense sense = (Sense) getLmfObjectById(Sense.class, senseId);
if (sense == null) {
// Caused by different sense selection (e.g., inflected forms)
// System.err.println("Sense not found: " + lexicalization);
continue;
}
if (sense.getSynset() != null) {
System.err.println("Inconsistent synset structure for " + lexicalization);
}
senses.add(sense);
}
if (senses.size() == 0)
return getNextSynset();
// Synset.
Synset synset = new Synset();
synset.setId(getLmfId(Synset.class, getSynsetId(owktSynset.getConceptId())));
// MonolingualExternalRef.
List<MonolingualExternalRef> monolingualExternalRefs = new LinkedList<MonolingualExternalRef>();
MonolingualExternalRef monolingualExternalRef = new MonolingualExternalRef();
monolingualExternalRef.setExternalSystem("OntoWiktionary" + wktLang.getISO639_1().toUpperCase() + "_ConceptID");
monolingualExternalRef.setExternalReference(owktSynset.getConceptId());
monolingualExternalRefs.add(monolingualExternalRef);
synset.setMonolingualExternalRefs(monolingualExternalRefs);
// Senses.
for (Sense sense : senses)
sense.setSynset(synset);
synset.setSenses(senses);
return synset;
}
protected void convertSynsetRelations() {
try {
synsetIter = ontoWiktionary.getConcepts().iterator();
} catch (Exception e) {
throw new RuntimeException(e);
}
int conceptCount = 0;
while (synsetIter.hasNext()) {
OntoWiktionaryConcept owktSynset = synsetIter.next();
Synset source = (Synset) getLmfObjectById(Synset.class,
getLmfId(Synset.class, getSynsetId(owktSynset.getConceptId())));
if (source == null) {
// System.err.println("Source concept not found: " + owktSynset.getConceptId());
continue;
}
// SynsetRelation.
List<SynsetRelation> synsetRelations = new LinkedList<SynsetRelation>();
addSynsetRelations(synsetRelations, owktSynset.getSubsumesRelations(),
ERelTypeSemantics.taxonomic, "subsumes", source);
addSynsetRelations(synsetRelations, owktSynset.getSubsumedByRelations(),
ERelTypeSemantics.taxonomic, "subsumedBy", source);
addSynsetRelations(synsetRelations, owktSynset.getRelatedConcepts(),
ERelTypeSemantics.association, "related", source);
source.setSynsetRelations(synsetRelations);
saveCascade(source);
if (++conceptCount % 1000 == 0) {
System.out.println("SAVING RELATIONS / PROCESSED " + conceptCount + " SYNSETS");
tx.commit();
session.close();
session = sessionFactory.openSession();
tx = session.beginTransaction();
}
}
synsetIter = null;
}
protected void addSynsetRelations(final List<SynsetRelation> synsetRelations,
final Iterable<String> relationTargets,
final ERelTypeSemantics relType, final String relName,
final Synset source) {
for (String targetID : relationTargets) {
Synset target = (Synset) getLmfObjectById(Synset.class,
getLmfId(Synset.class, getSynsetId(targetID)));
if (target == null) {
// System.err.println("Target concept not found: " + targetID);
continue;
}
SynsetRelation synsetRelation = new SynsetRelation();
synsetRelation.setRelType(relType);
synsetRelation.setRelName(relName);
synsetRelation.setSource(source);
synsetRelation.setTarget(target);
synsetRelations.add(synsetRelation);
}
}
@Override
protected ConstraintSet getNextConstraintSet() { return null;}
@Override
protected SemanticPredicate getNextSemanticPredicate() { return null;}
@Override
protected SenseAxis getNextSenseAxis() { return null;}
@Override
protected SubcategorizationFrameSet getNextSubcategorizationFrameSet() {return null;}
@Override
protected SynSemCorrespondence getNextSynSemCorrespondence() { return null;}
@Override
protected void finish() {
commit();
// Save all unsaved word froms from the cache.
int size = wordForms.size();
System.out.println("Finishing WORD FORMS... " + size);
for (Entry<String, List<WordForm>> entry : wordForms.entrySet()) {
if (size % 1000 == 0)
System.out.println("SAVING WORD FORMS: " + size + " LEFT");
LexicalEntry lexEntry = (LexicalEntry)getLmfObjectById(LexicalEntry.class, entry.getKey());
if (lexEntry != null) {
if (lexEntry.getWordForms() == null) {
lexEntry.setWordForms(entry.getValue());
} else {
lexEntry.getWordForms().addAll(entry.getValue());
}
// Save word forms and update lexEntry.
saveList(lexEntry, lexEntry.getWordForms());
}
size--;
}
}
/** Returns unique entry ID for a WiktionaryEntry. */
protected String getEntryId(IWiktionaryEntry entry){
return "e" + entry.getKey();
}
/** Returns unique sense ID for a WiktionarySense. */
protected String getSenseId(IWiktionarySense sense){
return getSenseId(sense.getKey());
}
protected String getSenseId(final String senseKey){
return "s" + senseKey;
}
protected String getSynsetId(final String conceptId) {
return "c" + conceptId;
}
private static String convert(final String text) {
return StringUtils.replaceNonUtf8(
StringUtils.replaceHtmlEntities(text));
}
private static String convert(final String text, int maxLength) {
if (text == null)
return null;
else
return StringUtils.replaceNonUtf8(
StringUtils.replaceHtmlEntities(text), maxLength);
}
protected String convertEtymology(final IWikiString etymology) {
if (etymology == null)
return null;
try {
String result = TemplateParser.parse(etymology.getText(), new EtymologyTemplateHandler());
return WikiString.makePlainText(result);
} catch (Exception e) {
return WikiString.makePlainText(etymology.getText());
}
}
}
| 52,716 | 0.711714 | 0.708906 | 1,366 | 37.585651 | 26.180271 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.900439 | false | false |
13
|
5ab6ff81246183f500aee12b3367acb5829dec6c
| 23,476,291,288,823 |
11597f0b6948fcba9ee57bb094f899386d2d2892
|
/SHS_Contact_Android/app/src/main/java/com/shs/contact/utils/GestureAdapter.java
|
6c90573eec80eefd232acb0cca57e572c0626354
|
[] |
no_license
|
yukirin000/KHClub_Android
|
https://github.com/yukirin000/KHClub_Android
|
8827d44fed7cfa64af425b8f16091a9e9aed1f1a
|
0aefffe71edc71da43663041606af25803ec8248
|
refs/heads/master
| 2021-01-10T01:10:29.644000 | 2016-02-24T11:07:30 | 2016-02-24T11:07:30 | 43,664,111 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.shs.contact.utils;
import android.view.GestureDetector;
import android.view.MotionEvent;
/**
* Created by wenhai on 2016/2/19.
* 手势操作适配器根据不同的需求重写写相关方法即可
*/
public class GestureAdapter implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener{
/**
* 单击事件
*/
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
/**
* 双击事件
*/
@Override
public boolean onDoubleTap(MotionEvent e) { return false; }
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
// 用户轻触触摸屏
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
// 轻击一下屏幕,立刻抬起来,才会有这个触发
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
// 用户按下触摸屏,并拖动
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
// 用户长按触摸屏,由多个MotionEvent ACTION_DOWN触发
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
|
UTF-8
|
Java
| 1,462 |
java
|
GestureAdapter.java
|
Java
|
[
{
"context": "mport android.view.MotionEvent;\n\n/**\n * Created by wenhai on 2016/2/19.\n * 手势操作适配器根据不同的需求重写写相关方法即可\n */\npubl",
"end": 127,
"score": 0.9995571970939636,
"start": 121,
"tag": "USERNAME",
"value": "wenhai"
}
] | null |
[] |
package com.shs.contact.utils;
import android.view.GestureDetector;
import android.view.MotionEvent;
/**
* Created by wenhai on 2016/2/19.
* 手势操作适配器根据不同的需求重写写相关方法即可
*/
public class GestureAdapter implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener{
/**
* 单击事件
*/
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
/**
* 双击事件
*/
@Override
public boolean onDoubleTap(MotionEvent e) { return false; }
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
// 用户轻触触摸屏
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
// 轻击一下屏幕,立刻抬起来,才会有这个触发
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
// 用户按下触摸屏,并拖动
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
// 用户长按触摸屏,由多个MotionEvent ACTION_DOWN触发
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
| 1,462 | 0.665639 | 0.657165 | 58 | 21.379311 | 24.176668 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.293103 | false | false |
13
|
2dc116ae27a6a8cb9b30991f62b7b5c4b1998a63
| 28,707,561,454,853 |
aa907db6c67504525d704206c9ad3a923c1d7ccd
|
/app/src/main/java/br/net/cicerosantos/compras2/model/Usuario.java
|
e9358fd0e748c401b55a3e22391b3e1a8b6ac1dc
|
[] |
no_license
|
cicerosnt/AppListaDeCompra
|
https://github.com/cicerosnt/AppListaDeCompra
|
e478fe322d879dae28ba20b8c7d85d884d015540
|
efd7648669f6977353388e3883c2b50b5a06aaaa
|
refs/heads/master
| 2021-03-06T13:22:38.761000 | 2020-03-12T01:55:17 | 2020-03-12T01:55:17 | 246,202,649 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.net.cicerosantos.compras2.model;
public class Usuario {
}
|
UTF-8
|
Java
| 70 |
java
|
Usuario.java
|
Java
|
[] | null |
[] |
package br.net.cicerosantos.compras2.model;
public class Usuario {
}
| 70 | 0.785714 | 0.771429 | 4 | 16.5 | 17.642279 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
13
|
5549caba6e644e140f8c68ae5b72490f2ef45c65
| 32,856,499,858,559 |
13fefd5ae720877e9f72f54334a3d67656976e12
|
/lss-my/src/main/java/jedis/JedisTest.java
|
b295997c61e7ff8cf721dba629ad64222966652b
|
[] |
no_license
|
LISEESEE/guli_college_back
|
https://github.com/LISEESEE/guli_college_back
|
8f60bc7701ae1407a80b1cd20f71ebae0a9f7e47
|
e5bcfd751945e8845f41662b95b74538ddfc0cee
|
refs/heads/main
| 2023-02-19T00:52:52.618000 | 2021-01-22T02:40:01 | 2021-01-22T02:40:01 | 323,914,150 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package jedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class JedisTest {
public static void main(String[] args) {
JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
Jedis jedis;
jedis = jedisPool.getResource();
jedis.set("aa","bb");
JedisPoolUtil.release(jedisPool,jedis);
}
}
|
UTF-8
|
Java
| 376 |
java
|
JedisTest.java
|
Java
|
[] | null |
[] |
package jedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class JedisTest {
public static void main(String[] args) {
JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
Jedis jedis;
jedis = jedisPool.getResource();
jedis.set("aa","bb");
JedisPoolUtil.release(jedisPool,jedis);
}
}
| 376 | 0.675532 | 0.675532 | 15 | 24.066668 | 20.071428 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
13
|
d0294d64bcf68807e100791ab61d96537f78db5d
| 18,339,510,399,340 |
4cda93305ce355c55fa01a0f11573c8220809bd7
|
/src/test/java/br/com/proway/senior/escola/ProvaTest.java
|
68228dfc6601da9788ca69c269c711b43ce705cd
|
[] |
no_license
|
Gabriel-Simon07/SchoolJavaExercises
|
https://github.com/Gabriel-Simon07/SchoolJavaExercises
|
4ddad3d45b441c3f7f231e50fb4e9c593cc1069c
|
018d56581155c8cc1f8f953fb4f9c0d264cf0254
|
refs/heads/main
| 2023-04-23T15:34:23.444000 | 2021-05-10T20:41:42 | 2021-05-10T20:41:42 | 365,247,998 | 0 | 0 | null | false | 2021-05-07T18:33:35 | 2021-05-07T13:47:25 | 2021-05-07T16:41:57 | 2021-05-07T18:24:13 | 6 | 0 | 0 | 1 |
Java
| false | false |
package br.com.proway.senior.escola;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.proway.senior.escola.model.Aluno;
import br.com.proway.senior.escola.model.Materia;
import br.com.proway.senior.escola.model.Prova;
public class ProvaTest {
static Prova prova;
@BeforeClass
public static void createProva(){
Integer periodo = 20210502;
Materia materia = new Materia();
Aluno aluno = new Aluno();
prova = new Prova (periodo, aluno, materia);
}
@Test
public void testProva() {
assertNotNull(prova);
}
@Test (expected = Exception.class)
public void testSetGetNotaIncorreta()throws Exception{
prova.setNota(-10.0);
}
@Test (expected = Exception.class)
public void testSetGetNotaCorreta() throws Exception{
try {
prova.setNota(10.0);
}catch(Exception e){
fail(e.getMessage());
}
assertEquals(10.0, (double) prova.getNota(), 0.01);
}
}
|
UTF-8
|
Java
| 1,058 |
java
|
ProvaTest.java
|
Java
|
[] | null |
[] |
package br.com.proway.senior.escola;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.proway.senior.escola.model.Aluno;
import br.com.proway.senior.escola.model.Materia;
import br.com.proway.senior.escola.model.Prova;
public class ProvaTest {
static Prova prova;
@BeforeClass
public static void createProva(){
Integer periodo = 20210502;
Materia materia = new Materia();
Aluno aluno = new Aluno();
prova = new Prova (periodo, aluno, materia);
}
@Test
public void testProva() {
assertNotNull(prova);
}
@Test (expected = Exception.class)
public void testSetGetNotaIncorreta()throws Exception{
prova.setNota(-10.0);
}
@Test (expected = Exception.class)
public void testSetGetNotaCorreta() throws Exception{
try {
prova.setNota(10.0);
}catch(Exception e){
fail(e.getMessage());
}
assertEquals(10.0, (double) prova.getNota(), 0.01);
}
}
| 1,058 | 0.713611 | 0.694707 | 45 | 22.51111 | 18.095575 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.088889 | false | false |
13
|
7e2d59266a807a6246c63b7117d1ab0fe67fde2d
| 1,864,015,857,054 |
1feb8f4c07e25b30ff9ec1bab8af4f42331a3763
|
/main/structural/adaptor/duckturkey/DuckTurkeyAdapter.java
|
ef7489411d37c3466abc26fead683b85342a3f79
|
[
"MIT"
] |
permissive
|
NathOrmond/java-design-patterns
|
https://github.com/NathOrmond/java-design-patterns
|
7debba92554ea9df6953d8ad0f702bfad7d7decc
|
b81acf663623f9e194523320f8b6b8d3e7ffda69
|
refs/heads/master
| 2022-12-23T21:41:08.699000 | 2020-09-25T09:08:34 | 2020-09-25T09:08:34 | 266,205,974 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package structural.adaptor.duckturkey;
public class DuckTurkeyAdapter implements IDuck {
private ITurkey wrappedInstance;
public DuckTurkeyAdapter(ITurkey wrappedInstance) {
this.wrappedInstance = wrappedInstance;
}
public void fly() {
wrappedInstance.run();
}
public void quack() {
wrappedInstance.gobble();
}
}
|
UTF-8
|
Java
| 359 |
java
|
DuckTurkeyAdapter.java
|
Java
|
[] | null |
[] |
package structural.adaptor.duckturkey;
public class DuckTurkeyAdapter implements IDuck {
private ITurkey wrappedInstance;
public DuckTurkeyAdapter(ITurkey wrappedInstance) {
this.wrappedInstance = wrappedInstance;
}
public void fly() {
wrappedInstance.run();
}
public void quack() {
wrappedInstance.gobble();
}
}
| 359 | 0.70195 | 0.70195 | 21 | 15.095238 | 17.91489 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.047619 | false | false |
13
|
e0b8abdd98b5fbf70e060b1a362f2a791d5cd363
| 11,888,469,509,366 |
e05975d6314d5d851eabd598096459b82407d49b
|
/src/labDay1/StackInt.java
|
b5bcf23616b2d0f1127d89510c5d1de23e822ffc
|
[] |
no_license
|
sanella/week10
|
https://github.com/sanella/week10
|
3e121874c6ee0053a5040efc53589486ff605ae3
|
94325edf869afd6d3626aa99389a55fe6fbb15a9
|
refs/heads/master
| 2021-01-22T09:09:14.233000 | 2015-01-15T18:35:36 | 2015-01-15T18:35:36 | 29,311,701 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package labDay1;
import javax.xml.soap.Node;
public class StackInt {
private Node head;
//Constructor
public StackInt(){
head =null;
}
// Private class for Node
private class Node{
public int value;
public Node next;
public Node(int value){
this.value = value;
next = null;
}
}
// function for adding a number in stack
public void push(int value){
Node newNode=new Node(value);
newNode.next = head;
head = newNode;
}
// function for removing a number from stack, LIFO method
public int pop(){
if(head==null)
throw new IllegalArgumentException("Steac is empty") ;
Node current = head;
head = head.next;
int value=current.value;
current = null;
return value;
}
public int peek(){
if(head==null)
throw new IllegalArgumentException("Steac is empty") ;
return head.value;
}
// get size of stack
public int getSize(){
if(head == null)
return 0;
return getSize(head, 0);
}
// getSize recursion
private int getSize(Node current, int counter){
if(current == null)
return counter;
return getSize(current.next, counter +1);
}
// for caching is this value in stack
public boolean contains(int value){
if( head.value == value)
return true;
return contains(head, value);
}
// recursion for contains methode
public boolean contains(Node current, int value){
if(current == null)
return false;
if(current.value == value)
return true;
return contains(current.next, value);
}
// @Override
// public String toString() {
// Node current = head;
// String str = "{";
// for(int i = 0; i<getSize(); i++){
// str += current.value;
// head = head.next;
// }
//
// return str;
// }
}
|
UTF-8
|
Java
| 1,701 |
java
|
StackInt.java
|
Java
|
[] | null |
[] |
package labDay1;
import javax.xml.soap.Node;
public class StackInt {
private Node head;
//Constructor
public StackInt(){
head =null;
}
// Private class for Node
private class Node{
public int value;
public Node next;
public Node(int value){
this.value = value;
next = null;
}
}
// function for adding a number in stack
public void push(int value){
Node newNode=new Node(value);
newNode.next = head;
head = newNode;
}
// function for removing a number from stack, LIFO method
public int pop(){
if(head==null)
throw new IllegalArgumentException("Steac is empty") ;
Node current = head;
head = head.next;
int value=current.value;
current = null;
return value;
}
public int peek(){
if(head==null)
throw new IllegalArgumentException("Steac is empty") ;
return head.value;
}
// get size of stack
public int getSize(){
if(head == null)
return 0;
return getSize(head, 0);
}
// getSize recursion
private int getSize(Node current, int counter){
if(current == null)
return counter;
return getSize(current.next, counter +1);
}
// for caching is this value in stack
public boolean contains(int value){
if( head.value == value)
return true;
return contains(head, value);
}
// recursion for contains methode
public boolean contains(Node current, int value){
if(current == null)
return false;
if(current.value == value)
return true;
return contains(current.next, value);
}
// @Override
// public String toString() {
// Node current = head;
// String str = "{";
// for(int i = 0; i<getSize(); i++){
// str += current.value;
// head = head.next;
// }
//
// return str;
// }
}
| 1,701 | 0.651382 | 0.648442 | 90 | 17.9 | 14.395254 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.988889 | false | false |
13
|
d6c933c2422fe7a22c754b863a8ee734f1954b13
| 16,295,105,951,156 |
ee0aaafc92e97e2bfac9858a0c133b16fd55fbb1
|
/vua-upms/vua-upms-rpc-api/src/main/java/com/vua/upms/rpc/api/UpmsOrganizationServiceMock.java
|
61f116b92a08fd976e9438019d3417428340e0b0
|
[] |
no_license
|
jachwang/vua
|
https://github.com/jachwang/vua
|
f12e4e0ef400ce9805a506d789fadfd7c9f28296
|
639ff0a52daaa261183e3de8b8af4ed6c67af27c
|
refs/heads/master
| 2020-04-26T07:27:50.009000 | 2017-08-29T11:44:20 | 2017-08-29T11:44:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vua.upms.rpc.api;
import com.vua.common.base.BaseServiceMock;
import com.vua.upms.dao.mapper.UpmsOrganizationMapper;
import com.vua.upms.dao.model.UpmsOrganization;
import com.vua.upms.dao.model.UpmsOrganizationExample;
/**
* 降级实现UpmsOrganizationService接口
* Created on 2017/6/24.
*/
public class UpmsOrganizationServiceMock extends BaseServiceMock<UpmsOrganizationMapper, UpmsOrganization, UpmsOrganizationExample> implements UpmsOrganizationService {
}
|
UTF-8
|
Java
| 481 |
java
|
UpmsOrganizationServiceMock.java
|
Java
|
[] | null |
[] |
package com.vua.upms.rpc.api;
import com.vua.common.base.BaseServiceMock;
import com.vua.upms.dao.mapper.UpmsOrganizationMapper;
import com.vua.upms.dao.model.UpmsOrganization;
import com.vua.upms.dao.model.UpmsOrganizationExample;
/**
* 降级实现UpmsOrganizationService接口
* Created on 2017/6/24.
*/
public class UpmsOrganizationServiceMock extends BaseServiceMock<UpmsOrganizationMapper, UpmsOrganization, UpmsOrganizationExample> implements UpmsOrganizationService {
}
| 481 | 0.837953 | 0.823028 | 14 | 32.5 | 42.821472 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
13
|
ba3e9ced0b4c654b9e33801f59e607ef9a65c69a
| 14,216,341,809,457 |
a3d22ac4335e480aff620d25944d9fed03874534
|
/Common-Java/src/net/socket/SocketListenerThread.java
|
265aa249dd4565513feffb6ab506a76377580f69
|
[] |
no_license
|
daileyet/openlib
|
https://github.com/daileyet/openlib
|
51e45fede4507f9c2e928fdcc282ffa33cb73087
|
fe916866dac1f5ca329c20f4d15807f5d54118c7
|
refs/heads/master
| 2021-01-22T13:47:26.754000 | 2016-10-20T08:55:57 | 2016-10-20T08:55:57 | 23,650,137 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* Thread for listening socket
*
* @author dailey_dai Feb 12, 2011
*/
public class SocketListenerThread extends Thread {
private SocketBean socketBean = null;
private Socket socket = null;
// for client
public SocketListenerThread(SocketBean clientBean) {
this(clientBean, null);
}
// for server
public SocketListenerThread(SocketBean serverBean, Socket socket) {
this.socketBean = serverBean;
this.socket = socket;
}
public void setSocketBean(SocketBean socketBean) {
this.socketBean = socketBean;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
/**
* get current socket object
*
* @return
*/
protected Socket getSocket() {
if (socket == null) {// client
return socketBean.getClient();
} else {// server
return socket;
}
}
public void run() {
BufferedReader br = null;// in stream
while (socketBean.isAlive()) {// if not closed
if (br == null) {
try {// client socket's inputstream
br = new BufferedReader(new InputStreamReader(getSocket()
.getInputStream()));
} catch (IOException e) {
socketBean.getSocketActionListener().onGetException(e);
}
}
String response = null;
try {
response = br.readLine();
// call back
socketBean.getSocketActionListener().onDataReceived(
getSocket(), response);
} catch (IOException e) {
// call back
socketBean.getSocketActionListener().onGetException(e);
break;
}
}
}
}
|
UTF-8
|
Java
| 1,608 |
java
|
SocketListenerThread.java
|
Java
|
[
{
"context": "\n/**\n * Thread for listening socket\n * \n * @author dailey_dai Feb 12, 2011\n */\npublic class SocketListenerThrea",
"end": 199,
"score": 0.9994699358940125,
"start": 189,
"tag": "USERNAME",
"value": "dailey_dai"
}
] | null |
[] |
package net.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* Thread for listening socket
*
* @author dailey_dai Feb 12, 2011
*/
public class SocketListenerThread extends Thread {
private SocketBean socketBean = null;
private Socket socket = null;
// for client
public SocketListenerThread(SocketBean clientBean) {
this(clientBean, null);
}
// for server
public SocketListenerThread(SocketBean serverBean, Socket socket) {
this.socketBean = serverBean;
this.socket = socket;
}
public void setSocketBean(SocketBean socketBean) {
this.socketBean = socketBean;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
/**
* get current socket object
*
* @return
*/
protected Socket getSocket() {
if (socket == null) {// client
return socketBean.getClient();
} else {// server
return socket;
}
}
public void run() {
BufferedReader br = null;// in stream
while (socketBean.isAlive()) {// if not closed
if (br == null) {
try {// client socket's inputstream
br = new BufferedReader(new InputStreamReader(getSocket()
.getInputStream()));
} catch (IOException e) {
socketBean.getSocketActionListener().onGetException(e);
}
}
String response = null;
try {
response = br.readLine();
// call back
socketBean.getSocketActionListener().onDataReceived(
getSocket(), response);
} catch (IOException e) {
// call back
socketBean.getSocketActionListener().onGetException(e);
break;
}
}
}
}
| 1,608 | 0.68097 | 0.677239 | 76 | 20.157894 | 18.36548 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
13
|
aa28b7801a956e26705f57ce85aef92c65f07522
| 4,793,183,534,524 |
347fd7efefc7d26d82211fef59f0023ba96707f9
|
/src/main/java/cn/edu/nju/charlesfeng/util/enums/OrderWay.java
|
81ffe76021363128af7d1f7137d4f39ab5c354f1
|
[] |
no_license
|
CharlesFeng47/TicketsManagementSystem
|
https://github.com/CharlesFeng47/TicketsManagementSystem
|
e51a0afbe9297b0bf5e9d196cc6abb7cc4f5e7d7
|
f043d4a909d999fef9bbc68b14bf02122ba587d8
|
refs/heads/master
| 2021-04-03T11:48:16.383000 | 2018-07-15T15:48:28 | 2018-07-15T15:48:28 | 125,184,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.edu.nju.charlesfeng.util.enums;
/**
* 订单生成的购票形式
*/
public enum OrderWay {
// 用户自己购买
BUY_ON_MEMBER,
// 场馆现场购票
BUY_ON_SPOT
}
|
UTF-8
|
Java
| 196 |
java
|
OrderWay.java
|
Java
|
[] | null |
[] |
package cn.edu.nju.charlesfeng.util.enums;
/**
* 订单生成的购票形式
*/
public enum OrderWay {
// 用户自己购买
BUY_ON_MEMBER,
// 场馆现场购票
BUY_ON_SPOT
}
| 196 | 0.61039 | 0.61039 | 12 | 11.833333 | 11.610579 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false |
13
|
c0d79ad1973cc2863dcff66647d987c10ed3b4b9
| 25,640,954,820,183 |
26b7f30c6640b8017a06786e4a2414ad8a4d71dd
|
/src/number_of_direct_superinterfaces/i64912.java
|
34222715ce5f8b8bdcbb68c0bb942b565e0fc64b
|
[] |
no_license
|
vincentclee/jvm-limits
|
https://github.com/vincentclee/jvm-limits
|
b72a2f2dcc18caa458f1e77924221d585f23316b
|
2fd1c26d1f7984ea8163bc103ad14b6d72282281
|
refs/heads/master
| 2020-05-18T11:18:41.711000 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package number_of_direct_superinterfaces;
public interface i64912 {}
|
UTF-8
|
Java
| 69 |
java
|
i64912.java
|
Java
|
[] | null |
[] |
package number_of_direct_superinterfaces;
public interface i64912 {}
| 69 | 0.826087 | 0.753623 | 3 | 22.333334 | 16.937796 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
13
|
ffb30ef9ee863bcc1181da24d6406a93e94f47f3
| 33,131,377,789,160 |
d05580ec1339b3774f78475fe33626eb7eae86e9
|
/LEAP.DEMO.BLL/src/com/lr/demo/client/DemoTree.java
|
4fa33097c78c09db301ffddd30c405a4b35041f9
|
[] |
no_license
|
zhaoccx/LS
|
https://github.com/zhaoccx/LS
|
0ff32bfa49e880bcb49ff9fd36d611261c360580
|
0151c351d2663b262aeede9df03e217c77190f0f
|
refs/heads/master
| 2018-02-10T19:46:41.346000 | 2018-02-06T09:53:42 | 2018-02-06T09:53:42 | 44,287,997 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lr.demo.client;
import com.longrise.LEAP.BLL.Cache.SearchBuilder;
import com.longrise.LEAP.BLL.Cache.util.AreaFilter;
import com.longrise.LEAP.Base.Global;
import com.longrise.LEAP.Base.Logic.LEAPLogic;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.LEAP.Base.Util.StringUtils;
/**
* @author zhaocc
* @time Aug 22, 2017 8:32:47 AM
* @parent
*/
public class DemoTree extends LEAPLogic {
/**
*
* @author zhaocc
* @time Aug 19, 2017 7:12:47 PM
* @param provinceid
* @return
* @path
* @parent
*/
public EntityBean[] searchProvince(String provinceid) {
if (StringUtils.isEmpty(provinceid)) {
return null;
}
EntityBean[] beans = null;
try {
beans = SearchBuilder.build("province").fields("areaid,provincename as areaname").par("provinceid", provinceid, 11).beanSearch();
for (int i = 0; i < beans.length; i++) {
beans[i].set("hasChild", true);
}
return beans;
} catch (Exception e) {
Global.getInstance().LogApp(e);
return null;
}
}
/**
*
* @author zhaocc
* @time Aug 19, 2017 7:12:52 PM
* @param areaid
* @return
* @path
* @parent
*/
public EntityBean[] searchChildByAreaid(String areaid) {
if (StringUtils.isEmpty(areaid)) {
return null;
}
String realAreaid = AreaFilter.getRealAreaID(areaid);
String tableName = null;
String namefield = null;
if (realAreaid.length() == 2) {
tableName = "city";
namefield = "cityname";
} else if (realAreaid.length() == 4) {
tableName = "county";
namefield = "countyname";
} else if (realAreaid.length() == 6) {
tableName = "street";
namefield = "streetname";
} else if (realAreaid.length() == 9) {
tableName = "community";
namefield = "communityname";
} else if (realAreaid.length() == 12) {
tableName = "team";
namefield = "teamname";
}
String maxAreaid = AreaFilter.getMaxAreaID(realAreaid);
String minAreaid = AreaFilter.getMinAreaID(realAreaid);
SearchBuilder builder = SearchBuilder.build(tableName).fields("areaid," + namefield + " as areaname");
builder.addParameter("areaid", minAreaid, 14);
builder.addParameter("areaid", maxAreaid, 15);
EntityBean[] beans = builder.beanSearch();
for (int i = 0; i < beans.length; i++) {
if (realAreaid.length() < 12) {
beans[i].set("hasChild", true);
} else {
beans[i].set("hasChild", false);
}
}
return beans;
}
}
|
UTF-8
|
Java
| 2,494 |
java
|
DemoTree.java
|
Java
|
[
{
"context": "ise.LEAP.Base.Util.StringUtils;\r\n\r\n/**\r\n * @author zhaocc\r\n * @time Aug 22, 2017 8:32:47 AM\r\n * @parent\r\n *",
"end": 346,
"score": 0.9996601939201355,
"start": 340,
"tag": "USERNAME",
"value": "zhaocc"
},
{
"context": "ree extends LEAPLogic {\r\n\r\n\t/**\r\n\t * \r\n\t * @author zhaocc\r\n\t * @time Aug 19, 2017 7:12:47 PM\r\n\t * @param pr",
"end": 474,
"score": 0.9996694922447205,
"start": 468,
"tag": "USERNAME",
"value": "zhaocc"
},
{
"context": "\t\treturn null;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * \r\n\t * @author zhaocc\r\n\t * @time Aug 19, 2017 7:12:52 PM\r\n\t * @param ar",
"end": 1099,
"score": 0.999669075012207,
"start": 1093,
"tag": "USERNAME",
"value": "zhaocc"
}
] | null |
[] |
package com.lr.demo.client;
import com.longrise.LEAP.BLL.Cache.SearchBuilder;
import com.longrise.LEAP.BLL.Cache.util.AreaFilter;
import com.longrise.LEAP.Base.Global;
import com.longrise.LEAP.Base.Logic.LEAPLogic;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.LEAP.Base.Util.StringUtils;
/**
* @author zhaocc
* @time Aug 22, 2017 8:32:47 AM
* @parent
*/
public class DemoTree extends LEAPLogic {
/**
*
* @author zhaocc
* @time Aug 19, 2017 7:12:47 PM
* @param provinceid
* @return
* @path
* @parent
*/
public EntityBean[] searchProvince(String provinceid) {
if (StringUtils.isEmpty(provinceid)) {
return null;
}
EntityBean[] beans = null;
try {
beans = SearchBuilder.build("province").fields("areaid,provincename as areaname").par("provinceid", provinceid, 11).beanSearch();
for (int i = 0; i < beans.length; i++) {
beans[i].set("hasChild", true);
}
return beans;
} catch (Exception e) {
Global.getInstance().LogApp(e);
return null;
}
}
/**
*
* @author zhaocc
* @time Aug 19, 2017 7:12:52 PM
* @param areaid
* @return
* @path
* @parent
*/
public EntityBean[] searchChildByAreaid(String areaid) {
if (StringUtils.isEmpty(areaid)) {
return null;
}
String realAreaid = AreaFilter.getRealAreaID(areaid);
String tableName = null;
String namefield = null;
if (realAreaid.length() == 2) {
tableName = "city";
namefield = "cityname";
} else if (realAreaid.length() == 4) {
tableName = "county";
namefield = "countyname";
} else if (realAreaid.length() == 6) {
tableName = "street";
namefield = "streetname";
} else if (realAreaid.length() == 9) {
tableName = "community";
namefield = "communityname";
} else if (realAreaid.length() == 12) {
tableName = "team";
namefield = "teamname";
}
String maxAreaid = AreaFilter.getMaxAreaID(realAreaid);
String minAreaid = AreaFilter.getMinAreaID(realAreaid);
SearchBuilder builder = SearchBuilder.build(tableName).fields("areaid," + namefield + " as areaname");
builder.addParameter("areaid", minAreaid, 14);
builder.addParameter("areaid", maxAreaid, 15);
EntityBean[] beans = builder.beanSearch();
for (int i = 0; i < beans.length; i++) {
if (realAreaid.length() < 12) {
beans[i].set("hasChild", true);
} else {
beans[i].set("hasChild", false);
}
}
return beans;
}
}
| 2,494 | 0.635525 | 0.615878 | 93 | 24.838709 | 22.140942 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.193548 | false | false |
13
|
a7c7dc6e3aaf3ff8342d9e40dd8debb4c9f5efbe
| 24,369,644,484,150 |
7136c4475855ab35bdb010a1678e2cb55a2ec7e9
|
/AutorouteServices/src/test/java/test/org/autoroute/common/dao/mock/MultiChannelMeasurementDaoMockImpl.java
|
c1f5303ccfe683bc64d498c576be6e146c396d26
|
[
"MIT"
] |
permissive
|
shannonlal/AutorouteServices
|
https://github.com/shannonlal/AutorouteServices
|
cbe9767b9c19694f1ecf8b917dfb3fc2e8d0f545
|
34f8fb1848d7aafa8c06a7fdd3e2c047a0934a07
|
refs/heads/master
| 2016-09-09T15:30:08.749000 | 2014-12-13T13:09:05 | 2014-12-13T13:09:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test.org.autoroute.common.dao.mock;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.autoroute.common.dao.AutorouteException;
import org.autoroute.common.dao.MultiChannelMeasurementDao;
import org.autoroute.common.domain.Device;
import org.autoroute.common.domain.MultiChannelMeasurement;
public class MultiChannelMeasurementDaoMockImpl extends AutorouteAbstractBaseMockDao<MultiChannelMeasurement, Long> implements MultiChannelMeasurementDao{
public static final Logger LOGGER = Logger.getLogger(MultiChannelMeasurementDaoMockImpl.class.getName());
private Map<Long, MultiChannelMeasurement> dao;
private int counter;
private int spectrumCounter;
public MultiChannelMeasurementDaoMockImpl(){
super();
dao = new HashMap<Long, MultiChannelMeasurement>();
//spectrumDao = new HashMap<Integer,MultiChannelMeasurement>();
counter = 1;
spectrumCounter = 1;
}
@Override
protected Long generateNextKey(MultiChannelMeasurement obj) throws AutorouteException {
obj.setId( counter ++);
return obj.getId();
}
@Override
protected Long getKey(MultiChannelMeasurement obj) throws AutorouteException {
return obj.getId();
}
protected Long generateNextSpectrumKey(MultiChannelMeasurement obj) throws AutorouteException {
obj.setId( spectrumCounter ++);
return obj.getId();
}
protected Long getSpectrumKey(MultiChannelMeasurement obj) throws AutorouteException {
return obj.getId();
}
/**
*
*
*/
@Override
public MultiChannelMeasurement getLatestMeasurementByDevice(Device d)
throws AutorouteException {
Long id = new Long (counter -1);
return mockDao.get(id);
}
@Override
public MultiChannelMeasurement findById(Long id) throws AutorouteException {
return super.findbyId(id);
}
/*private MultiChannelMeasurement createEmptyMeasurement(){
MultiChannelMeasurement m = new MultiChannelMeasurement();
MeasurementDetails mDetails = new MeasurementDetails();
mDetails.setDate(new Timestamp(System.currentTimeMillis()));
Device d = new Device();
d.setUiid("12313");
d.setDataProcessor("TestDevice");
d.setDescription("Test Device");
d.setActive(true);
mDetails.setDevice(d);
ReadingType rt = new ReadingType();
rt.setType( ReadingType.MULTI_CHANNEL);
mDetails.setReadingType( rt );
UnitOfMeasurement uOfM = new UnitOfMeasurement();
uOfM.setUofType( UnitOfMeasurement.uS_Hr);
uOfM.setDescription( "uShv");
mDetails.setUnitOfMeasurement( uOfM );
m.setMeasurementDetails(mDetails);
for(int i=0;i<3;i++){
MultiMeasurementDataPoint dp = new MultiMeasurementDataPoint((i*100.0), (i*50.1));
m.addDataPoint(dp);
}
return m;
}*/
}
|
UTF-8
|
Java
| 2,933 |
java
|
MultiChannelMeasurementDaoMockImpl.java
|
Java
|
[] | null |
[] |
package test.org.autoroute.common.dao.mock;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.autoroute.common.dao.AutorouteException;
import org.autoroute.common.dao.MultiChannelMeasurementDao;
import org.autoroute.common.domain.Device;
import org.autoroute.common.domain.MultiChannelMeasurement;
public class MultiChannelMeasurementDaoMockImpl extends AutorouteAbstractBaseMockDao<MultiChannelMeasurement, Long> implements MultiChannelMeasurementDao{
public static final Logger LOGGER = Logger.getLogger(MultiChannelMeasurementDaoMockImpl.class.getName());
private Map<Long, MultiChannelMeasurement> dao;
private int counter;
private int spectrumCounter;
public MultiChannelMeasurementDaoMockImpl(){
super();
dao = new HashMap<Long, MultiChannelMeasurement>();
//spectrumDao = new HashMap<Integer,MultiChannelMeasurement>();
counter = 1;
spectrumCounter = 1;
}
@Override
protected Long generateNextKey(MultiChannelMeasurement obj) throws AutorouteException {
obj.setId( counter ++);
return obj.getId();
}
@Override
protected Long getKey(MultiChannelMeasurement obj) throws AutorouteException {
return obj.getId();
}
protected Long generateNextSpectrumKey(MultiChannelMeasurement obj) throws AutorouteException {
obj.setId( spectrumCounter ++);
return obj.getId();
}
protected Long getSpectrumKey(MultiChannelMeasurement obj) throws AutorouteException {
return obj.getId();
}
/**
*
*
*/
@Override
public MultiChannelMeasurement getLatestMeasurementByDevice(Device d)
throws AutorouteException {
Long id = new Long (counter -1);
return mockDao.get(id);
}
@Override
public MultiChannelMeasurement findById(Long id) throws AutorouteException {
return super.findbyId(id);
}
/*private MultiChannelMeasurement createEmptyMeasurement(){
MultiChannelMeasurement m = new MultiChannelMeasurement();
MeasurementDetails mDetails = new MeasurementDetails();
mDetails.setDate(new Timestamp(System.currentTimeMillis()));
Device d = new Device();
d.setUiid("12313");
d.setDataProcessor("TestDevice");
d.setDescription("Test Device");
d.setActive(true);
mDetails.setDevice(d);
ReadingType rt = new ReadingType();
rt.setType( ReadingType.MULTI_CHANNEL);
mDetails.setReadingType( rt );
UnitOfMeasurement uOfM = new UnitOfMeasurement();
uOfM.setUofType( UnitOfMeasurement.uS_Hr);
uOfM.setDescription( "uShv");
mDetails.setUnitOfMeasurement( uOfM );
m.setMeasurementDetails(mDetails);
for(int i=0;i<3;i++){
MultiMeasurementDataPoint dp = new MultiMeasurementDataPoint((i*100.0), (i*50.1));
m.addDataPoint(dp);
}
return m;
}*/
}
| 2,933 | 0.704398 | 0.698602 | 97 | 28.237114 | 29.294373 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.350515 | false | false |
13
|
55e358b7dc1a3c81ce03f592afc1a922bc3ddcd1
| 34,222,299,437,850 |
e6fe8034c420b7fb8d2819df5107fdaf3c2aa06d
|
/app/src/main/java/br/com/nau/hortasurbanas/dao/PlantaDAO.java
|
4046fd11c5e9673b0671a758ddd5d95a4be62ec5
|
[] |
no_license
|
RicardoSilverio/tomatinhos-urbanos-android
|
https://github.com/RicardoSilverio/tomatinhos-urbanos-android
|
052c051ffc8869f33e3537bb6f8c0c702fa62d94
|
9a6f007e8e855d131e570dc04507cfb64c1b00a8
|
refs/heads/master
| 2017-05-11T21:38:07.669000 | 2017-02-22T01:24:55 | 2017-02-22T01:24:55 | 82,745,600 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.nau.hortasurbanas.dao;
import java.util.List;
import br.com.nau.hortasurbanas.model.Categoria;
import br.com.nau.hortasurbanas.model.Planta;
/**
* Created by silvr on 10/07/16.
*/
public interface PlantaDAO {
void atualizarCategoriasPlanta(List<Categoria> categorias);
Planta consultaPlantaPorId(String id);
void incluirAtualizarPlanta(Planta planta);
void excluirPlanta(String id);
List<Planta> listarPlantas();
}
|
UTF-8
|
Java
| 456 |
java
|
PlantaDAO.java
|
Java
|
[
{
"context": "nau.hortasurbanas.model.Planta;\n\n/**\n * Created by silvr on 10/07/16.\n */\npublic interface PlantaDAO {\n\n ",
"end": 182,
"score": 0.9996738433837891,
"start": 177,
"tag": "USERNAME",
"value": "silvr"
}
] | null |
[] |
package br.com.nau.hortasurbanas.dao;
import java.util.List;
import br.com.nau.hortasurbanas.model.Categoria;
import br.com.nau.hortasurbanas.model.Planta;
/**
* Created by silvr on 10/07/16.
*/
public interface PlantaDAO {
void atualizarCategoriasPlanta(List<Categoria> categorias);
Planta consultaPlantaPorId(String id);
void incluirAtualizarPlanta(Planta planta);
void excluirPlanta(String id);
List<Planta> listarPlantas();
}
| 456 | 0.756579 | 0.743421 | 18 | 24.333334 | 20.46406 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
13
|
c8a42b6cc33dd24f16de4b484f120ddf1162d44b
| 34,222,299,439,938 |
6c9eebf15d4712f59914b81b10b6f2c9c0844194
|
/redis-transaction/src/main/java/info/manxi/redis/lua/eval/RedisTemplateEnableTransaction.java
|
65faa8218b5672b98678ff78854468f576c994bc
|
[] |
no_license
|
hmgjdh521/redis-lua-101
|
https://github.com/hmgjdh521/redis-lua-101
|
39356fd363e9023844861455d1494a6d7aeb2681
|
5503d92f08b69cd23d048cf5c828745f407ca807
|
refs/heads/master
| 2022-03-23T18:39:50.742000 | 2019-12-07T07:04:38 | 2019-12-07T07:04:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package info.manxi.redis.lua.eval;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.TimeUnit;
@SpringBootApplication
public class RedisTemplateEnableTransaction {
public static void main(String[] args) {
var context = SpringApplication.run(RedisTemplateEnableTransaction.class, args);
var redisTemplate = (RedisTemplate<String, String>) context.getBean("redisTemplate");
var utf8 = StringRedisSerializer.UTF_8;
redisTemplate.setKeySerializer(utf8);
redisTemplate.setValueSerializer(utf8);
redisTemplate.setEnableTransactionSupport(true);// 启用事务 不然执行线程拿不到事务配置会报错
var start = Instant.now();
redisTemplate.multi();
for (var i =0; i < 300; i++) {
redisTemplate.opsForValue().set("tr_" + i, "1" + i);
}
List<Object> exec = redisTemplate.exec();
System.out.println(exec + " -- " + Duration.between(start, Instant.now()));
System.out.println(redisTemplate.opsForValue().get("tr_1"));
System.out.println(redisTemplate.opsForValue().get("tr_2"));
}
}
|
UTF-8
|
Java
| 1,427 |
java
|
RedisTemplateEnableTransaction.java
|
Java
|
[] | null |
[] |
package info.manxi.redis.lua.eval;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.TimeUnit;
@SpringBootApplication
public class RedisTemplateEnableTransaction {
public static void main(String[] args) {
var context = SpringApplication.run(RedisTemplateEnableTransaction.class, args);
var redisTemplate = (RedisTemplate<String, String>) context.getBean("redisTemplate");
var utf8 = StringRedisSerializer.UTF_8;
redisTemplate.setKeySerializer(utf8);
redisTemplate.setValueSerializer(utf8);
redisTemplate.setEnableTransactionSupport(true);// 启用事务 不然执行线程拿不到事务配置会报错
var start = Instant.now();
redisTemplate.multi();
for (var i =0; i < 300; i++) {
redisTemplate.opsForValue().set("tr_" + i, "1" + i);
}
List<Object> exec = redisTemplate.exec();
System.out.println(exec + " -- " + Duration.between(start, Instant.now()));
System.out.println(redisTemplate.opsForValue().get("tr_1"));
System.out.println(redisTemplate.opsForValue().get("tr_2"));
}
}
| 1,427 | 0.71305 | 0.705119 | 37 | 36.486488 | 28.658871 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.756757 | false | false |
13
|
6af13bf40286954fd00b385d96226609eeb8d77e
| 28,759,101,059,996 |
a4f3ad1023a9155b699e348b09c76058db0bbea3
|
/src/main/java/net/thumbtack/onlineshop/service/iface/AccountService.java
|
89981994c94dab289ee8195807649bd28f88e5f8
|
[] |
no_license
|
miffn3/online-shop
|
https://github.com/miffn3/online-shop
|
4acf0b2e5d0ca24b09115b478e5e557326d407a8
|
c1e985fccdd8beaee4d7833ec18e8d52d7731af6
|
refs/heads/master
| 2022-07-15T14:36:47.694000 | 2019-08-03T23:11:33 | 2019-08-03T23:11:33 | 209,130,269 | 0 | 0 | null | false | 2022-06-21T01:53:31 | 2019-09-17T18:37:11 | 2019-11-23T14:43:54 | 2022-06-21T01:53:28 | 117 | 0 | 0 | 3 |
Java
| false | false |
package net.thumbtack.onlineshop.service.iface;
import net.thumbtack.onlineshop.entity.User;
import org.springframework.stereotype.Service;
@Service
public interface AccountService {
User getCurrentUserById(Long id);
}
|
UTF-8
|
Java
| 225 |
java
|
AccountService.java
|
Java
|
[] | null |
[] |
package net.thumbtack.onlineshop.service.iface;
import net.thumbtack.onlineshop.entity.User;
import org.springframework.stereotype.Service;
@Service
public interface AccountService {
User getCurrentUserById(Long id);
}
| 225 | 0.817778 | 0.817778 | 9 | 24 | 20 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
13
|
14aec18a91739601b90507e98c6b830955c135cc
| 20,280,835,603,153 |
fbbb62f7f661dd53d663b01476b30fedce695c2e
|
/Sources/Matrix/FXMLDocumentController.java
|
f4e86bc51c60662d91b5af123b90d76d70691e44
|
[] |
no_license
|
Sedrakable/Sedrakable.github.io
|
https://github.com/Sedrakable/Sedrakable.github.io
|
2691bf37c684681ac23b6377a6d81164aaf06464
|
763258b891d7b7d92a831d3b1ead7bdba0e9b731
|
refs/heads/master
| 2021-07-15T06:22:49.261000 | 2021-04-09T13:52:55 | 2021-04-09T13:52:55 | 244,020,226 | 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 matrix;
import java.net.URL;
import java.text.DecimalFormat;
import static java.time.Clock.system;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import static matrix.Matrix.getStage;
/**
*
* @author cstuser
*/
public class FXMLDocumentController implements Initializable {
@FXML
public Label Title;
@FXML
public AnchorPane pane;
@FXML
private Pane pane3 = new Pane();
@FXML
private GridPane gridPane = new GridPane();
@FXML
private ScrollPane scrollPane = new ScrollPane();
@FXML
private ChoiceBox<Integer> RowBox;
@FXML
private ChoiceBox<Integer> ColumbBox;
@FXML
private Label LabelRows;
@FXML
private Label LabelColumbs;
@FXML
private Label ErrorLabel;
@FXML
private Button StartButton;
@FXML
private Button reduce;
@FXML
private Button exitButton;
@FXML
private Button minButton;
@FXML
int NumberRows = 0;
@FXML
int NumberColumbs = 0;
@FXML
int l = 1;
@FXML
int m = 0;
@FXML
int n = 0;
@FXML
int numo = 1;
@FXML
private double[][] numberField = null;
@FXML
private TextField[][] ArrayField = null;
@FXML
private ArrayList<Label> ArrayLabel = new ArrayList<>();
@FXML
private ArrayList<Label> numLabel = new ArrayList<>();
@FXML
private ArrayList<Label> actionLabel = new ArrayList<>();
@FXML
private void numberGetter()
{
numberField = new double[NumberRows][NumberColumbs];
int num = 0;
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
try
{
String boi = ArrayField[i][j].getText();
num = Integer.parseInt(boi);
numberField[i][j] = num;
ErrorLabel.setText("good");
}
catch (Exception e)
{
ErrorLabel.setText("Every block has to be filled or be a number.");
num = 0;
}
}
}
}
@FXML
private void matrixReducer(ActionEvent event)
{
RedReseter();
numberGetter();
paneExpander();
matrixPrint(numberField,l);
l++;
labelMatrixCreator(0,0,"null");
int count = 0;
if(NumberColumbs -1 >= NumberRows)
{
count = NumberRows;
}
if(NumberColumbs -1 < NumberRows)
{
count = NumberColumbs-1;
}
for (int k = 0; k < count; k++)
{
ZeroCheck();
ColumbReducer(k);
ZeroCheck();
TopOne(k);
ZeroCheck();
if(k > 0)
{
ColumbEquilizer(k);
ZeroCheck();
}
AutoReducer(k);
}
ZeroCheck();
CleanUp();
ZeroCheck();
CleanUp2();
matrixPrint(numberField,l);
labelMatrixCreator(0,0,"null");
}
@FXML
private void AutoReducer(int b)
{
for (int i = 0; i < NumberRows; i++) {
if(i != b && numberField[i][b] != 0)
{
RowSub(i,b);
}
}
}
@FXML
private void CleanUp2()
{
double x = 0;
for (int i = 0; i < NumberRows; i++)
{
int num = 0;
for (int j = 0; j < NumberColumbs-1; j++)
{
x = numberField[i][j];
if(x == 0)
{
num++;
}
}
if(num == NumberColumbs-1)
{
RowDiv(i,numberField[i][NumberColumbs-1]);
}
}
}
@FXML
private void ZeroCheck()
{
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
double x = numberField[i][j];
if(x < 0.0000001 && x > -0.0000001)
{
numberField[i][j] = 0;
}
}
}
}
@FXML
private void CleanUp()
{
double x = 0;
int count = 0;
if(NumberColumbs -1 >= NumberRows)
{
count = NumberRows;
}
if(NumberColumbs -1 < NumberRows)
{
count = NumberColumbs-1;
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < NumberRows; j++) {
x = numberField[j][i];
if(x != 0)
{
RowDiv(j,x);
}
}
}
}
@FXML
private void RowSub(int b, int a)
{
System.out.println("Operation(RowSub): " + b + " - " + a);
for (int i = 0; i < NumberColumbs; i++)
{
numberField[b][i] = numberField[b][i] - numberField[a][i] ;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(b,a,"RowSub");
}
@FXML
private void RowMult(int a,double x)
{
System.out.println("Operation(RowMult): " + a + " * x:" + x);
for (int i = 0; i < NumberColumbs; i++)
{
numberField[a][i] = numberField[a][i] * x;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(a,x,"RowMult");
}
@FXML
private void RowDiv(int a,double x)
{
System.out.println("Operation(RowDiv): " + a + " / x:" + x);
for (int i = 0; i < NumberColumbs; i++)
{
numberField[a][i] = numberField[a][i]/x;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(a,x,"RowDiv");
}
@FXML
private void ColumbReducer(int a)
{
System.out.println("Operation(ColumbReducer): I just made sure that Columb " + a + " has only ones and zeros" );
for (int i = a; i < NumberRows; i++)
{
double x = numberField[i][a];
if(x != 0)
{
RowDiv(i, x);
}
}
matrixPrint(numberField,l);
l++;
}
@FXML
private void ColumbEquilizer(int a)
{
System.out.println("Operation(ColumbEquilizer): I just made sure that Columb " + a + " has all the same numbers" );
double num = 0;
int t = 0;
for (int i = a-1; i >= 0; i--) {
if(t == 0)
{
num = numberField[i][a];
}
if(num != 0)
{
t = 1;
}
}
for (int i = 0; i < NumberRows; i++)
{
double x = numberField[i][a];
if(x != 0 && num != 0)
{
double y = num/x;
RowMult(i,y) ;
}
}
matrixPrint(numberField,l);
l++;
}
// AT THE END
@FXML
private boolean RowCheck(int a,int b)
{
System.out.println("Operation(RowCheck): this is to make sure that rows " + a + " and " + b + " have worth while operations" );
boolean boi = false;
int y = 0;
int n = 0;
for (int i = 0; i < NumberColumbs - 1; i++)
{
if(numberField[a][i] == numberField[b][i] && numberField[a][i] != 0 && numberField[b][i] != 0)
{
y++;
}
if(numberField[a][i] != numberField[b][i])
{
n++;
}
}
if(y >= n)
{
boi = true;
}
matrixPrint(numberField,l);
l++;
return boi;
}
@FXML
private void RowSwitcher(int a, int b)
{
System.out.println("Operation(RowSwitcher): this switches rows " + a + " and " + b);
double x = 0;
for (int i = 0; i < NumberColumbs; i++)
{
x = numberField[a][i];
numberField[a][i] = numberField[b][i];
numberField[b][i] = x;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(a,b,"RowSwitcher");
}
@FXML
private void TopOne(int b)
{
System.out.println("Operation(TopOne): this makes sure that in columb " + b + " the 1 is on top");
int num = 0;
int x = 0;
for (int i = b; i < NumberRows; i++)
{
if(numberField[i][b] == 1 && x == 0)
{
x++;
num = i;
}
}
if(x == 1)
{
RowSwitcher(b,num);
}
matrixPrint(numberField,l);
l++;
}
@FXML
private void matrixPrint(double[][] matrix, int l)
{
String print = " " + l + ": " + "\n";
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
double y = matrix[i][j];
String formattedString = String.format("%.02f", y);
if(j == 0)
{
print = print + " [ ";
}
if(j == NumberColumbs - 1)
{
print = print + " | " + formattedString + " ] " + "\n";
}
else
{
print = print + " " + formattedString + " " ;
}
}
}
System.out.println(print);
}
@FXML
private void paneExpander()
{
getStage().setWidth(1600);
pane.getChildren().add(scrollPane);
scrollPane.setPrefSize(800,800);
scrollPane.setLayoutX(800);
scrollPane.setLayoutY(0);
scrollPane.setId("scroll");
scrollPane.setContent(pane3);
scrollPane.setFitToWidth(true);
pane3.setId("pane3");
pane3.setPrefWidth(800);
pane3.setMinHeight(800);
pane3.setLayoutX(800);
pane3.setLayoutY(0);
}
@FXML
private void labelMatrixCreator(int a, double b, String c)
{
Label numero = new Label();
numero.setId("numero");
numero.setText(Integer.toString(numo));
numero.setPrefWidth(40);
numero.setPrefHeight(20);
numero.setLayoutX(20 +(m*62*NumberColumbs));
numero.setLayoutY(16 +(n*45*NumberRows));
pane3.getChildren().add(numero);
Rectangle rectangle = new Rectangle(20+ (45*(NumberColumbs-1)) +(m*62*NumberColumbs), 40+(n*45*NumberRows), 4, (30*NumberRows)-5);
rectangle.setId("rec");
pane3.getChildren().add(rectangle);
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
double x = numberField[i][j];
String y = Double.toString(x);
if(x != 0 && new Fraction(x).getDenominator() != 1)
{
y = new Fraction(x).toString();
if(y.length() > 4)
{
DecimalFormat df2 = new DecimalFormat("#.##");
y = df2.format(x);
}
}
if( x == 0 || new Fraction(x).getDenominator() == 1)
{
int z = (int) x;
y = Integer.toString(z);
}
Label boi = new Label();
boi.setText(y);
boi.setId("labels");
boi.setPrefWidth(40);
boi.setPrefHeight(25);
boi.setMaxHeight(25);
if(j < NumberColumbs-1)
{
boi.setLayoutX(20+ (45*j) +(m*62*NumberColumbs));
}
else
{
boi.setLayoutX(29 + (45*j) +(m*62*NumberColumbs));
}
boi.setLayoutY(40+ (30*i) +(n*45*NumberRows));
Label act = new Label();
act.setId("rowActions");
String mess = "";
if(j == NumberColumbs-1)
{
act.setLayoutX(29+ (45*(j+1)) +(m*62*NumberColumbs));
act.setLayoutY(40+ (30*i) +(n*45*NumberRows));
if(c.equals("RowMult") && i == a)
{
mess = "[R"+(a+1)+"]*"+(int)b;
}
if(c.equals("RowDiv") && i == a)
{
mess ="[R"+(a+1)+"]/"+(int)b;
}
if(c.equals("RowSub") && i == b)
{
mess = "[R"+((int)b+1)+"]-[R"+(a+1)+"]";
}
if(c.equals("RowSwitcher") && i == a)
{
mess = "[R"+(a+1)+"]<->[R"+(int)b +"]";
}
}
act.setText(mess);
pane3.getChildren().add(boi);
pane3.getChildren().add(act);
actionLabel.add(act);
ArrayLabel.add(boi);
numLabel.add(numero);
}
}
m++;
if(m==3 && NumberColumbs <= 4)
{
m = 0;
n++;
}
if(m==2 && NumberColumbs > 4)
{
m = 0;
n++;
}
if(m==1 && NumberColumbs > 6)
{
m = 0;
n++;
}
numo++;
}
@FXML
private void menuCreator()
{
for (int i = 1; i <= 10; i++) {
RowBox.getItems().add(i);
ColumbBox.getItems().add(i);
}
}
@FXML
private void textFieldCreator()
{
try
{
NumberRows = RowBox.getValue();
NumberColumbs = ColumbBox.getValue();
ArrayField = new TextField[NumberRows][NumberColumbs];
//gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.setVgap(5);
gridPane.setHgap(5);
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
TextField boi = new TextField();
boi.setPrefWidth(50);
boi.setPrefHeight(30);
gridPane.add(boi, j, i);
boi.setId("field");
ArrayField[i][j] = boi;
ErrorLabel.setText("Nice");
}
}
gridPane.setLayoutX(((800 - ((50*NumberColumbs)+(5*(NumberColumbs-1))))/2));
gridPane.setTranslateY(200);
pane.getChildren().add(gridPane);
}
catch(Exception e)
{
ErrorLabel.setText("Please put in numbers");
}
}
@FXML
private void RedReseter(){
for (int i = 0; i < ArrayLabel.size(); i++) {
pane3.getChildren().remove(ArrayLabel.get(i));
}
ArrayLabel.clear();
for (int i = 0; i < numLabel.size(); i++) {
pane3.getChildren().remove(numLabel.get(i));
}
numLabel.clear();
for (int i = 0; i < actionLabel.size(); i++) {
pane3.getChildren().remove(actionLabel.get(i));
}
actionLabel.clear();
getStage().setWidth(800);
pane.getChildren().remove(scrollPane);
pane3.getChildren().clear();
l = 1;
m = 0;
n = 0;
numo = 1;
}
@FXML
private void StartReseter()
{
for (int i = 0; i < ArrayLabel.size(); i++) {
pane3.getChildren().remove(ArrayLabel.get(i));
}
ArrayLabel.clear();
for (int i = 0; i < numLabel.size(); i++) {
pane3.getChildren().remove(numLabel.get(i));
}
numLabel.clear();
for (int i = 0; i < actionLabel.size(); i++) {
pane3.getChildren().remove(actionLabel.get(i));
}
actionLabel.clear();
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
pane.getChildren().remove(ArrayField[i][j]);
ArrayField[i][j] = null;
}
}
gridPane.getChildren().clear();
pane.getChildren().remove(gridPane);
getStage().setWidth(800);
pane.getChildren().remove(scrollPane);
pane3.getChildren().clear();
l = 1;
m = 0;
n = 0;
numo = 1;
}
@FXML
private void Start(ActionEvent event)
{
StartReseter();
textFieldCreator();
}
@FXML
private void Exit(ActionEvent event)
{
getStage().close();
}
@FXML
private void Minimise(ActionEvent event)
{
getStage().setIconified(true);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
menuCreator();
reduce.setId("reduce");
reduce.setText("Reduce");
StartButton.setId("start");
StartButton.setText("Start");
RowBox.setId("row_box");
ColumbBox.setId("col_box");
exitButton.setId("exit");
minButton.setId("minimise");
pane.setId("big_pane");
Title.setId("title");
}
}
|
UTF-8
|
Java
| 20,009 |
java
|
FXMLDocumentController.java
|
Java
|
[
{
"context": " static matrix.Matrix.getStage;\n\n/**\n *\n * @author cstuser\n */\npublic class FXMLDocumentController implement",
"end": 1038,
"score": 0.999555766582489,
"start": 1031,
"tag": "USERNAME",
"value": "cstuser"
}
] | 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 matrix;
import java.net.URL;
import java.text.DecimalFormat;
import static java.time.Clock.system;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import static matrix.Matrix.getStage;
/**
*
* @author cstuser
*/
public class FXMLDocumentController implements Initializable {
@FXML
public Label Title;
@FXML
public AnchorPane pane;
@FXML
private Pane pane3 = new Pane();
@FXML
private GridPane gridPane = new GridPane();
@FXML
private ScrollPane scrollPane = new ScrollPane();
@FXML
private ChoiceBox<Integer> RowBox;
@FXML
private ChoiceBox<Integer> ColumbBox;
@FXML
private Label LabelRows;
@FXML
private Label LabelColumbs;
@FXML
private Label ErrorLabel;
@FXML
private Button StartButton;
@FXML
private Button reduce;
@FXML
private Button exitButton;
@FXML
private Button minButton;
@FXML
int NumberRows = 0;
@FXML
int NumberColumbs = 0;
@FXML
int l = 1;
@FXML
int m = 0;
@FXML
int n = 0;
@FXML
int numo = 1;
@FXML
private double[][] numberField = null;
@FXML
private TextField[][] ArrayField = null;
@FXML
private ArrayList<Label> ArrayLabel = new ArrayList<>();
@FXML
private ArrayList<Label> numLabel = new ArrayList<>();
@FXML
private ArrayList<Label> actionLabel = new ArrayList<>();
@FXML
private void numberGetter()
{
numberField = new double[NumberRows][NumberColumbs];
int num = 0;
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
try
{
String boi = ArrayField[i][j].getText();
num = Integer.parseInt(boi);
numberField[i][j] = num;
ErrorLabel.setText("good");
}
catch (Exception e)
{
ErrorLabel.setText("Every block has to be filled or be a number.");
num = 0;
}
}
}
}
@FXML
private void matrixReducer(ActionEvent event)
{
RedReseter();
numberGetter();
paneExpander();
matrixPrint(numberField,l);
l++;
labelMatrixCreator(0,0,"null");
int count = 0;
if(NumberColumbs -1 >= NumberRows)
{
count = NumberRows;
}
if(NumberColumbs -1 < NumberRows)
{
count = NumberColumbs-1;
}
for (int k = 0; k < count; k++)
{
ZeroCheck();
ColumbReducer(k);
ZeroCheck();
TopOne(k);
ZeroCheck();
if(k > 0)
{
ColumbEquilizer(k);
ZeroCheck();
}
AutoReducer(k);
}
ZeroCheck();
CleanUp();
ZeroCheck();
CleanUp2();
matrixPrint(numberField,l);
labelMatrixCreator(0,0,"null");
}
@FXML
private void AutoReducer(int b)
{
for (int i = 0; i < NumberRows; i++) {
if(i != b && numberField[i][b] != 0)
{
RowSub(i,b);
}
}
}
@FXML
private void CleanUp2()
{
double x = 0;
for (int i = 0; i < NumberRows; i++)
{
int num = 0;
for (int j = 0; j < NumberColumbs-1; j++)
{
x = numberField[i][j];
if(x == 0)
{
num++;
}
}
if(num == NumberColumbs-1)
{
RowDiv(i,numberField[i][NumberColumbs-1]);
}
}
}
@FXML
private void ZeroCheck()
{
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
double x = numberField[i][j];
if(x < 0.0000001 && x > -0.0000001)
{
numberField[i][j] = 0;
}
}
}
}
@FXML
private void CleanUp()
{
double x = 0;
int count = 0;
if(NumberColumbs -1 >= NumberRows)
{
count = NumberRows;
}
if(NumberColumbs -1 < NumberRows)
{
count = NumberColumbs-1;
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < NumberRows; j++) {
x = numberField[j][i];
if(x != 0)
{
RowDiv(j,x);
}
}
}
}
@FXML
private void RowSub(int b, int a)
{
System.out.println("Operation(RowSub): " + b + " - " + a);
for (int i = 0; i < NumberColumbs; i++)
{
numberField[b][i] = numberField[b][i] - numberField[a][i] ;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(b,a,"RowSub");
}
@FXML
private void RowMult(int a,double x)
{
System.out.println("Operation(RowMult): " + a + " * x:" + x);
for (int i = 0; i < NumberColumbs; i++)
{
numberField[a][i] = numberField[a][i] * x;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(a,x,"RowMult");
}
@FXML
private void RowDiv(int a,double x)
{
System.out.println("Operation(RowDiv): " + a + " / x:" + x);
for (int i = 0; i < NumberColumbs; i++)
{
numberField[a][i] = numberField[a][i]/x;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(a,x,"RowDiv");
}
@FXML
private void ColumbReducer(int a)
{
System.out.println("Operation(ColumbReducer): I just made sure that Columb " + a + " has only ones and zeros" );
for (int i = a; i < NumberRows; i++)
{
double x = numberField[i][a];
if(x != 0)
{
RowDiv(i, x);
}
}
matrixPrint(numberField,l);
l++;
}
@FXML
private void ColumbEquilizer(int a)
{
System.out.println("Operation(ColumbEquilizer): I just made sure that Columb " + a + " has all the same numbers" );
double num = 0;
int t = 0;
for (int i = a-1; i >= 0; i--) {
if(t == 0)
{
num = numberField[i][a];
}
if(num != 0)
{
t = 1;
}
}
for (int i = 0; i < NumberRows; i++)
{
double x = numberField[i][a];
if(x != 0 && num != 0)
{
double y = num/x;
RowMult(i,y) ;
}
}
matrixPrint(numberField,l);
l++;
}
// AT THE END
@FXML
private boolean RowCheck(int a,int b)
{
System.out.println("Operation(RowCheck): this is to make sure that rows " + a + " and " + b + " have worth while operations" );
boolean boi = false;
int y = 0;
int n = 0;
for (int i = 0; i < NumberColumbs - 1; i++)
{
if(numberField[a][i] == numberField[b][i] && numberField[a][i] != 0 && numberField[b][i] != 0)
{
y++;
}
if(numberField[a][i] != numberField[b][i])
{
n++;
}
}
if(y >= n)
{
boi = true;
}
matrixPrint(numberField,l);
l++;
return boi;
}
@FXML
private void RowSwitcher(int a, int b)
{
System.out.println("Operation(RowSwitcher): this switches rows " + a + " and " + b);
double x = 0;
for (int i = 0; i < NumberColumbs; i++)
{
x = numberField[a][i];
numberField[a][i] = numberField[b][i];
numberField[b][i] = x;
}
matrixPrint(numberField,l);
l++;
labelMatrixCreator(a,b,"RowSwitcher");
}
@FXML
private void TopOne(int b)
{
System.out.println("Operation(TopOne): this makes sure that in columb " + b + " the 1 is on top");
int num = 0;
int x = 0;
for (int i = b; i < NumberRows; i++)
{
if(numberField[i][b] == 1 && x == 0)
{
x++;
num = i;
}
}
if(x == 1)
{
RowSwitcher(b,num);
}
matrixPrint(numberField,l);
l++;
}
@FXML
private void matrixPrint(double[][] matrix, int l)
{
String print = " " + l + ": " + "\n";
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
double y = matrix[i][j];
String formattedString = String.format("%.02f", y);
if(j == 0)
{
print = print + " [ ";
}
if(j == NumberColumbs - 1)
{
print = print + " | " + formattedString + " ] " + "\n";
}
else
{
print = print + " " + formattedString + " " ;
}
}
}
System.out.println(print);
}
@FXML
private void paneExpander()
{
getStage().setWidth(1600);
pane.getChildren().add(scrollPane);
scrollPane.setPrefSize(800,800);
scrollPane.setLayoutX(800);
scrollPane.setLayoutY(0);
scrollPane.setId("scroll");
scrollPane.setContent(pane3);
scrollPane.setFitToWidth(true);
pane3.setId("pane3");
pane3.setPrefWidth(800);
pane3.setMinHeight(800);
pane3.setLayoutX(800);
pane3.setLayoutY(0);
}
@FXML
private void labelMatrixCreator(int a, double b, String c)
{
Label numero = new Label();
numero.setId("numero");
numero.setText(Integer.toString(numo));
numero.setPrefWidth(40);
numero.setPrefHeight(20);
numero.setLayoutX(20 +(m*62*NumberColumbs));
numero.setLayoutY(16 +(n*45*NumberRows));
pane3.getChildren().add(numero);
Rectangle rectangle = new Rectangle(20+ (45*(NumberColumbs-1)) +(m*62*NumberColumbs), 40+(n*45*NumberRows), 4, (30*NumberRows)-5);
rectangle.setId("rec");
pane3.getChildren().add(rectangle);
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
double x = numberField[i][j];
String y = Double.toString(x);
if(x != 0 && new Fraction(x).getDenominator() != 1)
{
y = new Fraction(x).toString();
if(y.length() > 4)
{
DecimalFormat df2 = new DecimalFormat("#.##");
y = df2.format(x);
}
}
if( x == 0 || new Fraction(x).getDenominator() == 1)
{
int z = (int) x;
y = Integer.toString(z);
}
Label boi = new Label();
boi.setText(y);
boi.setId("labels");
boi.setPrefWidth(40);
boi.setPrefHeight(25);
boi.setMaxHeight(25);
if(j < NumberColumbs-1)
{
boi.setLayoutX(20+ (45*j) +(m*62*NumberColumbs));
}
else
{
boi.setLayoutX(29 + (45*j) +(m*62*NumberColumbs));
}
boi.setLayoutY(40+ (30*i) +(n*45*NumberRows));
Label act = new Label();
act.setId("rowActions");
String mess = "";
if(j == NumberColumbs-1)
{
act.setLayoutX(29+ (45*(j+1)) +(m*62*NumberColumbs));
act.setLayoutY(40+ (30*i) +(n*45*NumberRows));
if(c.equals("RowMult") && i == a)
{
mess = "[R"+(a+1)+"]*"+(int)b;
}
if(c.equals("RowDiv") && i == a)
{
mess ="[R"+(a+1)+"]/"+(int)b;
}
if(c.equals("RowSub") && i == b)
{
mess = "[R"+((int)b+1)+"]-[R"+(a+1)+"]";
}
if(c.equals("RowSwitcher") && i == a)
{
mess = "[R"+(a+1)+"]<->[R"+(int)b +"]";
}
}
act.setText(mess);
pane3.getChildren().add(boi);
pane3.getChildren().add(act);
actionLabel.add(act);
ArrayLabel.add(boi);
numLabel.add(numero);
}
}
m++;
if(m==3 && NumberColumbs <= 4)
{
m = 0;
n++;
}
if(m==2 && NumberColumbs > 4)
{
m = 0;
n++;
}
if(m==1 && NumberColumbs > 6)
{
m = 0;
n++;
}
numo++;
}
@FXML
private void menuCreator()
{
for (int i = 1; i <= 10; i++) {
RowBox.getItems().add(i);
ColumbBox.getItems().add(i);
}
}
@FXML
private void textFieldCreator()
{
try
{
NumberRows = RowBox.getValue();
NumberColumbs = ColumbBox.getValue();
ArrayField = new TextField[NumberRows][NumberColumbs];
//gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.setVgap(5);
gridPane.setHgap(5);
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
TextField boi = new TextField();
boi.setPrefWidth(50);
boi.setPrefHeight(30);
gridPane.add(boi, j, i);
boi.setId("field");
ArrayField[i][j] = boi;
ErrorLabel.setText("Nice");
}
}
gridPane.setLayoutX(((800 - ((50*NumberColumbs)+(5*(NumberColumbs-1))))/2));
gridPane.setTranslateY(200);
pane.getChildren().add(gridPane);
}
catch(Exception e)
{
ErrorLabel.setText("Please put in numbers");
}
}
@FXML
private void RedReseter(){
for (int i = 0; i < ArrayLabel.size(); i++) {
pane3.getChildren().remove(ArrayLabel.get(i));
}
ArrayLabel.clear();
for (int i = 0; i < numLabel.size(); i++) {
pane3.getChildren().remove(numLabel.get(i));
}
numLabel.clear();
for (int i = 0; i < actionLabel.size(); i++) {
pane3.getChildren().remove(actionLabel.get(i));
}
actionLabel.clear();
getStage().setWidth(800);
pane.getChildren().remove(scrollPane);
pane3.getChildren().clear();
l = 1;
m = 0;
n = 0;
numo = 1;
}
@FXML
private void StartReseter()
{
for (int i = 0; i < ArrayLabel.size(); i++) {
pane3.getChildren().remove(ArrayLabel.get(i));
}
ArrayLabel.clear();
for (int i = 0; i < numLabel.size(); i++) {
pane3.getChildren().remove(numLabel.get(i));
}
numLabel.clear();
for (int i = 0; i < actionLabel.size(); i++) {
pane3.getChildren().remove(actionLabel.get(i));
}
actionLabel.clear();
for (int i = 0; i < NumberRows; i++)
{
for (int j = 0; j < NumberColumbs; j++)
{
pane.getChildren().remove(ArrayField[i][j]);
ArrayField[i][j] = null;
}
}
gridPane.getChildren().clear();
pane.getChildren().remove(gridPane);
getStage().setWidth(800);
pane.getChildren().remove(scrollPane);
pane3.getChildren().clear();
l = 1;
m = 0;
n = 0;
numo = 1;
}
@FXML
private void Start(ActionEvent event)
{
StartReseter();
textFieldCreator();
}
@FXML
private void Exit(ActionEvent event)
{
getStage().close();
}
@FXML
private void Minimise(ActionEvent event)
{
getStage().setIconified(true);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
menuCreator();
reduce.setId("reduce");
reduce.setText("Reduce");
StartButton.setId("start");
StartButton.setText("Start");
RowBox.setId("row_box");
ColumbBox.setId("col_box");
exitButton.setId("exit");
minButton.setId("minimise");
pane.setId("big_pane");
Title.setId("title");
}
}
| 20,009 | 0.407667 | 0.393773 | 798 | 24.073935 | 20.134031 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508772 | false | false |
13
|
50b9e7ab61503028771c8b7943a76b60fca0b84e
| 20,280,835,604,254 |
c4273aaaa297da3043b9adf03c1cd79cd4ec5b69
|
/src/main/java/com/krinroman/parse/avito/data/AvitoObjectApartment.java
|
5c4b8f735de913242cf62daf6054906cbd4b6f3b
|
[] |
no_license
|
krinroman/AvitoParser
|
https://github.com/krinroman/AvitoParser
|
13aecdb752583d6b804565de2aea99445e7e7dec
|
096cdffd1b5e3f28c799a3cb3b655a63b2f4da81
|
refs/heads/master
| 2022-09-21T07:56:41.272000 | 2019-12-22T12:24:35 | 2019-12-22T12:24:35 | 229,561,205 | 2 | 1 | null | false | 2022-09-08T01:05:16 | 2019-12-22T12:03:44 | 2020-04-13T18:28:36 | 2022-09-08T01:05:13 | 17 | 0 | 1 | 4 |
Java
| false | false |
package com.krinroman.parse.avito.data;
import com.krinroman.parse.avito.core.MyConnection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class AvitoObjectApartment {
private long id;
private String url;
private String title;
private int price;
private String description;
private String address;
private int floor;
private int floorInHome;
private int rooms;
private List<String> urlImages;
public AvitoObjectApartment(long id, String url) throws IOException {
this.id = id;
this.url = url;
description = null;
address = null;
floor = -1;
floorInHome = -1;
rooms = -1;
urlImages = new ArrayList<>();
Document doc = MyConnection.getDocument(url);
Elements paramElements;
title = doc.select("span.title-info-title-text").get(0).text();
price = Integer.parseInt(doc.select("span.js-item-price").get(0).text().replace(" ", ""));
paramElements = doc.select("div.item-description-text");
if(!paramElements.isEmpty()) description = paramElements.get(0).text();
paramElements = doc.select("span.item-address__string");
if(!paramElements.isEmpty()) address = paramElements.get(0).text();
Elements elementsImgUrl = doc.select("div.gallery-img-frame.js-gallery-img-frame");
for(Element elementImgUrl : elementsImgUrl){
urlImages.add("https:" + elementImgUrl.attr("data-url"));
}
paramElements = doc.select("li.item-params-list-item");
for(Element elementParam: paramElements){
switch(elementParam.text().split(":")[0]){
case("Этаж"):{
floor = Integer.parseInt(elementParam.text().split(" ")[1].trim());
}break;
case("Этажей в доме"):{
String [] args = elementParam.text().split(" ");
floorInHome = Integer.parseInt(args[args.length-1].trim());
}break;
case("Количество комнат"):{
String [] args = elementParam.text().split(" ");
switch(args[args.length-1].trim()){
case("студии"): rooms = 0; break;
case("1-комнатные"): rooms = 1; break;
case("2-комнатные"): rooms = 2; break;
case("3-комнатные"): rooms = 3; break;
case("4-комнатные"): rooms = 4; break;
case("5-комнатные"): rooms = 5; break;
case("6-комнатные"): rooms = 6; break;
case("7-комнатные"): rooms = 7; break;
}
}
}
}
}
public AvitoObjectApartment(long id, String url, String title, int price, String description, String address, int floor, int floorInHome, int rooms, List<String> urlImages) {
this.id = id;
this.url = url;
this.title = title;
this.price = price;
this.description = description;
this.address = address;
this.floor = floor;
this.floorInHome = floorInHome;
this.rooms = rooms;
this.urlImages = urlImages;
}
public long getId() {
return id;
}
public String getUrl() {
return url;
}
public String getTitle() {
return title;
}
public int getPrice() {
return price;
}
public String getDescription() {
return description;
}
public String getAddress() {
return address;
}
public int getFloor() {
return floor;
}
public int getFloorInHome() {
return floorInHome;
}
public int getRooms() {
return rooms;
}
public List<String> getUrlImages() {
return urlImages;
}
@Override
public String toString() {
return id + ": " + url;
}
}
|
UTF-8
|
Java
| 4,183 |
java
|
AvitoObjectApartment.java
|
Java
|
[] | null |
[] |
package com.krinroman.parse.avito.data;
import com.krinroman.parse.avito.core.MyConnection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class AvitoObjectApartment {
private long id;
private String url;
private String title;
private int price;
private String description;
private String address;
private int floor;
private int floorInHome;
private int rooms;
private List<String> urlImages;
public AvitoObjectApartment(long id, String url) throws IOException {
this.id = id;
this.url = url;
description = null;
address = null;
floor = -1;
floorInHome = -1;
rooms = -1;
urlImages = new ArrayList<>();
Document doc = MyConnection.getDocument(url);
Elements paramElements;
title = doc.select("span.title-info-title-text").get(0).text();
price = Integer.parseInt(doc.select("span.js-item-price").get(0).text().replace(" ", ""));
paramElements = doc.select("div.item-description-text");
if(!paramElements.isEmpty()) description = paramElements.get(0).text();
paramElements = doc.select("span.item-address__string");
if(!paramElements.isEmpty()) address = paramElements.get(0).text();
Elements elementsImgUrl = doc.select("div.gallery-img-frame.js-gallery-img-frame");
for(Element elementImgUrl : elementsImgUrl){
urlImages.add("https:" + elementImgUrl.attr("data-url"));
}
paramElements = doc.select("li.item-params-list-item");
for(Element elementParam: paramElements){
switch(elementParam.text().split(":")[0]){
case("Этаж"):{
floor = Integer.parseInt(elementParam.text().split(" ")[1].trim());
}break;
case("Этажей в доме"):{
String [] args = elementParam.text().split(" ");
floorInHome = Integer.parseInt(args[args.length-1].trim());
}break;
case("Количество комнат"):{
String [] args = elementParam.text().split(" ");
switch(args[args.length-1].trim()){
case("студии"): rooms = 0; break;
case("1-комнатные"): rooms = 1; break;
case("2-комнатные"): rooms = 2; break;
case("3-комнатные"): rooms = 3; break;
case("4-комнатные"): rooms = 4; break;
case("5-комнатные"): rooms = 5; break;
case("6-комнатные"): rooms = 6; break;
case("7-комнатные"): rooms = 7; break;
}
}
}
}
}
public AvitoObjectApartment(long id, String url, String title, int price, String description, String address, int floor, int floorInHome, int rooms, List<String> urlImages) {
this.id = id;
this.url = url;
this.title = title;
this.price = price;
this.description = description;
this.address = address;
this.floor = floor;
this.floorInHome = floorInHome;
this.rooms = rooms;
this.urlImages = urlImages;
}
public long getId() {
return id;
}
public String getUrl() {
return url;
}
public String getTitle() {
return title;
}
public int getPrice() {
return price;
}
public String getDescription() {
return description;
}
public String getAddress() {
return address;
}
public int getFloor() {
return floor;
}
public int getFloorInHome() {
return floorInHome;
}
public int getRooms() {
return rooms;
}
public List<String> getUrlImages() {
return urlImages;
}
@Override
public String toString() {
return id + ": " + url;
}
}
| 4,183 | 0.558658 | 0.55229 | 133 | 29.699247 | 26.579144 | 178 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false |
13
|
a5e03df1552dbe9be50b2e245a018f376cb750c5
| 21,088,289,492,469 |
933b54ea3608b7f4cbca06a44d97f1df7ce551ba
|
/src/de/upb/ddi/lejos/util/ButtonUtils.java
|
8f30a44d1842bb4ac3654f245e4c27ea0633afca
|
[
"MIT"
] |
permissive
|
jneug/upb.LeJOS
|
https://github.com/jneug/upb.LeJOS
|
778846158feb588171b7d45edd834b77df7885c9
|
c4f6950f4f3bafcf53ff1b0b0e0c3d3dd340c0a5
|
refs/heads/master
| 2020-04-14T23:43:14.902000 | 2014-02-26T13:00:03 | 2014-02-26T13:00:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.upb.ddi.lejos.util;
import lejos.nxt.Button;
import lejos.nxt.ButtonListener;
import lejos.util.Delay;
/**
* Hilfsklasse zum Einrichten von Abbruch Buttons.
*
* @author Zoe Werth <zwerth@it.cargotech.com>
*/
public class ButtonUtils {
/**
* Privater Konstruktor.
*/
private ButtonUtils() {
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der {@link Button#ESCAPE Escape-Button} eine Sekunde gedrückt
* gehalten wurde.
*/
public static void addExitListener() {
addExitListener(Button.ESCAPE, 1000);
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der gewählte Button eine Sekunde gedrückt gehalten wurde.
*
* @param btn Button der zum Abbruch dienen soll.
*/
public static void addExitListener( Button btn ) {
addExitListener(btn, 1000);
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der {@link Button#ESCAPE Escape-Button} die festgelegte Zeit
* gedrückt gehalten wurde.
*
* @param timeout Zeit bis beenden in Millisekunden.
*/
public static void addExitListener( int timeout ) {
addExitListener(Button.ESCAPE, timeout);
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der gewählte Button die festgelegte Zeit gedrückt gehalten wurde.
*
* @param btn Button der zum Abbruch dienen soll.
* @param t Zeit bis beenden in Millisekunden.
*/
public static void addExitListener( Button btn, final int t ) {
// Einrichten des Buttons über einen anonymen ButtonListener
btn.addButtonListener(new ButtonListener() {
/**
* Timeout bis beenden des Programms
*/
private int timeout = t;
public void buttonPressed( Button b ) {
// Falls ein Timeout eingestellt wurde wird nach Ablauf der
// Button erneut geprüft und dann ggf beendet.
if( timeout > 0 ) {
Delay.msDelay(timeout);
if( b.isDown() ) {
this.exit();
}
}
}
public void buttonReleased( Button b ) {
// Falls kein Timeout eingestellt wurde wird beendet, sobald der
// Button losgelassen wird.
if( timeout == 0 ) {
this.exit();
}
}
/**
* Beendet das Programm.
*/
private void exit() {
System.exit(1);
}
});
}
}
|
UTF-8
|
Java
| 2,324 |
java
|
ButtonUtils.java
|
Java
|
[
{
"context": "zum Einrichten von Abbruch Buttons.\n * \n * @author Zoe Werth <zwerth@it.cargotech.com>\n */\npublic class Button",
"end": 196,
"score": 0.9998666644096375,
"start": 187,
"tag": "NAME",
"value": "Zoe Werth"
},
{
"context": "en von Abbruch Buttons.\n * \n * @author Zoe Werth <zwerth@it.cargotech.com>\n */\npublic class ButtonUtils {\n\n\t/**\n\t * Private",
"end": 221,
"score": 0.9999325275421143,
"start": 198,
"tag": "EMAIL",
"value": "zwerth@it.cargotech.com"
}
] | null |
[] |
package de.upb.ddi.lejos.util;
import lejos.nxt.Button;
import lejos.nxt.ButtonListener;
import lejos.util.Delay;
/**
* Hilfsklasse zum Einrichten von Abbruch Buttons.
*
* @author <NAME> <<EMAIL>>
*/
public class ButtonUtils {
/**
* Privater Konstruktor.
*/
private ButtonUtils() {
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der {@link Button#ESCAPE Escape-Button} eine Sekunde gedrückt
* gehalten wurde.
*/
public static void addExitListener() {
addExitListener(Button.ESCAPE, 1000);
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der gewählte Button eine Sekunde gedrückt gehalten wurde.
*
* @param btn Button der zum Abbruch dienen soll.
*/
public static void addExitListener( Button btn ) {
addExitListener(btn, 1000);
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der {@link Button#ESCAPE Escape-Button} die festgelegte Zeit
* gedrückt gehalten wurde.
*
* @param timeout Zeit bis beenden in Millisekunden.
*/
public static void addExitListener( int timeout ) {
addExitListener(Button.ESCAPE, timeout);
}
/**
* Einrichten eines Abbruch-Buttons. Ein Beenden des Programms erfolgt
* nachdem der gewählte Button die festgelegte Zeit gedrückt gehalten wurde.
*
* @param btn Button der zum Abbruch dienen soll.
* @param t Zeit bis beenden in Millisekunden.
*/
public static void addExitListener( Button btn, final int t ) {
// Einrichten des Buttons über einen anonymen ButtonListener
btn.addButtonListener(new ButtonListener() {
/**
* Timeout bis beenden des Programms
*/
private int timeout = t;
public void buttonPressed( Button b ) {
// Falls ein Timeout eingestellt wurde wird nach Ablauf der
// Button erneut geprüft und dann ggf beendet.
if( timeout > 0 ) {
Delay.msDelay(timeout);
if( b.isDown() ) {
this.exit();
}
}
}
public void buttonReleased( Button b ) {
// Falls kein Timeout eingestellt wurde wird beendet, sobald der
// Button losgelassen wird.
if( timeout == 0 ) {
this.exit();
}
}
/**
* Beendet das Programm.
*/
private void exit() {
System.exit(1);
}
});
}
}
| 2,305 | 0.683506 | 0.678756 | 94 | 23.638298 | 23.913786 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.797872 | false | false |
13
|
6f3835323a7dcaaf1464dcf1055dbb0dfcf8b819
| 20,091,857,068,863 |
467534fd677a46c5e77bcaf24518a6b5b4456f09
|
/app/src/main/java/com/beaumont/chrisj/bc_solodualcontrols/Constants.java
|
cf95fae2debdd1ba1c7cc3fceb3c372c3e1df99f
|
[] |
no_license
|
ChrisJLester/BC-SoloDualControls
|
https://github.com/ChrisJLester/BC-SoloDualControls
|
4a6026fe2504f1aa74dcac6a09ee5873174ebf51
|
a3b75c386f8a7238711eaa25f118d47cda5d4b55
|
refs/heads/master
| 2021-01-10T18:36:57.326000 | 2016-05-23T20:17:39 | 2016-05-23T20:17:39 | 56,686,659 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.beaumont.chrisj.bc_solodualcontrols;
/**
* Created by ChrisJ on 26/04/2016.
*/
public interface Constants {
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public static final int MESSAGE_STATE_CHANGE = 4;
public static final int MESSAGE_READ = 5;
public static final int MESSAGE_WRITE = 6;
public static final int MESSAGE_DEVICE_NAME = 7;
public static final int MESSAGE_TOAST = 8;
}
|
UTF-8
|
Java
| 562 |
java
|
Constants.java
|
Java
|
[
{
"context": "ont.chrisj.bc_solodualcontrols;\n\n/**\n * Created by ChrisJ on 26/04/2016.\n */\npublic interface Constants {\n ",
"end": 74,
"score": 0.8981131315231323,
"start": 68,
"tag": "USERNAME",
"value": "ChrisJ"
}
] | null |
[] |
package com.beaumont.chrisj.bc_solodualcontrols;
/**
* Created by ChrisJ on 26/04/2016.
*/
public interface Constants {
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
public static final int MESSAGE_STATE_CHANGE = 4;
public static final int MESSAGE_READ = 5;
public static final int MESSAGE_WRITE = 6;
public static final int MESSAGE_DEVICE_NAME = 7;
public static final int MESSAGE_TOAST = 8;
}
| 562 | 0.709964 | 0.679715 | 17 | 32.058823 | 20.592604 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false |
13
|
9f84b0e6c079299d04e76864e5508c5819ead9ba
| 35,081,292,895,247 |
3225eb6938302f7968aef39bd2feeb2202d7a7a6
|
/src/main/java/minigame/plugin/contest/backend/database/MySQL.java
|
7277f1756eb58decdd5b0711e269593113eb461a
|
[] |
no_license
|
xX1bumblebee1Xx/Racing-Minigame
|
https://github.com/xX1bumblebee1Xx/Racing-Minigame
|
48ced960140ce727915273015434cf4a53ea03fa
|
b6fea62a90f133d7f2497b93ae354827992ba065
|
refs/heads/master
| 2020-06-24T08:52:02.545000 | 2017-07-16T19:00:48 | 2017-07-16T19:00:48 | 96,928,761 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package minigame.plugin.contest.backend.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Created by Vengeancey on 12.7.2017..
*/
public class MySQL extends Database
{
private final String host;
private final int port;
private final String username;
private final String password;
private final String database;
private final String driver = "com.mysql.jdbc.Driver";
public MySQL(String host, int port, String username, String password, String database)
{
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.database = database;
}
@Override
public Connection openConnection()
{
try
{
if (checkConnection())
return connection;
final String URL = "jdbc:mysql://%s:%d/%s"; //host, port, database
Class.forName(this.driver);
connection = DriverManager.getConnection(String.format(URL, this.host, this.port, this.database), this.username, this.password);
return connection;
} catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
}
|
UTF-8
|
Java
| 1,296 |
java
|
MySQL.java
|
Java
|
[
{
"context": ";\nimport java.sql.SQLException;\n\n/**\n * Created by Vengeancey on 12.7.2017..\n */\npublic class MySQL extends Dat",
"end": 169,
"score": 0.9991829991340637,
"start": 159,
"tag": "USERNAME",
"value": "Vengeancey"
},
{
"context": "\n this.port = port;\n this.username = username;\n this.password = password;\n this.d",
"end": 633,
"score": 0.9912027716636658,
"start": 625,
"tag": "USERNAME",
"value": "username"
},
{
"context": " this.username = username;\n this.password = password;\n this.database = database;\n }\n\n @Ov",
"end": 667,
"score": 0.9993866682052612,
"start": 659,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package minigame.plugin.contest.backend.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Created by Vengeancey on 12.7.2017..
*/
public class MySQL extends Database
{
private final String host;
private final int port;
private final String username;
private final String password;
private final String database;
private final String driver = "com.mysql.jdbc.Driver";
public MySQL(String host, int port, String username, String password, String database)
{
this.host = host;
this.port = port;
this.username = username;
this.password = <PASSWORD>;
this.database = database;
}
@Override
public Connection openConnection()
{
try
{
if (checkConnection())
return connection;
final String URL = "jdbc:mysql://%s:%d/%s"; //host, port, database
Class.forName(this.driver);
connection = DriverManager.getConnection(String.format(URL, this.host, this.port, this.database), this.username, this.password);
return connection;
} catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
}
| 1,298 | 0.628086 | 0.622685 | 47 | 26.595745 | 26.422636 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723404 | false | false |
13
|
fc4f8a911154c20f96636a61a520fd789999937e
| 5,076,651,392,276 |
dc4ca18155c0fb6436891f62bc92e68e9b5d0ef9
|
/app/src/main/java/com/mooviest/ui/tasks/InitialValuesInterface.java
|
27214672d59d0a215365f5a5d54e91cd280d536e
|
[] |
no_license
|
JoseAntpr/mooviest_android
|
https://github.com/JoseAntpr/mooviest_android
|
3fcc865646c2c74683d39703b9c7eb1dc0fcb82d
|
337ae9feaa6370f7fe6cb3641856bcba77797e0c
|
refs/heads/master
| 2021-01-19T05:33:42.768000 | 2016-11-30T11:34:38 | 2016-11-30T11:34:38 | 63,253,892 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mooviest.ui.tasks;
import com.mooviest.ui.rest.responses.MooviestApiResult;
/**
* Created by jesus on 25/10/16.
*/
public interface InitialValuesInterface {
public void swipeResponse(MooviestApiResult mooviestApiResult);
public void listsResponse(String list_name, MooviestApiResult mooviestApiResult);
}
|
UTF-8
|
Java
| 333 |
java
|
InitialValuesInterface.java
|
Java
|
[
{
"context": "st.responses.MooviestApiResult;\n\n/**\n * Created by jesus on 25/10/16.\n */\n\npublic interface InitialValuesI",
"end": 113,
"score": 0.9992669224739075,
"start": 108,
"tag": "USERNAME",
"value": "jesus"
}
] | null |
[] |
package com.mooviest.ui.tasks;
import com.mooviest.ui.rest.responses.MooviestApiResult;
/**
* Created by jesus on 25/10/16.
*/
public interface InitialValuesInterface {
public void swipeResponse(MooviestApiResult mooviestApiResult);
public void listsResponse(String list_name, MooviestApiResult mooviestApiResult);
}
| 333 | 0.783784 | 0.765766 | 15 | 21.200001 | 27.967123 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
13
|
d788156901d243a116df5e21003bfdcb76da365f
| 35,966,056,163,949 |
83b0f3e374c83a3bdc3e064a4c880121c25fd551
|
/WarehouseTerminal.java
|
930a546a7cb8ca830dc28742c18dcd05946aa636
|
[] |
no_license
|
aaronParkinson1/invManagement
|
https://github.com/aaronParkinson1/invManagement
|
e5da6426f0e5a979f7fca7bdb143d6d6092a2c88
|
8b3150bb5fae7be8aa64fecc360a68c32b654fa4
|
refs/heads/main
| 2023-02-13T11:30:34.791000 | 2021-01-14T12:42:03 | 2021-01-14T12:42:03 | 329,610,632 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package EmailGen;
import java.util.Scanner;
public class WarehouseTerminal {
public static void main(String[] args) {
// variables to control menu
Scanner sc = new Scanner(System.in);
int choice = 0;
boolean exit = false;
// Create a warehouse on launch
StockLocation warehouse = new StockLocation("Warehouse");
// menu loop until exit
do {
System.out.println("Stock management System. Please select an option:");
System.out.println("1. Add product");
System.out.println("2. Process sale");
System.out.println("3. Stock count");
System.out.println("4. Print transaction log");
System.out.println("4. Exit");
if (sc.hasNextInt()) {
choice = sc.nextInt();
} else {
System.out.println("Sorry, couldn't understand you!");
}
if (choice > 0 && choice< 6){
switch (choice) {
case 1:
String name;
int prodID;
int quantity;
double price;
System.out.println("Enter new product name:");
sc.nextLine();
name = sc.nextLine();
System.out.println("Enter product ID:");
prodID = sc.nextInt();
System.out.println("Enter opening stock:");
quantity = sc.nextInt();
System.out.println("Enter price per unit:");
price = sc.nextDouble();
Product newProd = new Product(name, prodID, quantity, price);
warehouse.addProduct(newProd, quantity);
break;
case 2:
System.out.println("Enter product ID:");
prodID = sc.nextInt();
System.out.println("Enter sale quantity:");
quantity = sc.nextInt();
warehouse.processSale(prodID, quantity);
break;
case 3:
System.out.println("Enter product ID:");
prodID = sc.nextInt();
System.out.println("Enter count:");
quantity = sc.nextInt();
warehouse.stockCount(prodID, quantity);
break;
case 4:
System.out.println("Enter product ID:");
prodID = sc.nextInt();
warehouse.printTransactionLog(prodID);
break;
case 5:
exit = true;
break;
}
} else System.out.println("Invalid selection");
} while (!exit);
}
}
|
UTF-8
|
Java
| 3,097 |
java
|
WarehouseTerminal.java
|
Java
|
[] | null |
[] |
package EmailGen;
import java.util.Scanner;
public class WarehouseTerminal {
public static void main(String[] args) {
// variables to control menu
Scanner sc = new Scanner(System.in);
int choice = 0;
boolean exit = false;
// Create a warehouse on launch
StockLocation warehouse = new StockLocation("Warehouse");
// menu loop until exit
do {
System.out.println("Stock management System. Please select an option:");
System.out.println("1. Add product");
System.out.println("2. Process sale");
System.out.println("3. Stock count");
System.out.println("4. Print transaction log");
System.out.println("4. Exit");
if (sc.hasNextInt()) {
choice = sc.nextInt();
} else {
System.out.println("Sorry, couldn't understand you!");
}
if (choice > 0 && choice< 6){
switch (choice) {
case 1:
String name;
int prodID;
int quantity;
double price;
System.out.println("Enter new product name:");
sc.nextLine();
name = sc.nextLine();
System.out.println("Enter product ID:");
prodID = sc.nextInt();
System.out.println("Enter opening stock:");
quantity = sc.nextInt();
System.out.println("Enter price per unit:");
price = sc.nextDouble();
Product newProd = new Product(name, prodID, quantity, price);
warehouse.addProduct(newProd, quantity);
break;
case 2:
System.out.println("Enter product ID:");
prodID = sc.nextInt();
System.out.println("Enter sale quantity:");
quantity = sc.nextInt();
warehouse.processSale(prodID, quantity);
break;
case 3:
System.out.println("Enter product ID:");
prodID = sc.nextInt();
System.out.println("Enter count:");
quantity = sc.nextInt();
warehouse.stockCount(prodID, quantity);
break;
case 4:
System.out.println("Enter product ID:");
prodID = sc.nextInt();
warehouse.printTransactionLog(prodID);
break;
case 5:
exit = true;
break;
}
} else System.out.println("Invalid selection");
} while (!exit);
}
}
| 3,097 | 0.424604 | 0.420407 | 81 | 36.23457 | 22.563639 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703704 | false | false |
13
|
6c976e4c7da73c48313e3f7ec6c5a219025764c6
| 37,486,474,564,238 |
5dc699290c6deb67907a20929d14e0c5310bebbc
|
/baselibrary/src/main/java/com/minlu/baselibrary/http/OkHttpManger.java
|
a4a353e1187f3838a06fc2ffa83841b810c4863b
|
[] |
no_license
|
sfgjys/Office_System
|
https://github.com/sfgjys/Office_System
|
6f5272e701424712163c5bced0d7844f02a5378e
|
37c64bce6a70b2a8522ba9a94ab5547fbb4c683b
|
refs/heads/master
| 2021-01-18T06:21:14.622000 | 2017-05-31T01:58:39 | 2017-05-31T01:58:39 | 84,282,610 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.minlu.baselibrary.http;
import okhttp3.OkHttpClient;
/**
* Created by user on 2016/7/25.
*/
public class OkHttpManger {
private static OkHttpManger okHttpManger;
private OkHttpClient okHttpClient;
private OkHttpManger() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient().newBuilder().cookieJar(new CookiesManager()).build();
}
}
/**
* 获取本类的单例对象
*/
public static OkHttpManger getInstance() {
if (okHttpManger == null) { //线程1,线程2
synchronized (OkHttpManger.class) {
if (okHttpManger == null) {
okHttpManger = new OkHttpManger();
}
}
}
return okHttpManger;
}
public OkHttpClient getOkHttpClient() {
return okHttpClient;
}
}
|
UTF-8
|
Java
| 867 |
java
|
OkHttpManger.java
|
Java
|
[
{
"context": ";\n\nimport okhttp3.OkHttpClient;\n\n/**\n * Created by user on 2016/7/25.\n */\npublic class OkHttpManger {\n\n ",
"end": 89,
"score": 0.6966590285301208,
"start": 85,
"tag": "USERNAME",
"value": "user"
}
] | null |
[] |
package com.minlu.baselibrary.http;
import okhttp3.OkHttpClient;
/**
* Created by user on 2016/7/25.
*/
public class OkHttpManger {
private static OkHttpManger okHttpManger;
private OkHttpClient okHttpClient;
private OkHttpManger() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient().newBuilder().cookieJar(new CookiesManager()).build();
}
}
/**
* 获取本类的单例对象
*/
public static OkHttpManger getInstance() {
if (okHttpManger == null) { //线程1,线程2
synchronized (OkHttpManger.class) {
if (okHttpManger == null) {
okHttpManger = new OkHttpManger();
}
}
}
return okHttpManger;
}
public OkHttpClient getOkHttpClient() {
return okHttpClient;
}
}
| 867 | 0.576877 | 0.564958 | 38 | 21.078947 | 21.616735 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | false | false |
13
|
e69e975dfabac1ea33a7238e8f5798309917f40d
| 36,189,394,467,356 |
898577e8b616e61016326e0896fc5c85c3fefe44
|
/src/main/java/br/com/domainconsult/apir/swagger/SwaggerConfig.java
|
4fd96a426c03bc8d87967263528c43f42273d32f
|
[] |
no_license
|
caduarruda/piloto-sb
|
https://github.com/caduarruda/piloto-sb
|
227ec59e5b8c12d100b57f7f09c7bfc2a75bc776
|
c4155a9453314133fcc2f48c93d6a6dbfef22612
|
refs/heads/master
| 2020-03-28T11:47:15.333000 | 2018-09-20T17:41:04 | 2018-09-20T17:41:04 | 148,246,792 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.domainconsult.apir.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import br.com.domainconsult.apir.components.Messages;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
Messages messages;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("br.com.domainconsult")).paths(PathSelectors.any()).build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(messages.get("swagger.titulo"))
.description(messages.get("swagger.descricao"))
.version(messages.get("swagger.versao"))
.build();
}
}
|
UTF-8
|
Java
| 1,260 |
java
|
SwaggerConfig.java
|
Java
|
[] | null |
[] |
package br.com.domainconsult.apir.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import br.com.domainconsult.apir.components.Messages;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
Messages messages;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("br.com.domainconsult")).paths(PathSelectors.any()).build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(messages.get("swagger.titulo"))
.description(messages.get("swagger.descricao"))
.version(messages.get("swagger.versao"))
.build();
}
}
| 1,260 | 0.776984 | 0.77381 | 37 | 33.054054 | 26.165735 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.837838 | false | false |
13
|
b50f312a8f83657e3f9e0a016e572b00c2773c5b
| 36,017,595,773,292 |
5c60f6d75e5ab2d2d85873384826ccda8b74e8eb
|
/src/main/java/kz/reserve/backend/payload/request/CategoryRequest.java
|
5e28df66bc3a41758731d0319172a7858fd7f8f8
|
[] |
no_license
|
QazaqTitans/backend-project
|
https://github.com/QazaqTitans/backend-project
|
d8b71d6159c7db5c7725084c9b082384dc5b15a5
|
da3539b4b00004cfb3285492c5ab569c3faf3330
|
refs/heads/main
| 2023-04-30T14:00:04.818000 | 2021-05-23T13:20:17 | 2021-05-23T13:20:17 | 339,128,671 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kz.reserve.backend.payload.request;
import kz.reserve.backend.domain.Category;
import javax.validation.constraints.NotBlank;
public class CategoryRequest {
@NotBlank
private String name;
private Long parentCategory;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentCategory() {
return parentCategory;
}
public void setParentCategory(Long parentCategory) {
this.parentCategory = parentCategory;
}
}
|
UTF-8
|
Java
| 557 |
java
|
CategoryRequest.java
|
Java
|
[] | null |
[] |
package kz.reserve.backend.payload.request;
import kz.reserve.backend.domain.Category;
import javax.validation.constraints.NotBlank;
public class CategoryRequest {
@NotBlank
private String name;
private Long parentCategory;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentCategory() {
return parentCategory;
}
public void setParentCategory(Long parentCategory) {
this.parentCategory = parentCategory;
}
}
| 557 | 0.684022 | 0.684022 | 28 | 18.928572 | 18.043457 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false |
13
|
bd2bfc8ff832bc746aba06108bd5c0429561fc39
| 20,658,792,753,766 |
511fb6f291397248aacabd872e54f8b2779cbbb8
|
/app/src/main/java/com/koalafield/cmart/db/dao/Column.java
|
8dfed562fa6134e87990d09ab0c27b1eb4a0743f
|
[] |
no_license
|
jiangrenming/KoalaMart
|
https://github.com/jiangrenming/KoalaMart
|
fd318cf5fdf7f207618aaca1c69ae61f33bee6fc
|
463c45ba50777c70d77bf1712354b700132a5d40
|
refs/heads/master
| 2020-03-16T15:23:23.034000 | 2018-07-31T07:31:18 | 2018-07-31T07:31:18 | 132,741,568 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.koalafield.cmart.db.dao;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface Column {
String name() default "";
boolean primaryKey() default false;
int len() default 10;
boolean unique() default false;
}
|
UTF-8
|
Java
| 489 |
java
|
Column.java
|
Java
|
[] | null |
[] |
package com.koalafield.cmart.db.dao;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface Column {
String name() default "";
boolean primaryKey() default false;
int len() default 10;
boolean unique() default false;
}
| 489 | 0.773006 | 0.768916 | 22 | 21.227272 | 19.605036 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.863636 | false | false |
13
|
b488e1903e5c351a5adf74fa61674b35b9d8d826
| 18,554,258,775,595 |
61d0ab8c9eb280994b76be6a09568d59a4d40190
|
/src/Find_the_Duplicate_Number_p287_sol1.java
|
4062fc570661364b5d10979b59be773b992a28c0
|
[] |
no_license
|
arnabs542/LeetCode_Round_4
|
https://github.com/arnabs542/LeetCode_Round_4
|
5f69e2ca6a693896a0ac11ea0faae2631ddc0dc5
|
8c351251a3cb17c3f8bb59447f37ced3ad6806dc
|
refs/heads/master
| 2022-03-17T13:13:26.053000 | 2016-07-10T09:00:44 | 2016-07-10T09:00:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
prove that at least one duplicate element must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only constant extra space.
Your runtime complexity should be less than O(n2).
*/
/**
* Binary Search solution
*
* First of all we need to realize that the input allow has one duplicate number and it can appear multiple times
*
* The problem also limits the value range is from 1 to n (both inclusive), and input has len n + 1
* So we can make use of index from 1 to n (both inclusive) to find the target value
* Notice that index 0 can be the mid but we will never stop at it. If input size < 2, then we do not have solutions
*
* In this solution, we will use binary search on our index, each binary search will scan all inputs and count how
* many nums <= mid. Say we are looking at index 3, then we at most would have 1,2,3, three numbers smaller than it.
* If not, then it means one of 1,2,3 will be duplicate, and we can shrink our range by half. If yes, then it means
* non of 1,2,3 will be duplicate, so we can look numbers > 3, and we still shrink our range by half
*
* Time complexity: O(NlogN)
* Space complexity: O(1)
*
* Sol1 is binary-search solution
* Sol2 is two pointer solution
*
* @author hpPlayer
* @date Jul 3, 2016 4:52:24 PM
*/
public class Find_the_Duplicate_Number_p287_sol1 {
public int findDuplicate(int[] nums) {
int start = 0, end = nums.length - 1;
//since input is guaranteed to have a solution, we can stop when we have only one element remaining
while(start < end){
int mid = start + (end - start)/2;
int count = 0;
//count how many nums in array <= mid.
for(int num : nums){
if( num <= mid ) count++;
}
if( count <= mid ){
//count <= mid indicates nums <= mid do not contain duplicate, so we can search nums > mid
//ex: mid = 3, we can have 1, 2, 3 in array
start = mid + 1;
}else{
//count > mid indicates num < mid contains duplicate, so we shrink search range to be 1-mid(both inclusive)
end = mid;
}
}
//start == end now, return either start or end
return start;
}
}
|
UTF-8
|
Java
| 2,575 |
java
|
Find_the_Duplicate_Number_p287_sol1.java
|
Java
|
[
{
"context": "ion\n * Sol2 is two pointer solution\n * \n * @author hpPlayer\n * @date Jul 3, 2016 4:52:24 PM\n */\npublic class ",
"end": 1478,
"score": 0.9995611310005188,
"start": 1470,
"tag": "USERNAME",
"value": "hpPlayer"
}
] | null |
[] |
/*
Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
prove that at least one duplicate element must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only constant extra space.
Your runtime complexity should be less than O(n2).
*/
/**
* Binary Search solution
*
* First of all we need to realize that the input allow has one duplicate number and it can appear multiple times
*
* The problem also limits the value range is from 1 to n (both inclusive), and input has len n + 1
* So we can make use of index from 1 to n (both inclusive) to find the target value
* Notice that index 0 can be the mid but we will never stop at it. If input size < 2, then we do not have solutions
*
* In this solution, we will use binary search on our index, each binary search will scan all inputs and count how
* many nums <= mid. Say we are looking at index 3, then we at most would have 1,2,3, three numbers smaller than it.
* If not, then it means one of 1,2,3 will be duplicate, and we can shrink our range by half. If yes, then it means
* non of 1,2,3 will be duplicate, so we can look numbers > 3, and we still shrink our range by half
*
* Time complexity: O(NlogN)
* Space complexity: O(1)
*
* Sol1 is binary-search solution
* Sol2 is two pointer solution
*
* @author hpPlayer
* @date Jul 3, 2016 4:52:24 PM
*/
public class Find_the_Duplicate_Number_p287_sol1 {
public int findDuplicate(int[] nums) {
int start = 0, end = nums.length - 1;
//since input is guaranteed to have a solution, we can stop when we have only one element remaining
while(start < end){
int mid = start + (end - start)/2;
int count = 0;
//count how many nums in array <= mid.
for(int num : nums){
if( num <= mid ) count++;
}
if( count <= mid ){
//count <= mid indicates nums <= mid do not contain duplicate, so we can search nums > mid
//ex: mid = 3, we can have 1, 2, 3 in array
start = mid + 1;
}else{
//count > mid indicates num < mid contains duplicate, so we shrink search range to be 1-mid(both inclusive)
end = mid;
}
}
//start == end now, return either start or end
return start;
}
}
| 2,575 | 0.625243 | 0.607379 | 64 | 39.234375 | 38.969437 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.546875 | false | false |
13
|
8cc0099d318fc1660b46ee396b2e2617ddcf21be
| 22,325,240,073,415 |
f52b026a532dd6b29c489d36a0357f56b508bc88
|
/app/src/main/java/com/origiontest/activity/TestFragmentActivity.java
|
d1298195530bb285120e98491f8d35938acfc017
|
[] |
no_license
|
LJ-GH/OrigionTest
|
https://github.com/LJ-GH/OrigionTest
|
d35be79af5ffd975050321b9f0fdb93fb3b107cc
|
cb59e82c182e1becd8567f952742ceaa079129ff
|
refs/heads/master
| 2021-05-04T01:53:01.040000 | 2016-10-18T10:07:05 | 2016-10-18T10:07:05 | 71,214,062 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.origiontest.activity;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.fragment.BlankFragment1;
import com.fragment.BlankFragment2;
import com.origiontest.R;
public class TestFragmentActivity extends Activity {
private Button btn_add_frag1;
private Button btn_add_frag2;
private Button btn_remove_frag2;
private Button btn_repalce_frag1;
private Button btn_pop_back;
private Button btn_show;
private Button btn_hide;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_fragment);
initView();
}
private void initView(){
btn_add_frag1 = (Button) findViewById(R.id.btn_add_frag1);
btn_add_frag2 = (Button) findViewById(R.id.btn_add_frag2);
btn_remove_frag2 = (Button) findViewById(R.id.btn_remove_frag2);
btn_repalce_frag1 = (Button) findViewById(R.id.btn_repalce_frag1);
btn_pop_back = (Button) findViewById(R.id.btn_pop_back);
btn_show = (Button) findViewById(R.id.btn_show);
btn_hide = (Button) findViewById(R.id.btn_hide);
btn_add_frag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment blankFragment1 = new BlankFragment1();
addFragment(blankFragment1,"blankFragment1");
}
});
btn_add_frag2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment blankFragment2 = new BlankFragment2();
addFragment(blankFragment2,"blankFragment2");
}
});
btn_remove_frag2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
removeFragment2();
}
});
btn_repalce_frag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
replaceFragment1();
}
});
btn_pop_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popBackStack();
}
});
btn_hide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideFragment("blankFragment2");
}
});
btn_show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFragment("blankFragment2");
}
});
}
private void addFragment(Fragment fragment, String tag){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragment_container,fragment,tag);
transaction.addToBackStack(tag);
transaction.commit();
}
private void removeFragment2(){
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag("blankFragment2");
if(fragment==null){return;}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
}
private void replaceFragment1() {
FragmentManager manager = getFragmentManager();
BlankFragment2 fragment2 = new BlankFragment2();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment2);
transaction.commit();
}
private void popBackStack(){
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack();
}
private void hideFragment(String tag){
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (null == fragment){return;}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fragment);
fragmentTransaction.commit();
}
private void showFragment(String tag){
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if(null==fragment){return;}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
}
}
|
UTF-8
|
Java
| 4,892 |
java
|
TestFragmentActivity.java
|
Java
|
[] | null |
[] |
package com.origiontest.activity;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.fragment.BlankFragment1;
import com.fragment.BlankFragment2;
import com.origiontest.R;
public class TestFragmentActivity extends Activity {
private Button btn_add_frag1;
private Button btn_add_frag2;
private Button btn_remove_frag2;
private Button btn_repalce_frag1;
private Button btn_pop_back;
private Button btn_show;
private Button btn_hide;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_fragment);
initView();
}
private void initView(){
btn_add_frag1 = (Button) findViewById(R.id.btn_add_frag1);
btn_add_frag2 = (Button) findViewById(R.id.btn_add_frag2);
btn_remove_frag2 = (Button) findViewById(R.id.btn_remove_frag2);
btn_repalce_frag1 = (Button) findViewById(R.id.btn_repalce_frag1);
btn_pop_back = (Button) findViewById(R.id.btn_pop_back);
btn_show = (Button) findViewById(R.id.btn_show);
btn_hide = (Button) findViewById(R.id.btn_hide);
btn_add_frag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment blankFragment1 = new BlankFragment1();
addFragment(blankFragment1,"blankFragment1");
}
});
btn_add_frag2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment blankFragment2 = new BlankFragment2();
addFragment(blankFragment2,"blankFragment2");
}
});
btn_remove_frag2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
removeFragment2();
}
});
btn_repalce_frag1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
replaceFragment1();
}
});
btn_pop_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popBackStack();
}
});
btn_hide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideFragment("blankFragment2");
}
});
btn_show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFragment("blankFragment2");
}
});
}
private void addFragment(Fragment fragment, String tag){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragment_container,fragment,tag);
transaction.addToBackStack(tag);
transaction.commit();
}
private void removeFragment2(){
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag("blankFragment2");
if(fragment==null){return;}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
}
private void replaceFragment1() {
FragmentManager manager = getFragmentManager();
BlankFragment2 fragment2 = new BlankFragment2();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment2);
transaction.commit();
}
private void popBackStack(){
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack();
}
private void hideFragment(String tag){
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (null == fragment){return;}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fragment);
fragmentTransaction.commit();
}
private void showFragment(String tag){
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if(null==fragment){return;}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
}
}
| 4,892 | 0.64861 | 0.641047 | 140 | 33.942856 | 24.312775 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
13
|
a059b0b74270842361d25ce61c0298ecc5233f1b
| 34,471,407,551,564 |
f8f7fb3853ded78c02b9392009d09916b1fd6977
|
/src/main/java/com/ahyx/wechat/communicationplant/utils/TokenUtil.java
|
8745010d96914db67143cee1569b8f0dbb72f84d
|
[] |
no_license
|
daimengying/communicationplant
|
https://github.com/daimengying/communicationplant
|
457cc93bc090415487ec24ff24d9e99841fd0d6b
|
6d84ce3f79ea5b8c8b6c8d633accf7b5ba527d41
|
refs/heads/master
| 2020-03-22T17:03:31.206000 | 2018-10-05T13:40:07 | 2018-10-05T13:40:07 | 140,369,521 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ahyx.wechat.communicationplant.utils;
import com.ahyx.wechat.communicationplant.config.WeChatAccountConfig;
import com.ahyx.wechat.communicationplant.contants.WeChatContant;
import com.ahyx.wechat.communicationplant.vo.AccessToken;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: daimengying
* @Date: 2018/7/3 11:41
* @Description:获取微信access_token的工具类
*/
@Component
public class TokenUtil {
private Logger _logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestUtils restUtils;
@Autowired
WeChatAccountConfig weChatAccountConfig;
// 第三方用户唯一凭证
private static AccessToken accessToken ;
public static AccessToken getInstance(){
return accessToken;
}
@Scheduled(fixedDelay = 2*3600*1000)
// @Scheduled(cron ="0 0/2 * * * ?" )
public void getAccessToken(){
Map<String ,String> reqMap =new HashMap();
reqMap.put("grant_type", WeChatContant.GRANTTYPE);
reqMap.put("appid",weChatAccountConfig.getAppId());
reqMap.put("secret",weChatAccountConfig.getAppSecret());
//返回格式{"access_token":"ACCESS_TOKEN","expires_in":7200}
try {
// if(accessToken==null){
// synchronized(AccessToken.class){
// if(accessToken==null){
// accessToken = new AccessToken();
// String restCallResult=restUtils.restGetForEntity( WeChatContant.ACCESS_TOKEN_URL,reqMap);
// if (!StringUtils.isEmpty(restCallResult)) {
// JSONObject accessJson=JSONObject.fromObject(restCallResult);
// accessToken.setToken(accessJson.getString("access_token"));
// accessToken.setExpiresIn(accessJson.getInt("expires_in"));
// }
// }
// }
// }
accessToken = new AccessToken();
String restCallResult=restUtils.restGetForEntity( WeChatContant.ACCESS_TOKEN_URL,reqMap);
if (!StringUtils.isEmpty(restCallResult)) {
JSONObject accessJson=JSONObject.fromObject(restCallResult);
accessToken.setToken(accessJson.getString("access_token"));
accessToken.setExpiresIn(accessJson.getInt("expires_in"));
}
}catch (Exception e){
_logger.error("获取access_token失败:"+e.getMessage());
}
}
}
|
UTF-8
|
Java
| 2,839 |
java
|
TokenUtil.java
|
Java
|
[
{
"context": "il.HashMap;\nimport java.util.Map;\n\n/**\n * @Author: daimengying\n * @Date: 2018/7/3 11:41\n * @Description:获取微信acce",
"end": 627,
"score": 0.9996362924575806,
"start": 616,
"tag": "USERNAME",
"value": "daimengying"
}
] | null |
[] |
package com.ahyx.wechat.communicationplant.utils;
import com.ahyx.wechat.communicationplant.config.WeChatAccountConfig;
import com.ahyx.wechat.communicationplant.contants.WeChatContant;
import com.ahyx.wechat.communicationplant.vo.AccessToken;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: daimengying
* @Date: 2018/7/3 11:41
* @Description:获取微信access_token的工具类
*/
@Component
public class TokenUtil {
private Logger _logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestUtils restUtils;
@Autowired
WeChatAccountConfig weChatAccountConfig;
// 第三方用户唯一凭证
private static AccessToken accessToken ;
public static AccessToken getInstance(){
return accessToken;
}
@Scheduled(fixedDelay = 2*3600*1000)
// @Scheduled(cron ="0 0/2 * * * ?" )
public void getAccessToken(){
Map<String ,String> reqMap =new HashMap();
reqMap.put("grant_type", WeChatContant.GRANTTYPE);
reqMap.put("appid",weChatAccountConfig.getAppId());
reqMap.put("secret",weChatAccountConfig.getAppSecret());
//返回格式{"access_token":"ACCESS_TOKEN","expires_in":7200}
try {
// if(accessToken==null){
// synchronized(AccessToken.class){
// if(accessToken==null){
// accessToken = new AccessToken();
// String restCallResult=restUtils.restGetForEntity( WeChatContant.ACCESS_TOKEN_URL,reqMap);
// if (!StringUtils.isEmpty(restCallResult)) {
// JSONObject accessJson=JSONObject.fromObject(restCallResult);
// accessToken.setToken(accessJson.getString("access_token"));
// accessToken.setExpiresIn(accessJson.getInt("expires_in"));
// }
// }
// }
// }
accessToken = new AccessToken();
String restCallResult=restUtils.restGetForEntity( WeChatContant.ACCESS_TOKEN_URL,reqMap);
if (!StringUtils.isEmpty(restCallResult)) {
JSONObject accessJson=JSONObject.fromObject(restCallResult);
accessToken.setToken(accessJson.getString("access_token"));
accessToken.setExpiresIn(accessJson.getInt("expires_in"));
}
}catch (Exception e){
_logger.error("获取access_token失败:"+e.getMessage());
}
}
}
| 2,839 | 0.642268 | 0.632221 | 74 | 36.662163 | 28.371702 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false |
7
|
7a13b77a4e12b97e1d29e038b28bf8cb1ef3a430
| 22,814,866,309,098 |
bf7fa697396557a4b84f9b3bf7d11e001863b0d1
|
/src/main/java/cwe/NetworkHandler.java
|
7c8f91905e22c4d3bd320c871d4dee7cef0e5acb
|
[] |
no_license
|
JasonYjz/MyLearn
|
https://github.com/JasonYjz/MyLearn
|
668af2ae5880db9ed40422fde4e7d5a05cf8dcd1
|
277c03fbf30fad5fe5dca76ee31b3dcc57f70f9c
|
refs/heads/master
| 2021-07-24T03:10:49.951000 | 2020-12-22T06:29:29 | 2020-12-22T06:29:29 | 229,166,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cwe;
/**
* Created by jasyu on 2020/12/8.
**/
final class HandleRequest implements Runnable {
public void run() {
// Do something
}
}
public final class NetworkHandler implements Runnable {
private static ThreadGroup tg = new ThreadGroup("Chief");
@Override public void run() {
new Thread(tg, new HandleRequest(), "thread1").start();
new Thread(tg, new HandleRequest(), "thread2").start();
new Thread(tg, new HandleRequest(), "thread3").start();
}
public static void printActiveCount(int point) {
System.out.println("Active Threads in Thread Group " + tg.getName() +
" at point(" + point + "):" + " " + tg.activeCount());
}
public static void printEnumeratedThreads(Thread[] ta, int len) {
System.out.println("Enumerating all threads...");
for (int i = 0; i < len; i++) {
System.out.println("Thread " + i + " = " + ta[i].getName());
}
}
public static void main(String[] args) throws InterruptedException {
// Start thread controller
Thread thread = new Thread(tg, new NetworkHandler(), "controller");
thread.start();
// Gets the active count (insecure)
Thread[] ta = new Thread[tg.activeCount()];
printActiveCount(1); // P1
// Delay to demonstrate TOCTOU condition (race window)
Thread.sleep(1000);
// P2: the thread count changes as new threads are initiated
printActiveCount(2);
// Incorrectly uses the (now stale) thread count obtained at P1
int n = tg.enumerate(ta);
// Silently ignores newly initiated threads
printEnumeratedThreads(ta, n);
// (between P1 and P2)
// This code destroys the thread group if it does
// not have any live threads
for (Thread thr : ta) {
thr.interrupt();
while(thr.isAlive());
}
tg.destroy();
}
}
|
UTF-8
|
Java
| 2,030 |
java
|
NetworkHandler.java
|
Java
|
[
{
"context": "package cwe;\r\n\r\n/**\r\n * Created by jasyu on 2020/12/8.\r\n **/\r\nfinal class HandleRequest im",
"end": 40,
"score": 0.9059984087944031,
"start": 35,
"tag": "USERNAME",
"value": "jasyu"
}
] | null |
[] |
package cwe;
/**
* Created by jasyu on 2020/12/8.
**/
final class HandleRequest implements Runnable {
public void run() {
// Do something
}
}
public final class NetworkHandler implements Runnable {
private static ThreadGroup tg = new ThreadGroup("Chief");
@Override public void run() {
new Thread(tg, new HandleRequest(), "thread1").start();
new Thread(tg, new HandleRequest(), "thread2").start();
new Thread(tg, new HandleRequest(), "thread3").start();
}
public static void printActiveCount(int point) {
System.out.println("Active Threads in Thread Group " + tg.getName() +
" at point(" + point + "):" + " " + tg.activeCount());
}
public static void printEnumeratedThreads(Thread[] ta, int len) {
System.out.println("Enumerating all threads...");
for (int i = 0; i < len; i++) {
System.out.println("Thread " + i + " = " + ta[i].getName());
}
}
public static void main(String[] args) throws InterruptedException {
// Start thread controller
Thread thread = new Thread(tg, new NetworkHandler(), "controller");
thread.start();
// Gets the active count (insecure)
Thread[] ta = new Thread[tg.activeCount()];
printActiveCount(1); // P1
// Delay to demonstrate TOCTOU condition (race window)
Thread.sleep(1000);
// P2: the thread count changes as new threads are initiated
printActiveCount(2);
// Incorrectly uses the (now stale) thread count obtained at P1
int n = tg.enumerate(ta);
// Silently ignores newly initiated threads
printEnumeratedThreads(ta, n);
// (between P1 and P2)
// This code destroys the thread group if it does
// not have any live threads
for (Thread thr : ta) {
thr.interrupt();
while(thr.isAlive());
}
tg.destroy();
}
}
| 2,030 | 0.573892 | 0.563054 | 60 | 31.833334 | 25.488014 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516667 | false | false |
7
|
5a338d5736eb19095d7c96c55aadc9b2813cc6f5
| 38,792,144,618,372 |
dfe5caf190661c003619bfe7a7944c527c917ee4
|
/src/main/java/com/vmware/vim25/DvsHostInfrastructureTrafficResource.java
|
33a1d9e2f72a2091c328cfd194048d9f39b451a1
|
[
"BSD-3-Clause"
] |
permissive
|
timtasse/vijava
|
https://github.com/timtasse/vijava
|
c9787f9f9b3116a01f70a89d6ea29cc4f6dc3cd0
|
5d75bc0bd212534d44f78e5a287abf3f909a2e8e
|
refs/heads/master
| 2023-06-01T08:20:39.601000 | 2022-10-31T12:43:24 | 2022-10-31T12:43:24 | 150,118,529 | 4 | 1 |
BSD-3-Clause
| false | 2023-05-01T21:19:53 | 2018-09-24T14:46:15 | 2022-10-04T16:57:20 | 2023-05-01T21:19:51 | 2,039 | 4 | 0 | 1 |
Java
| false | false |
package com.vmware.vim25;
/**
* This class defines the resource allocation for a host infrastructure traffic class on a physical NIC
*
* @author Stefan Dilk <stefan.dilk@freenet.ag>
* @since 6.0
*/
public class DvsHostInfrastructureTrafficResource extends DynamicData {
private String key;
private String description;
private DvsHostInfrastructureTrafficResourceAllocation allocationInfo;
@Override
public String toString() {
return "DvsHostInfrastructureTrafficResource{" +
"key='" + key + '\'' +
", description='" + description + '\'' +
", allocationInfo=" + allocationInfo +
"} " + super.toString();
}
public DvsHostInfrastructureTrafficResourceAllocation getAllocationInfo() {
return allocationInfo;
}
public void setAllocationInfo(final DvsHostInfrastructureTrafficResourceAllocation allocationInfo) {
this.allocationInfo = allocationInfo;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getKey() {
return key;
}
public void setKey(final String key) {
this.key = key;
}
}
|
UTF-8
|
Java
| 1,295 |
java
|
DvsHostInfrastructureTrafficResource.java
|
Java
|
[
{
"context": "ture traffic class on a physical NIC\n *\n * @author Stefan Dilk <stefan.dilk@freenet.ag>\n * @since 6.0\n */\npublic",
"end": 160,
"score": 0.999893844127655,
"start": 149,
"tag": "NAME",
"value": "Stefan Dilk"
},
{
"context": "lass on a physical NIC\n *\n * @author Stefan Dilk <stefan.dilk@freenet.ag>\n * @since 6.0\n */\npublic class DvsHostInfrastruc",
"end": 184,
"score": 0.9999310970306396,
"start": 162,
"tag": "EMAIL",
"value": "stefan.dilk@freenet.ag"
}
] | null |
[] |
package com.vmware.vim25;
/**
* This class defines the resource allocation for a host infrastructure traffic class on a physical NIC
*
* @author <NAME> <<EMAIL>>
* @since 6.0
*/
public class DvsHostInfrastructureTrafficResource extends DynamicData {
private String key;
private String description;
private DvsHostInfrastructureTrafficResourceAllocation allocationInfo;
@Override
public String toString() {
return "DvsHostInfrastructureTrafficResource{" +
"key='" + key + '\'' +
", description='" + description + '\'' +
", allocationInfo=" + allocationInfo +
"} " + super.toString();
}
public DvsHostInfrastructureTrafficResourceAllocation getAllocationInfo() {
return allocationInfo;
}
public void setAllocationInfo(final DvsHostInfrastructureTrafficResourceAllocation allocationInfo) {
this.allocationInfo = allocationInfo;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getKey() {
return key;
}
public void setKey(final String key) {
this.key = key;
}
}
| 1,275 | 0.659459 | 0.656371 | 47 | 26.553192 | 27.794695 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276596 | false | false |
7
|
69a1e56ef2ffbf421a3d502385190d2547b65a5a
| 34,875,134,494,957 |
370f95d3924f7f902738f5cd4c3f2fb36559ee34
|
/src/main/java/com/technogise/expensesharingapp/services/DebtService.java
|
cfdff2bb377e86c871adbc5014cd5f4584d2d35e
|
[] |
no_license
|
chandan911/expense-sharing-app
|
https://github.com/chandan911/expense-sharing-app
|
2331840aa612441864d6c577cea2078a19fc227e
|
e337320ccad9375307493db12a961f3c2181b6b4
|
refs/heads/master
| 2023-03-02T22:22:21.299000 | 2021-02-12T05:16:31 | 2021-02-12T05:16:31 | 331,211,348 | 0 | 0 | null | false | 2021-02-12T05:16:32 | 2021-01-20T06:15:12 | 2021-02-08T08:28:50 | 2021-02-12T05:16:31 | 199 | 0 | 0 | 0 |
Java
| false | false |
package com.technogise.expensesharingapp.services;
import com.technogise.expensesharingapp.models.NewExpenseRequest;
import com.technogise.expensesharingapp.models.Debt;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("debtService")
public interface DebtService {
List<Debt> getAllDebtsByUserId(Long userId);
Boolean updateDebtRepository(Long payerId, Long debtorId, Double debtAmount);
Boolean updateDebtProcess(NewExpenseRequest newExpenseRequest);
}
|
UTF-8
|
Java
| 501 |
java
|
DebtService.java
|
Java
|
[] | null |
[] |
package com.technogise.expensesharingapp.services;
import com.technogise.expensesharingapp.models.NewExpenseRequest;
import com.technogise.expensesharingapp.models.Debt;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("debtService")
public interface DebtService {
List<Debt> getAllDebtsByUserId(Long userId);
Boolean updateDebtRepository(Long payerId, Long debtorId, Double debtAmount);
Boolean updateDebtProcess(NewExpenseRequest newExpenseRequest);
}
| 501 | 0.834331 | 0.834331 | 18 | 26.833334 | 27.248344 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
7
|
97e376b54715408b00a9f0b85058763a11ac1a2d
| 36,704,790,548,695 |
2e2d3c702ca23f23c0d291d0c8c1354037de2bd1
|
/code/gradle/src/main/java/com/chriswk/App.java
|
00b0886aecfb55f95ccc26126b89f58ce44e2088
|
[] |
no_license
|
chriswk/academyapr13th2016
|
https://github.com/chriswk/academyapr13th2016
|
5c122d3996910d3d256648c0f4dee82f55627aa6
|
995deb1698255fc7aea0eb92f0b4698b12c26d44
|
refs/heads/master
| 2019-08-28T07:46:03.041000 | 2016-04-13T11:50:55 | 2016-04-13T11:50:55 | 56,128,525 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chriswk;
public class App {
public static void main(String... args) {
ImmutableEstateUnit unit = ImmutableEstateUnit.builder().id(1).teaser("Some tease").plotSize(42.0d).build();
ImmutableEstateUnit unit2 = ImmutableEstateUnit.builder().id(2).teaser("Some tease").plotSize(82.0d).build();
ImmutableEstateProject project = ImmutableEstateProject.builder()
.addUnits(unit).addUnits(unit2).build();
ImmutableOrganisation org = ImmutableOrganisation.builder().id(-3L).name("FINN Jobb AS").build();
ImmutableAd builtAd = ImmutableAd.builder()
.addEstateProjects(project)
.id(1L)
.type(1L)
.status(50L)
.heading("HEading")
.body("Body")
.organisation(org)
.build();
System.out.println(unit.toString());
System.out.println(project);
System.out.println(project.totalArea());
System.out.println(org);
System.out.println(builtAd.unitCount());
ImmutableAd buildAd2 = builtAd.withStatus(51L).withId(2L).withOrganisation(org.withName("DNB").withId(3L));
System.out.println(buildAd2);
System.out.println(builtAd);
}
}
|
UTF-8
|
Java
| 1,273 |
java
|
App.java
|
Java
|
[] | null |
[] |
package com.chriswk;
public class App {
public static void main(String... args) {
ImmutableEstateUnit unit = ImmutableEstateUnit.builder().id(1).teaser("Some tease").plotSize(42.0d).build();
ImmutableEstateUnit unit2 = ImmutableEstateUnit.builder().id(2).teaser("Some tease").plotSize(82.0d).build();
ImmutableEstateProject project = ImmutableEstateProject.builder()
.addUnits(unit).addUnits(unit2).build();
ImmutableOrganisation org = ImmutableOrganisation.builder().id(-3L).name("FINN Jobb AS").build();
ImmutableAd builtAd = ImmutableAd.builder()
.addEstateProjects(project)
.id(1L)
.type(1L)
.status(50L)
.heading("HEading")
.body("Body")
.organisation(org)
.build();
System.out.println(unit.toString());
System.out.println(project);
System.out.println(project.totalArea());
System.out.println(org);
System.out.println(builtAd.unitCount());
ImmutableAd buildAd2 = builtAd.withStatus(51L).withId(2L).withOrganisation(org.withName("DNB").withId(3L));
System.out.println(buildAd2);
System.out.println(builtAd);
}
}
| 1,273 | 0.612726 | 0.596229 | 28 | 44.464287 | 32.205238 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
7
|
7ff45584cf004a42c512e371ac66028ab2f2d945
| 36,704,790,548,233 |
2d18de57e2625abdf7745361cb4d9291691d80b7
|
/src/clueGame/WalkwayCell.java
|
1b4d6e9464fb191c346396fb8b28f34c93b6f1c0
|
[] |
no_license
|
Qualenal/ClueGame-1
|
https://github.com/Qualenal/ClueGame-1
|
975f67a4394c79eb91dda594c79e4735676926e1
|
e686b9a28b90d1dd9c5b7fbdf4cd1e0880b9b3d1
|
refs/heads/master
| 2021-01-22T10:14:14.557000 | 2014-10-25T08:04:39 | 2014-10-25T08:04:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package clueGame;
import java.awt.Color;
import java.awt.Graphics;
public class WalkwayCell extends BoardCell {
public static int SQUARE_LENGTH = 30;
public WalkwayCell(int row, int col) {
super(row, col, "W");
}
public boolean isWalkway() {
return true;
}
public void draw(Graphics g, Board b) {
g.setColor(Color.YELLOW);
g.fillRect(col*SQUARE_LENGTH, row*SQUARE_LENGTH, SQUARE_LENGTH, SQUARE_LENGTH);
g.setColor(Color.BLACK);
g.drawRect(col*SQUARE_LENGTH, row*SQUARE_LENGTH, SQUARE_LENGTH, SQUARE_LENGTH);
}
}
|
UTF-8
|
Java
| 578 |
java
|
WalkwayCell.java
|
Java
|
[] | null |
[] |
package clueGame;
import java.awt.Color;
import java.awt.Graphics;
public class WalkwayCell extends BoardCell {
public static int SQUARE_LENGTH = 30;
public WalkwayCell(int row, int col) {
super(row, col, "W");
}
public boolean isWalkway() {
return true;
}
public void draw(Graphics g, Board b) {
g.setColor(Color.YELLOW);
g.fillRect(col*SQUARE_LENGTH, row*SQUARE_LENGTH, SQUARE_LENGTH, SQUARE_LENGTH);
g.setColor(Color.BLACK);
g.drawRect(col*SQUARE_LENGTH, row*SQUARE_LENGTH, SQUARE_LENGTH, SQUARE_LENGTH);
}
}
| 578 | 0.67128 | 0.66782 | 26 | 21.23077 | 23.475533 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.153846 | false | false |
7
|
44624700f4f2a63c82a5523b8f721eb0d1acbf3c
| 37,082,747,665,891 |
4579ea1f97b370f85a2c6b619281c0078e6cb3c1
|
/src/test/java/BoundaryCellTest.java
|
c6189b88ebcc0821c3b357d4438bfb8e8e38c75c
|
[] |
no_license
|
Jiangxuelin1205/ThoughtWorksProgramming
|
https://github.com/Jiangxuelin1205/ThoughtWorksProgramming
|
3d497b4750697383c443e801287498b9f9e20fe6
|
6b67b83ef6242640b978dff423b681b173c9eac3
|
refs/heads/master
| 2021-07-06T15:34:56.926000 | 2019-06-13T03:55:03 | 2019-06-13T03:55:03 | 191,491,905 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import Backend.Cells;
import org.junit.Assert;
import org.junit.Test;
public class BoundaryCellTest {
@Test
public void living_cell_with_fewer_than_two_neighbours_left_top_will_die() {
//given
int[][] currentState = new int[][]{
{1, 0, 1, 0},
{0, 1, 0, 0},
{0, 0, 0, 0}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(0, 0), 0);
}
@Test
public void living_cell_with_more_than_three_neighbours_will_die() {
//given
int[][] currentState = new int[][]{
{1, 1, 1, 1},
{1, 1, 1, 1},
{0, 0, 1, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(0, 1), 0);
}
@Test
public void living_cell_with_two_neighbours_right_bottom_will_live_on() {
//given
int[][] currentState = new int[][]{
{1, 1, 1, 1},
{1, 1, 1, 0},
{0, 0, 1, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(2, 3), 1);
}
@Test
public void living_cell_with_three_neighbours_will_live_on() {
//given
int[][] currentState = new int[][]{
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 0, 0, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(1, 1), 1);
}
@Test
public void died_cell_with_three_neighbours_will_live_on() {
//given
int[][] currentState = new int[][]{
{0, 1, 0, 1},
{1, 1, 0, 0},
{0, 0, 0, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(1, 2), 0);
}
@Test
public void died_cell_with_more_than_three_neighbours_will_die() {
//given
int[][] currentState = new int[][]{
{1, 1, 0, 1},
{1, 1, 1, 0},
{0, 0, 0, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(0, 1), 0);
}
@Test
public void died_cell_with_fewer_than_three_neighbours_will_die() {
//given
int[][] currentState = new int[][]{
{1, 1, 0, 1},
{1, 1, 1, 0},
{0, 0, 0, 0}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(2, 2), 0);
}
}
|
UTF-8
|
Java
| 3,013 |
java
|
BoundaryCellTest.java
|
Java
|
[] | null |
[] |
import Backend.Cells;
import org.junit.Assert;
import org.junit.Test;
public class BoundaryCellTest {
@Test
public void living_cell_with_fewer_than_two_neighbours_left_top_will_die() {
//given
int[][] currentState = new int[][]{
{1, 0, 1, 0},
{0, 1, 0, 0},
{0, 0, 0, 0}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(0, 0), 0);
}
@Test
public void living_cell_with_more_than_three_neighbours_will_die() {
//given
int[][] currentState = new int[][]{
{1, 1, 1, 1},
{1, 1, 1, 1},
{0, 0, 1, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(0, 1), 0);
}
@Test
public void living_cell_with_two_neighbours_right_bottom_will_live_on() {
//given
int[][] currentState = new int[][]{
{1, 1, 1, 1},
{1, 1, 1, 0},
{0, 0, 1, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(2, 3), 1);
}
@Test
public void living_cell_with_three_neighbours_will_live_on() {
//given
int[][] currentState = new int[][]{
{1, 1, 0, 1},
{1, 1, 0, 0},
{0, 0, 0, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(1, 1), 1);
}
@Test
public void died_cell_with_three_neighbours_will_live_on() {
//given
int[][] currentState = new int[][]{
{0, 1, 0, 1},
{1, 1, 0, 0},
{0, 0, 0, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(1, 2), 0);
}
@Test
public void died_cell_with_more_than_three_neighbours_will_die() {
//given
int[][] currentState = new int[][]{
{1, 1, 0, 1},
{1, 1, 1, 0},
{0, 0, 0, 1}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(0, 1), 0);
}
@Test
public void died_cell_with_fewer_than_three_neighbours_will_die() {
//given
int[][] currentState = new int[][]{
{1, 1, 0, 1},
{1, 1, 1, 0},
{0, 0, 0, 0}
};
Cells cells = new Cells(currentState);
//when
cells.nextState();
//then
Assert.assertEquals(cells.cellCurrentState(2, 2), 0);
}
}
| 3,013 | 0.467308 | 0.432459 | 111 | 26.144144 | 19.922302 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.099099 | false | false |
7
|
bd0e3d835ae438f36b8e42376feb070c29a0143e
| 34,325,378,687,469 |
310223c9774c93794cf5c3ab492ea051edc3fb58
|
/src/main/java/com/visionet/common/model/datagrid/DataOptions.java
|
b4faceb93fc8da4eb0093a488f839f4c69f8031c
|
[] |
no_license
|
mcsanchez093/vitality
|
https://github.com/mcsanchez093/vitality
|
24b1a3f36cc1181a06e626d5542667be9f46ded2
|
68e241566d2ccf662e397af6166be09810a0015f
|
refs/heads/master
| 2021-05-27T00:24:41.644000 | 2013-05-10T07:12:30 | 2013-05-10T07:12:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.visionet.common.model.datagrid;
public class DataOptions {
/**
* 起始页数
*/
private Integer pageIndex;
/**
* 每页显示条数
*/
private Integer pageSize;
/**
* 升序降序
*/
private String sortDirection;
/**
* 排序列名
*/
private String sortProperty;
/**
* @return the pageIndex
*/
public Integer getPageIndex() {
return pageIndex;
}
/**
* @param pageIndex the pageIndex to set
*/
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
/**
* @return the pageSize
*/
public Integer getPageSize() {
return pageSize;
}
/**
* @param pageSize the pageSize to set
*/
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
/**
* @return the sortDirection
*/
public String getSortDirection() {
return sortDirection;
}
/**
* @param sortDirection the sortDirection to set
*/
public void setSortDirection(String sortDirection) {
this.sortDirection = sortDirection;
}
/**
* @return the sortProperty
*/
public String getSortProperty() {
return sortProperty;
}
/**
* @param sortProperty the sortProperty to set
*/
public void setSortProperty(String sortProperty) {
this.sortProperty = sortProperty;
}
}
|
UTF-8
|
Java
| 1,324 |
java
|
DataOptions.java
|
Java
|
[] | null |
[] |
package com.visionet.common.model.datagrid;
public class DataOptions {
/**
* 起始页数
*/
private Integer pageIndex;
/**
* 每页显示条数
*/
private Integer pageSize;
/**
* 升序降序
*/
private String sortDirection;
/**
* 排序列名
*/
private String sortProperty;
/**
* @return the pageIndex
*/
public Integer getPageIndex() {
return pageIndex;
}
/**
* @param pageIndex the pageIndex to set
*/
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
/**
* @return the pageSize
*/
public Integer getPageSize() {
return pageSize;
}
/**
* @param pageSize the pageSize to set
*/
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
/**
* @return the sortDirection
*/
public String getSortDirection() {
return sortDirection;
}
/**
* @param sortDirection the sortDirection to set
*/
public void setSortDirection(String sortDirection) {
this.sortDirection = sortDirection;
}
/**
* @return the sortProperty
*/
public String getSortProperty() {
return sortProperty;
}
/**
* @param sortProperty the sortProperty to set
*/
public void setSortProperty(String sortProperty) {
this.sortProperty = sortProperty;
}
}
| 1,324 | 0.63587 | 0.63587 | 70 | 16.4 | 15.983384 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.242857 | false | false |
7
|
60b53ca3c502d0fc72033f873f27bd0c330573d2
| 36,575,941,533,191 |
1c40b7839027cf2ef11826a31d65e6fea18c0b38
|
/testframewok/src/main/java/jet/opengl/demos/intel/cput/CPUTMaterial.java
|
b09c68e990f242e5beb984841c50274a038fd796
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
mzhg/PostProcessingWork
|
https://github.com/mzhg/PostProcessingWork
|
5370d37597015a178aef8cb631cc2925e4dde71e
|
fbc0f2a4693995102f623bf5b7643c15d7309f9a
|
refs/heads/master
| 2022-10-21T04:32:24.792000 | 2022-10-06T06:37:31 | 2022-10-06T06:37:31 | 86,224,204 | 17 | 8 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package jet.opengl.demos.intel.cput;
import org.lwjgl.util.vector.Vector4f;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jet.opengl.postprocessing.common.Disposeable;
import jet.opengl.postprocessing.shader.Macro;
import jet.opengl.postprocessing.util.StringUtils;
/**
* Created by mazhen'gui on 2017/11/13.
*/
public class CPUTMaterial implements Disposeable{
public static final int
CPUT_MATERIAL_MAX_TEXTURE_SLOTS =8, // TODO Eight is enough.
CPUT_MATERIAL_MAX_BUFFER_SLOTS =8,
CPUT_MATERIAL_MAX_CONSTANT_BUFFER_SLOTS =8,
CPUT_MATERIAL_MAX_SRV_SLOTS =8,
CPUT_MATERIAL_MAX_UAV_SLOTS = 8;
public static final CPUTConfigBlock mGlobalProperties = new CPUTConfigBlock();
protected String mMaterialName;
protected CPUTModel mpModel; // We use pointers to the model and mesh to distinguish instanced materials.
protected int mMeshIndex;
protected CPUTConfigBlock mConfigBlock;
protected CPUTRenderStateBlock mpRenderStateBlock;
// A material can have multiple submaterials. If it does, then that's all it does. It just "branches" to other materials.
// TODO: We could make that a special object, and derive them from material. Not sure that's worth the effort.
// The alternative we choose here is to simply comandeer this one, ignoring most of its state and functionality.
protected int mMaterialEffectCount;
protected CPUTMaterialEffect [] mpMaterialEffects;
protected String [] mpMaterialEffectNames;
protected int mCurrentMaterialEffect;
CPUTMaterial mpMaterialNextClone;
CPUTMaterial mpMaterialLastClone;
public static CPUTMaterial CreateMaterial(String absolutePathAndFilename, String modelSuffix, String meshSuffix )throws IOException{
CPUTMaterialDX11 pMaterial = new CPUTMaterialDX11();
pMaterial.LoadMaterial(absolutePathAndFilename, modelSuffix, meshSuffix);
// ASSERT( CPUTSUCCESS(result), _L("\nError - CPUTAssetLibrary::GetMaterial() - Error in material file: '")+absolutePathAndFilename+_L("'") );
// add material to material library list
// cString finalName = pMaterial->MaterialRequiresPerModelPayload() ? absolutePathAndFilename + modelSuffix + meshSuffix : absolutePathAndFilename;
// CPUTAssetLibrary::GetAssetLibrary()->AddMaterial( finalName, pMaterial );
// CPUTAssetLibrary::GetAssetLibrary()->AddMaterial( absolutePathAndFilename, pMaterial ); TODO
return pMaterial;
}
public static CPUTMaterial CreateMaterial(
String absolutePathAndFilename,
CPUTModel pModel,
int meshIndex,
Macro[] pShaderMacros, // Note: this is honored only on first load. Subsequent GetMaterial calls will return the material with shaders as compiled with original macros.
int numSystemMaterials,
String[] pSystemMaterialNames,
int externalCount,
String pExternalName,
Vector4f[] pExternals,
int[] pExternalOffset,
int[] pExternalSize
)throws IOException{
// Create the material and load it from file.
//#ifdef CPUT_FOR_DX11
// CPUTMaterial *pMaterial = new CPUTMaterialDX11();
//#elif (defined(CPUT_FOR_OGL) || defined(CPUT_FOR_OGLES))
// CPUTMaterial *pMaterial = new CPUTMaterialOGL();
//#else
// #error You must supply a target graphics API (ex: #define CPUT_FOR_DX11), or implement the target API for this file.
//#endif
// pMaterial->mpSubMaterials = NULL;
CPUTMaterial pMaterial = new CPUTMaterial();
pMaterial.LoadMaterial( absolutePathAndFilename, pModel, meshIndex, pShaderMacros, numSystemMaterials, pSystemMaterialNames, externalCount, pExternalName, pExternals, pExternalOffset, pExternalSize );
// ASSERT( CPUTSUCCESS(result), _L("\nError - CPUTAssetLibrary::GetMaterial() - Error in material file: '")+absolutePathAndFilename+_L("'") );
// UNREFERENCED_PARAMETER(result);
// Add the material to the asset library.
CPUTAssetLibrary.GetAssetLibrary().AddMaterial( absolutePathAndFilename, "", "", pMaterial, pShaderMacros, null,-1 );
return pMaterial;
}
private void LoadMaterial(String fileName, CPUTModel pModel, int meshIndex/*=-1*/,
Macro[] pShaderMacros, int systemMaterialCount, String []pSystemMaterialNames,
int externalCount, String pExternalName,Vector4f []pExternals,
int []pExternalOffset, int []pExternalSize)throws IOException{
mMaterialName = fileName;
// mMaterialNameHash = CPUTComputeHash( mMaterialName );
// Open/parse the file
CPUTConfigFile file = new CPUTConfigFile();
file.LoadFile(fileName);
// const char * tempfilename = fileName.c_str();
// Make a local copy of all the parameters
CPUTConfigBlock pBlock = file.GetBlock(0);
// ASSERT( pBlock, _L("Error getting parameter block") );
if( pBlock == null)
{
// return CPUT_ERROR_PARAMETER_BLOCK_NOT_FOUND;
throw new NullPointerException("Error getting parameter block");
}
mConfigBlock = pBlock;
CPUTAssetLibrary pAssetLibrary = CPUTAssetLibrary.GetAssetLibrary();
mMaterialEffectCount = 0;
if( mConfigBlock.GetValueByName("MultiMaterial" ).ValueAsBool() )
{
// Count materials;
for(;;)
{
CPUTConfigEntry pValue = mConfigBlock.GetValueByName( "Material" + mMaterialEffectCount );
if( pValue.IsValid() )
{
++mMaterialEffectCount;
} else
{
break;
}
}
assert mMaterialEffectCount != 0 : ("MultiMaterial specified, but no sub materials given.");
// Reserve space for "authored" materials plus system materials
mpMaterialEffectNames = new String[mMaterialEffectCount+systemMaterialCount];
int ii;
for( ii=0; ii<mMaterialEffectCount; ii++ )
{
CPUTConfigEntry pValue = mConfigBlock.GetValueByName( "Material" + ii );
mpMaterialEffectNames[ii] = pAssetLibrary.GetMaterialEffectPath(pValue.ValueAsString(), false);
}
}
else
{
mMaterialEffectCount = 1;
mpMaterialEffectNames = new String[mMaterialEffectCount+systemMaterialCount];
mpMaterialEffectNames[0] = fileName;
}
// The real material count includes the system material count
mMaterialEffectCount += systemMaterialCount;
for( int ii=0; ii<systemMaterialCount; ii++ )
{
// System materials "grow" from the end; the 1st system material is at the end of the list.
mpMaterialEffectNames[mMaterialEffectCount-systemMaterialCount+ii] = pSystemMaterialNames[ii];
}
mpMaterialEffects = new CPUTMaterialEffect[mMaterialEffectCount+1];
for( int ii=0; ii<mMaterialEffectCount; ii++ )
{
Macro [] pFinalShaderMacros = pShaderMacros;
Macro []pUserSpecifiedMacros = null;
int numUserSpecifiedMacros = 0;
// Read additional macros from .mtl file
String macroBlockName = "defines" + ii;
CPUTConfigBlock pMacrosBlock = file.GetBlockByName(macroBlockName);
if( pMacrosBlock != null)
{
List<Macro> userSpecifiedMacros = new ArrayList<>();
List<Macro> finalShaderMacros = new ArrayList<>();
ReadMacrosFromConfigBlock( pMacrosBlock, pShaderMacros, userSpecifiedMacros, /*&numUserSpecifiedMacros,*/ finalShaderMacros );
pUserSpecifiedMacros = userSpecifiedMacros.toArray(new Macro[userSpecifiedMacros.size()]);
pFinalShaderMacros = finalShaderMacros.toArray(new Macro[finalShaderMacros.size()]);
numUserSpecifiedMacros = pUserSpecifiedMacros.length;
}
mpMaterialEffects[ii] = pAssetLibrary.GetMaterialEffect( mpMaterialEffectNames[ii], true, pModel, meshIndex, pFinalShaderMacros );
for( int kk=0; kk<numUserSpecifiedMacros; kk++ )
{
// ReadMacrosFromConfigBlock allocates memory (ws2s does). Delete it here.
// SAFE_DELETE(pUserSpecifiedMacros[kk].Name);
// SAFE_DELETE(pUserSpecifiedMacros[kk].Definition);
}
// SAFE_DELETE_ARRAY( pFinalShaderMacros );
// SAFE_DELETE_ARRAY( pUserSpecifiedMacros );
}
mpMaterialEffects[mMaterialEffectCount] = null;
}
//-----------------------------------------------------------------------------
void ReadMacrosFromConfigBlock(
CPUTConfigBlock pMacrosBlock,
Macro[] pShaderMacros,
List<Macro> pUserSpecifiedMacros,
// int *pNumUserSpecifiedMacros,
List<Macro> pFinalShaderMacros
){
int pNumUserSpecifiedMacros = pMacrosBlock.ValueCount();
// Count the number of macros passed in
Macro[] pMacro = pShaderMacros;
int numPassedInMacros = 0;
if( pMacro != null && pMacro.length > 0)
{
while( !StringUtils.isBlank(pMacro[numPassedInMacros].key))
{
++numPassedInMacros;
// ++pMacro;
}
}
// Allocate an array of macro pointer large enough to contain the passed-in macros plus those specified in the .mtl file.
// *pFinalShaderMacros = new CPUT_SHADER_MACRO[*pNumUserSpecifiedMacros + numPassedInMacros + 1];
// Copy the passed-in macro pointers to the final array
int jj;
for( jj=0; jj<numPassedInMacros; jj++ )
{
// (*pFinalShaderMacros)[jj] = *(CPUT_SHADER_MACRO*)&pShaderMacros[jj];
pFinalShaderMacros.add(pShaderMacros[jj]);
}
// Create a CPUT_SHADER_MACRO for each of the macros specified in the .mtl file.
// And, add their pointers to the final array
// *pUserSpecifiedMacros = new CPUT_SHADER_MACRO[pNumUserSpecifiedMacros];
for( int kk=0; kk<pNumUserSpecifiedMacros; kk++, jj++ )
{
CPUTConfigEntry pValue = pMacrosBlock.GetValue(kk);
// (*pUserSpecifiedMacros)[kk].Name = ws2s(pValue->NameAsString());
// (*pUserSpecifiedMacros)[kk].Definition = ws2s(pValue->ValueAsString());
// (*pFinalShaderMacros)[jj] = (*pUserSpecifiedMacros)[kk];
Macro macro = new Macro(pValue.NameAsString(), pValue.ValueAsString());
pUserSpecifiedMacros.add(macro);
pFinalShaderMacros.add(macro);
}
// (*pFinalShaderMacros)[jj].Name = NULL;
// (*pFinalShaderMacros)[jj].Definition = NULL;
}
public void SetMaterialName(String MaterialName) { mMaterialName = MaterialName; }
public String GetMaterialName() {return mMaterialName; }
public CPUTMaterialEffect [] GetMaterialEffects() { return mpMaterialEffects; }
public int GetMaterialEffectCount() { return mMaterialEffectCount; }
public int GetCurrentEffect() { return mCurrentMaterialEffect; }
public void SetCurrentEffect(int CurrentMaterial) { mCurrentMaterialEffect = CurrentMaterial; }
public CPUTMaterial GetNextClone() { return mpMaterialNextClone; }
@Override
public void dispose() {
for(int ii = 0; ii < mMaterialEffectCount; ii++)
{
SAFE_RELEASE(mpMaterialEffects[ii]);
}
mpMaterialEffects = null;
}
}
|
UTF-8
|
Java
| 11,993 |
java
|
CPUTMaterial.java
|
Java
|
[
{
"context": "ostprocessing.util.StringUtils;\n\n/**\n * Created by mazhen'gui on 2017/11/13.\n */\n\npublic class CPUTMaterial imp",
"end": 338,
"score": 0.9882647395133972,
"start": 328,
"tag": "USERNAME",
"value": "mazhen'gui"
}
] | null |
[] |
package jet.opengl.demos.intel.cput;
import org.lwjgl.util.vector.Vector4f;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jet.opengl.postprocessing.common.Disposeable;
import jet.opengl.postprocessing.shader.Macro;
import jet.opengl.postprocessing.util.StringUtils;
/**
* Created by mazhen'gui on 2017/11/13.
*/
public class CPUTMaterial implements Disposeable{
public static final int
CPUT_MATERIAL_MAX_TEXTURE_SLOTS =8, // TODO Eight is enough.
CPUT_MATERIAL_MAX_BUFFER_SLOTS =8,
CPUT_MATERIAL_MAX_CONSTANT_BUFFER_SLOTS =8,
CPUT_MATERIAL_MAX_SRV_SLOTS =8,
CPUT_MATERIAL_MAX_UAV_SLOTS = 8;
public static final CPUTConfigBlock mGlobalProperties = new CPUTConfigBlock();
protected String mMaterialName;
protected CPUTModel mpModel; // We use pointers to the model and mesh to distinguish instanced materials.
protected int mMeshIndex;
protected CPUTConfigBlock mConfigBlock;
protected CPUTRenderStateBlock mpRenderStateBlock;
// A material can have multiple submaterials. If it does, then that's all it does. It just "branches" to other materials.
// TODO: We could make that a special object, and derive them from material. Not sure that's worth the effort.
// The alternative we choose here is to simply comandeer this one, ignoring most of its state and functionality.
protected int mMaterialEffectCount;
protected CPUTMaterialEffect [] mpMaterialEffects;
protected String [] mpMaterialEffectNames;
protected int mCurrentMaterialEffect;
CPUTMaterial mpMaterialNextClone;
CPUTMaterial mpMaterialLastClone;
public static CPUTMaterial CreateMaterial(String absolutePathAndFilename, String modelSuffix, String meshSuffix )throws IOException{
CPUTMaterialDX11 pMaterial = new CPUTMaterialDX11();
pMaterial.LoadMaterial(absolutePathAndFilename, modelSuffix, meshSuffix);
// ASSERT( CPUTSUCCESS(result), _L("\nError - CPUTAssetLibrary::GetMaterial() - Error in material file: '")+absolutePathAndFilename+_L("'") );
// add material to material library list
// cString finalName = pMaterial->MaterialRequiresPerModelPayload() ? absolutePathAndFilename + modelSuffix + meshSuffix : absolutePathAndFilename;
// CPUTAssetLibrary::GetAssetLibrary()->AddMaterial( finalName, pMaterial );
// CPUTAssetLibrary::GetAssetLibrary()->AddMaterial( absolutePathAndFilename, pMaterial ); TODO
return pMaterial;
}
public static CPUTMaterial CreateMaterial(
String absolutePathAndFilename,
CPUTModel pModel,
int meshIndex,
Macro[] pShaderMacros, // Note: this is honored only on first load. Subsequent GetMaterial calls will return the material with shaders as compiled with original macros.
int numSystemMaterials,
String[] pSystemMaterialNames,
int externalCount,
String pExternalName,
Vector4f[] pExternals,
int[] pExternalOffset,
int[] pExternalSize
)throws IOException{
// Create the material and load it from file.
//#ifdef CPUT_FOR_DX11
// CPUTMaterial *pMaterial = new CPUTMaterialDX11();
//#elif (defined(CPUT_FOR_OGL) || defined(CPUT_FOR_OGLES))
// CPUTMaterial *pMaterial = new CPUTMaterialOGL();
//#else
// #error You must supply a target graphics API (ex: #define CPUT_FOR_DX11), or implement the target API for this file.
//#endif
// pMaterial->mpSubMaterials = NULL;
CPUTMaterial pMaterial = new CPUTMaterial();
pMaterial.LoadMaterial( absolutePathAndFilename, pModel, meshIndex, pShaderMacros, numSystemMaterials, pSystemMaterialNames, externalCount, pExternalName, pExternals, pExternalOffset, pExternalSize );
// ASSERT( CPUTSUCCESS(result), _L("\nError - CPUTAssetLibrary::GetMaterial() - Error in material file: '")+absolutePathAndFilename+_L("'") );
// UNREFERENCED_PARAMETER(result);
// Add the material to the asset library.
CPUTAssetLibrary.GetAssetLibrary().AddMaterial( absolutePathAndFilename, "", "", pMaterial, pShaderMacros, null,-1 );
return pMaterial;
}
private void LoadMaterial(String fileName, CPUTModel pModel, int meshIndex/*=-1*/,
Macro[] pShaderMacros, int systemMaterialCount, String []pSystemMaterialNames,
int externalCount, String pExternalName,Vector4f []pExternals,
int []pExternalOffset, int []pExternalSize)throws IOException{
mMaterialName = fileName;
// mMaterialNameHash = CPUTComputeHash( mMaterialName );
// Open/parse the file
CPUTConfigFile file = new CPUTConfigFile();
file.LoadFile(fileName);
// const char * tempfilename = fileName.c_str();
// Make a local copy of all the parameters
CPUTConfigBlock pBlock = file.GetBlock(0);
// ASSERT( pBlock, _L("Error getting parameter block") );
if( pBlock == null)
{
// return CPUT_ERROR_PARAMETER_BLOCK_NOT_FOUND;
throw new NullPointerException("Error getting parameter block");
}
mConfigBlock = pBlock;
CPUTAssetLibrary pAssetLibrary = CPUTAssetLibrary.GetAssetLibrary();
mMaterialEffectCount = 0;
if( mConfigBlock.GetValueByName("MultiMaterial" ).ValueAsBool() )
{
// Count materials;
for(;;)
{
CPUTConfigEntry pValue = mConfigBlock.GetValueByName( "Material" + mMaterialEffectCount );
if( pValue.IsValid() )
{
++mMaterialEffectCount;
} else
{
break;
}
}
assert mMaterialEffectCount != 0 : ("MultiMaterial specified, but no sub materials given.");
// Reserve space for "authored" materials plus system materials
mpMaterialEffectNames = new String[mMaterialEffectCount+systemMaterialCount];
int ii;
for( ii=0; ii<mMaterialEffectCount; ii++ )
{
CPUTConfigEntry pValue = mConfigBlock.GetValueByName( "Material" + ii );
mpMaterialEffectNames[ii] = pAssetLibrary.GetMaterialEffectPath(pValue.ValueAsString(), false);
}
}
else
{
mMaterialEffectCount = 1;
mpMaterialEffectNames = new String[mMaterialEffectCount+systemMaterialCount];
mpMaterialEffectNames[0] = fileName;
}
// The real material count includes the system material count
mMaterialEffectCount += systemMaterialCount;
for( int ii=0; ii<systemMaterialCount; ii++ )
{
// System materials "grow" from the end; the 1st system material is at the end of the list.
mpMaterialEffectNames[mMaterialEffectCount-systemMaterialCount+ii] = pSystemMaterialNames[ii];
}
mpMaterialEffects = new CPUTMaterialEffect[mMaterialEffectCount+1];
for( int ii=0; ii<mMaterialEffectCount; ii++ )
{
Macro [] pFinalShaderMacros = pShaderMacros;
Macro []pUserSpecifiedMacros = null;
int numUserSpecifiedMacros = 0;
// Read additional macros from .mtl file
String macroBlockName = "defines" + ii;
CPUTConfigBlock pMacrosBlock = file.GetBlockByName(macroBlockName);
if( pMacrosBlock != null)
{
List<Macro> userSpecifiedMacros = new ArrayList<>();
List<Macro> finalShaderMacros = new ArrayList<>();
ReadMacrosFromConfigBlock( pMacrosBlock, pShaderMacros, userSpecifiedMacros, /*&numUserSpecifiedMacros,*/ finalShaderMacros );
pUserSpecifiedMacros = userSpecifiedMacros.toArray(new Macro[userSpecifiedMacros.size()]);
pFinalShaderMacros = finalShaderMacros.toArray(new Macro[finalShaderMacros.size()]);
numUserSpecifiedMacros = pUserSpecifiedMacros.length;
}
mpMaterialEffects[ii] = pAssetLibrary.GetMaterialEffect( mpMaterialEffectNames[ii], true, pModel, meshIndex, pFinalShaderMacros );
for( int kk=0; kk<numUserSpecifiedMacros; kk++ )
{
// ReadMacrosFromConfigBlock allocates memory (ws2s does). Delete it here.
// SAFE_DELETE(pUserSpecifiedMacros[kk].Name);
// SAFE_DELETE(pUserSpecifiedMacros[kk].Definition);
}
// SAFE_DELETE_ARRAY( pFinalShaderMacros );
// SAFE_DELETE_ARRAY( pUserSpecifiedMacros );
}
mpMaterialEffects[mMaterialEffectCount] = null;
}
//-----------------------------------------------------------------------------
void ReadMacrosFromConfigBlock(
CPUTConfigBlock pMacrosBlock,
Macro[] pShaderMacros,
List<Macro> pUserSpecifiedMacros,
// int *pNumUserSpecifiedMacros,
List<Macro> pFinalShaderMacros
){
int pNumUserSpecifiedMacros = pMacrosBlock.ValueCount();
// Count the number of macros passed in
Macro[] pMacro = pShaderMacros;
int numPassedInMacros = 0;
if( pMacro != null && pMacro.length > 0)
{
while( !StringUtils.isBlank(pMacro[numPassedInMacros].key))
{
++numPassedInMacros;
// ++pMacro;
}
}
// Allocate an array of macro pointer large enough to contain the passed-in macros plus those specified in the .mtl file.
// *pFinalShaderMacros = new CPUT_SHADER_MACRO[*pNumUserSpecifiedMacros + numPassedInMacros + 1];
// Copy the passed-in macro pointers to the final array
int jj;
for( jj=0; jj<numPassedInMacros; jj++ )
{
// (*pFinalShaderMacros)[jj] = *(CPUT_SHADER_MACRO*)&pShaderMacros[jj];
pFinalShaderMacros.add(pShaderMacros[jj]);
}
// Create a CPUT_SHADER_MACRO for each of the macros specified in the .mtl file.
// And, add their pointers to the final array
// *pUserSpecifiedMacros = new CPUT_SHADER_MACRO[pNumUserSpecifiedMacros];
for( int kk=0; kk<pNumUserSpecifiedMacros; kk++, jj++ )
{
CPUTConfigEntry pValue = pMacrosBlock.GetValue(kk);
// (*pUserSpecifiedMacros)[kk].Name = ws2s(pValue->NameAsString());
// (*pUserSpecifiedMacros)[kk].Definition = ws2s(pValue->ValueAsString());
// (*pFinalShaderMacros)[jj] = (*pUserSpecifiedMacros)[kk];
Macro macro = new Macro(pValue.NameAsString(), pValue.ValueAsString());
pUserSpecifiedMacros.add(macro);
pFinalShaderMacros.add(macro);
}
// (*pFinalShaderMacros)[jj].Name = NULL;
// (*pFinalShaderMacros)[jj].Definition = NULL;
}
public void SetMaterialName(String MaterialName) { mMaterialName = MaterialName; }
public String GetMaterialName() {return mMaterialName; }
public CPUTMaterialEffect [] GetMaterialEffects() { return mpMaterialEffects; }
public int GetMaterialEffectCount() { return mMaterialEffectCount; }
public int GetCurrentEffect() { return mCurrentMaterialEffect; }
public void SetCurrentEffect(int CurrentMaterial) { mCurrentMaterialEffect = CurrentMaterial; }
public CPUTMaterial GetNextClone() { return mpMaterialNextClone; }
@Override
public void dispose() {
for(int ii = 0; ii < mMaterialEffectCount; ii++)
{
SAFE_RELEASE(mpMaterialEffects[ii]);
}
mpMaterialEffects = null;
}
}
| 11,993 | 0.633536 | 0.629451 | 262 | 44.774811 | 38.310089 | 208 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.763359 | false | false |
7
|
a87cebdadfa8d02ab4f53a9349743e6b59c4ada0
| 39,127,152,087,720 |
ff261e74d9fa974816c1e3c6cf59a3719d333f36
|
/my-web-service/src/com/server/MyService.java
|
29e8479b790e78710c9f347d044fb11df979ed03
|
[] |
no_license
|
zhangsikeke/springMVC
|
https://github.com/zhangsikeke/springMVC
|
d3765e34d2c17286c8c4e5902328b31cad534b01
|
44cc71e6d2edb8e37c4fea86ace107a92af4af42
|
refs/heads/master
| 2021-05-23T20:27:58.450000 | 2018-06-15T17:35:27 | 2018-06-15T17:35:27 | 63,601,276 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.server;
import java.io.File;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Endpoint;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.xml.internal.ws.developer.JAXWSProperties;
@WebService(targetNamespace = "http://service.zsk.com", serviceName = "MyService")
public class MyService
{
@Resource
private static WebServiceContext wsContext;
private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static
{
System.out.println(new File(MyService.class.getResource("/").getPath()).getParent());
}
@WebMethod(operationName = "showInfo")
@WebResult(name = "String")
public String getinfo(@WebParam(name = "name") String name)
{
getClientInfo();
return "you input is:" + name;
}
private void getClientInfo()
{
try
{
MessageContext mc = wsContext.getMessageContext();
//HttpExchange exchange = (HttpExchange) mc.get(JAXWSProperties.HTTP_EXCHANGE);
HttpServletRequest request=(HttpServletRequest)mc.get("javax.xml.ws.servlet.request");
String path=request.getSession().getServletContext().getRealPath("");
System.out.println(path);
File f=new File(path+"/WEB-INF/lib/dll/NppShell_05.dll");
if(f.exists())
{
System.out.println("dll exist");
}
else
{
System.out.println("dll not exist");
}
System.out.println(df.format(new Date())+" romote address:" + request.getRemoteAddr()+" port:"+request.getRemotePort());
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
Endpoint.publish("http://127.0.0.1:8080/server", new MyService());
System.out.println("·¢²¼³É¹¦");
}
}
|
WINDOWS-1252
|
Java
| 2,075 |
java
|
MyService.java
|
Java
|
[
{
"context": "in(String[] args)\r\n\t{\r\n\t\tEndpoint.publish(\"http://127.0.0.1:8080/server\", new MyService());\r\n\t\tSystem.out.pri",
"end": 1991,
"score": 0.9987254738807678,
"start": 1982,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null |
[] |
package com.server;
import java.io.File;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Endpoint;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.xml.internal.ws.developer.JAXWSProperties;
@WebService(targetNamespace = "http://service.zsk.com", serviceName = "MyService")
public class MyService
{
@Resource
private static WebServiceContext wsContext;
private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static
{
System.out.println(new File(MyService.class.getResource("/").getPath()).getParent());
}
@WebMethod(operationName = "showInfo")
@WebResult(name = "String")
public String getinfo(@WebParam(name = "name") String name)
{
getClientInfo();
return "you input is:" + name;
}
private void getClientInfo()
{
try
{
MessageContext mc = wsContext.getMessageContext();
//HttpExchange exchange = (HttpExchange) mc.get(JAXWSProperties.HTTP_EXCHANGE);
HttpServletRequest request=(HttpServletRequest)mc.get("javax.xml.ws.servlet.request");
String path=request.getSession().getServletContext().getRealPath("");
System.out.println(path);
File f=new File(path+"/WEB-INF/lib/dll/NppShell_05.dll");
if(f.exists())
{
System.out.println("dll exist");
}
else
{
System.out.println("dll not exist");
}
System.out.println(df.format(new Date())+" romote address:" + request.getRemoteAddr()+" port:"+request.getRemotePort());
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
Endpoint.publish("http://127.0.0.1:8080/server", new MyService());
System.out.println("·¢²¼³É¹¦");
}
}
| 2,075 | 0.69521 | 0.68747 | 77 | 24.844156 | 26.907763 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.727273 | false | false |
7
|
fe8a5722414a5504c35f8aee1ca42b45fed937b2
| 38,611,756,022,602 |
3662731c92f4b3b3503d2a472ec721e458ba516c
|
/provider/exoscale/src/main/java/com/opsbears/cscanner/exoscale/ExoscaleCloudProvider.java
|
634b67aeef93358184bc117a0fa5bee3e828a5f5
|
[
"Apache-2.0"
] |
permissive
|
mhmxs/cscanner
|
https://github.com/mhmxs/cscanner
|
a220a1376091714055159aabe0d2196200a43ef5
|
7e4179854ea195b526782a46ce3049c0d89e08ad
|
refs/heads/master
| 2020-05-17T13:46:19.421000 | 2019-04-30T12:34:05 | 2019-04-30T13:12:43 | 183,744,872 | 0 | 0 | null | true | 2019-04-27T07:55:53 | 2019-04-27T07:55:52 | 2019-04-17T07:11:15 | 2019-04-17T07:12:19 | 1,730 | 0 | 0 | 0 | null | false | false |
package com.opsbears.cscanner.exoscale;
import com.opsbears.cscanner.core.CloudProvider;
import com.opsbears.cscanner.core.HostDiscoveryCloudProvider;
import com.opsbears.cscanner.firewall.FirewallCloudProvider;
import com.opsbears.cscanner.objectstorage.ObjectStorageCloudProvider;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class ExoscaleCloudProvider implements
CloudProvider<ExoscaleConfiguration, ExoscaleConnection>,
HostDiscoveryCloudProvider<ExoscaleConfiguration, ExoscaleConnection>,
ObjectStorageCloudProvider<ExoscaleConfiguration, ExoscaleConnection>,
FirewallCloudProvider<ExoscaleConfiguration, ExoscaleConnection> {
@Override
public String getName() {
return "exoscale";
}
@Override
public Class<ExoscaleConfiguration> getConfigurationType() {
return ExoscaleConfiguration.class;
}
@Override
public Class<ExoscaleConnection> getConnectionType() {
return ExoscaleConnection.class;
}
@Override
public ExoscaleConnection getConnection(
String name,
ExoscaleConfiguration configuration
) {
return new ExoscaleConnection(name, configuration);
}
}
|
UTF-8
|
Java
| 1,230 |
java
|
ExoscaleCloudProvider.java
|
Java
|
[] | null |
[] |
package com.opsbears.cscanner.exoscale;
import com.opsbears.cscanner.core.CloudProvider;
import com.opsbears.cscanner.core.HostDiscoveryCloudProvider;
import com.opsbears.cscanner.firewall.FirewallCloudProvider;
import com.opsbears.cscanner.objectstorage.ObjectStorageCloudProvider;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class ExoscaleCloudProvider implements
CloudProvider<ExoscaleConfiguration, ExoscaleConnection>,
HostDiscoveryCloudProvider<ExoscaleConfiguration, ExoscaleConnection>,
ObjectStorageCloudProvider<ExoscaleConfiguration, ExoscaleConnection>,
FirewallCloudProvider<ExoscaleConfiguration, ExoscaleConnection> {
@Override
public String getName() {
return "exoscale";
}
@Override
public Class<ExoscaleConfiguration> getConfigurationType() {
return ExoscaleConfiguration.class;
}
@Override
public Class<ExoscaleConnection> getConnectionType() {
return ExoscaleConnection.class;
}
@Override
public ExoscaleConnection getConnection(
String name,
ExoscaleConfiguration configuration
) {
return new ExoscaleConnection(name, configuration);
}
}
| 1,230 | 0.781301 | 0.781301 | 38 | 31.368422 | 25.642708 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
7
|
22d2da1c6fb879a29b41bb9173983d6675d74f99
| 446,676,632,085 |
9179d25f0947e43a31ea153b7ab7f27a8318d56f
|
/src/org/aific/blogs/Blog.java
|
5c8b1f7fa47590316928f40b43116577d8589245
|
[] |
no_license
|
brainsqueezer/FeedParser
|
https://github.com/brainsqueezer/FeedParser
|
5949a4c7ed39e85a07016d6b3eb76be1336280cc
|
1348966fc73ee8c6ae1ea2f846a51da06f68e8a6
|
refs/heads/master
| 2021-01-10T22:07:59.562000 | 2011-06-14T10:45:00 | 2011-06-14T10:45:00 | 1,893,749 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.aific.blogs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Date;
public class Blog {
private URL url;
private Date lastUpdate;
//private String status;
private int failedAttemps = 0;
private long lastModified = 1;
public Blog(URL url) {
this.url = url;
}
public String toString() {
return url.toString();
}
public boolean update() {
if (failedAttemps < 5) {
StringBuffer input = new StringBuffer();
try {
URL updateURL = new URL("http://ramonantonio.net/updateblogs.php?url="+URLEncoder.encode(url.toString(), "UTF-8"));
URLConnection c = updateURL.openConnection();
c.setRequestProperty("User-agent", "G3Bot/0.5_(http://ramonantonio.net/g3/; robot)");
long _lastModified = c.getLastModified();
if (_lastModified == this.lastModified) {
System.out.println("Skipped: "+url.toString()+ " Modified: "+lastModified);
return true;
} else {
this.lastModified = _lastModified;
System.out.println("Updating: "+url.toString());
}
BufferedReader in;
in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
input.append(inputLine);
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException e) {
System.out.println(e);
failedAttemps++;
return false;
} catch (IOException e) {
System.out.println(e);
failedAttemps++;
return false;
}
lastUpdate = new Date(System.currentTimeMillis());
return true;
} else {
return false;
}
}
public Date getLastUpdate() {
return lastUpdate;
}
}
|
UTF-8
|
Java
| 1,882 |
java
|
Blog.java
|
Java
|
[] | null |
[] |
package org.aific.blogs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Date;
public class Blog {
private URL url;
private Date lastUpdate;
//private String status;
private int failedAttemps = 0;
private long lastModified = 1;
public Blog(URL url) {
this.url = url;
}
public String toString() {
return url.toString();
}
public boolean update() {
if (failedAttemps < 5) {
StringBuffer input = new StringBuffer();
try {
URL updateURL = new URL("http://ramonantonio.net/updateblogs.php?url="+URLEncoder.encode(url.toString(), "UTF-8"));
URLConnection c = updateURL.openConnection();
c.setRequestProperty("User-agent", "G3Bot/0.5_(http://ramonantonio.net/g3/; robot)");
long _lastModified = c.getLastModified();
if (_lastModified == this.lastModified) {
System.out.println("Skipped: "+url.toString()+ " Modified: "+lastModified);
return true;
} else {
this.lastModified = _lastModified;
System.out.println("Updating: "+url.toString());
}
BufferedReader in;
in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
input.append(inputLine);
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException e) {
System.out.println(e);
failedAttemps++;
return false;
} catch (IOException e) {
System.out.println(e);
failedAttemps++;
return false;
}
lastUpdate = new Date(System.currentTimeMillis());
return true;
} else {
return false;
}
}
public Date getLastUpdate() {
return lastUpdate;
}
}
| 1,882 | 0.655685 | 0.651435 | 76 | 23.763159 | 21.836636 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.789474 | false | false |
7
|
d8659e543d63b7ac4a91ac76553c1d851fb8148d
| 7,301,444,433,665 |
eb717113c7e3cb0f8a890c66437b79035ae31d47
|
/forge/mcp/src/minecraft/cr0s/WarpDrive/client/gui/GUIAirDistributor.java
|
0c5657370a4780e72a5731c66256e32fe9649570
|
[] |
no_license
|
AwesCorp/SpaceAge-1.6.4
|
https://github.com/AwesCorp/SpaceAge-1.6.4
|
9c49e589059efeb23aa84174312ec0ea9d53af76
|
d697761be7dc47443ede548da73137a671a13cbf
|
refs/heads/master
| 2021-01-19T00:16:21.356000 | 2015-01-19T10:37:29 | 2015-01-19T10:37:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cr0s.WarpDrive.client.gui;
import org.lwjgl.opengl.GL11;
import uedevkit.gui.GuiElectricBase;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.*;
import cr0s.WarpDrive.client.ClientProxy;
import cr0s.WarpDrive.common.container.ContainerAirDistributor;
import cr0s.WarpDrive.tile.TileEntityAirDistributor;
@SideOnly(Side.CLIENT)
public class GUIAirDistributor extends GuiElectricBase {
private static final ResourceLocation furnaceGuiTextures = new ResourceLocation(WarpDrive.modid + ":" + "textures/gui" + ClientProxy.guiAirGen);
private TileEntityAirDistributor furnaceInventory;
public GUIAirDistributor(InventoryPlayer player, TileEntityAirDistributor tile_entity) {
super(new ContainerAirDistributor(player, tile_entity));
this.furnaceInventory = tile_entity;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
String s = I18n.getString("airDistributor.name");
this.fontRenderer.drawString(s, this.xSize / 2 - this.fontRenderer.getStringWidth(s) / 2, 6, 4210752);
this.fontRenderer.drawString(I18n.getString("container.inventory"), 8, this.ySize - 96 + 2, 4210752);
if (this.isPointInRegion(161, 3, 8, 58, mouseX, mouseY)) {
this.drawTooltip(mouseX - this.guiLeft, mouseY - this.guiTop + 10, "Energy " + String.valueOf(this.furnaceInventory.getPowerRemainingScaled(100)) + " %");
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(furnaceGuiTextures);
int k = (this.width - this.xSize) / 2;
int l = (this.height - this.ySize) / 2;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize);
int i1;
int powerRemainingPercentage = this.furnaceInventory.getPowerRemainingScaled(58);
this.drawTexturedModalRect(k + 160, l + 10, 176, 0, 8, 58 - powerRemainingPercentage);
}
}
|
UTF-8
|
Java
| 2,237 |
java
|
GUIAirDistributor.java
|
Java
|
[] | null |
[] |
package cr0s.WarpDrive.client.gui;
import org.lwjgl.opengl.GL11;
import uedevkit.gui.GuiElectricBase;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import cr0s.WarpDrive.*;
import cr0s.WarpDrive.client.ClientProxy;
import cr0s.WarpDrive.common.container.ContainerAirDistributor;
import cr0s.WarpDrive.tile.TileEntityAirDistributor;
@SideOnly(Side.CLIENT)
public class GUIAirDistributor extends GuiElectricBase {
private static final ResourceLocation furnaceGuiTextures = new ResourceLocation(WarpDrive.modid + ":" + "textures/gui" + ClientProxy.guiAirGen);
private TileEntityAirDistributor furnaceInventory;
public GUIAirDistributor(InventoryPlayer player, TileEntityAirDistributor tile_entity) {
super(new ContainerAirDistributor(player, tile_entity));
this.furnaceInventory = tile_entity;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
String s = I18n.getString("airDistributor.name");
this.fontRenderer.drawString(s, this.xSize / 2 - this.fontRenderer.getStringWidth(s) / 2, 6, 4210752);
this.fontRenderer.drawString(I18n.getString("container.inventory"), 8, this.ySize - 96 + 2, 4210752);
if (this.isPointInRegion(161, 3, 8, 58, mouseX, mouseY)) {
this.drawTooltip(mouseX - this.guiLeft, mouseY - this.guiTop + 10, "Energy " + String.valueOf(this.furnaceInventory.getPowerRemainingScaled(100)) + " %");
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(furnaceGuiTextures);
int k = (this.width - this.xSize) / 2;
int l = (this.height - this.ySize) / 2;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize);
int i1;
int powerRemainingPercentage = this.furnaceInventory.getPowerRemainingScaled(58);
this.drawTexturedModalRect(k + 160, l + 10, 176, 0, 8, 58 - powerRemainingPercentage);
}
}
| 2,237 | 0.722843 | 0.687528 | 51 | 42.862743 | 38.539524 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.137255 | false | false |
7
|
026a34ab88f59c7e44aba9ec803a8052361562bd
| 19,396,072,338,273 |
4f9326a648a2a5e5a6dd29123ded49025d053908
|
/practice-world/src/com/compit/programming/basics/datatype/PrimitiveDataType.java
|
f1de9727006ecaf9e0457bcd3b1452ff7f6d6512
|
[] |
no_license
|
a0chaud/oli-oli
|
https://github.com/a0chaud/oli-oli
|
4f3bb24ddcefcfb5207926859c447c0483a2840e
|
79c20c692ae47a036ce8ec7b6914909a3933c3fb
|
refs/heads/master
| 2021-01-17T09:59:43.984000 | 2017-10-11T05:04:09 | 2017-10-11T05:04:09 | 58,517,980 | 0 | 1 | null | false | 2017-02-22T06:27:29 | 2016-05-11T05:56:49 | 2017-02-16T06:53:08 | 2017-02-22T06:27:29 | 17 | 0 | 1 | 0 |
Java
| null | null |
package com.compit.programming.basics.datatype;
/**
* @author: chaudharimehul
* @date: Apr 28, 2017
*
*
* Work on DataType
* Primitive
* byte, short, int, long, float, double, boolean
*
* https://en.wikibooks.org/wiki/Java_Programming/Primitive_Types
*
*
*/
public class PrimitiveDataType {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//byte - 8 bits - 1 Byte - -128 to 127 - 2^7 - 1 bit for +/-
//short - 16 bits - 2 Byte - -32,768 to 32,767 - 2^15 - 1 bit for +/-
//int - 32 bits - 4 Byte - -2,147,483,648 to 2,147,483, 647 - 2^31
//long - 64 bits - 8 Byte - -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 - 2^63
//float - 32 bits - 4 Byte
//double - 64 bits - 8 Bytes
//boolean - 1 bit -
//char - 16 bits - 2 Byte - 0 to 65,536
/*
* byte data type
*/
System.out.println("---------------------byte Data Type---------------------");
byte byteDataType = 127; //8 bits - 1 Byte
System.out.println("Byte Data Type " + byteDataType);
/*
* short data type
*/
System.out.println("---------------------short Data Type---------------------");
short shortDataType = 32000; //16 bits - 1 Byte
System.out.println(shortDataType);
shortDataType = byteDataType;
/*
* int data type
*/
System.out.println("---------------------int Data Type---------------------");
int intDataType = 10; //32 bits - 4 Byte
//Printing with two different format
System.out.println(intDataType);
System.out.printf("Printing with white space with s option %5s\n", intDataType); //It will print left adjust 5 space and print integer value
System.out.printf("printing with white space with d option %5d\n", intDataType); //Same as above
intDataType = '1'; // It will assign ascii value for char '1' to intger. Which is 49
char converFromIntToChar = (char) intDataType; //
System.out.println("int value " + intDataType); //this will print 49
System.out.println("char value " + converFromIntToChar); // this will print '1'
System.out.println("int converted to String " + String.valueOf(intDataType));
/*
* char data type
*/
System.out.println("---------------------char Data Type---------------------");
char charDataType = 'b';
System.out.println(charDataType);
System.out.printf("character printing %c",charDataType);
System.out.println("char converted to String "+String.valueOf(charDataType)); //It will print b, but as a String
System.out.printf("char converted to int %d \n", (int)charDataType); // It will print 98, ascii value of 'b'
/*
* float data type
*/
System.out.println("---------------------float Data Type---------------------");
float floatDataType = 10.4f;
System.out.println("Printing Float Data Type " + floatDataType);
System.out.printf("Printing Float Data Type with white space %5.2f \n ", floatDataType);
//floatDataType = charDataType;
/*
* double data type
*/
System.out.println("---------------------double Data Type---------------------");
double doubleDataType = 10.4;
System.out.println("Printing double data type " + doubleDataType);
System.out.printf("printing double data type with white space %20.5f \n" , doubleDataType);
/*
* boolean data type
*/
System.out.println("---------------------boolean Data Type---------------------");
boolean booleanDataType = true;
System.out.println("Printing boolean data type " + booleanDataType);
}
}
|
UTF-8
|
Java
| 3,520 |
java
|
PrimitiveDataType.java
|
Java
|
[
{
"context": "mpit.programming.basics.datatype;\n\n/**\n * @author: chaudharimehul\n * @date:\tApr 28, 2017\n * \n * \n * Work on DataTyp",
"end": 79,
"score": 0.9989979267120361,
"start": 65,
"tag": "NAME",
"value": "chaudharimehul"
}
] | null |
[] |
package com.compit.programming.basics.datatype;
/**
* @author: chaudharimehul
* @date: Apr 28, 2017
*
*
* Work on DataType
* Primitive
* byte, short, int, long, float, double, boolean
*
* https://en.wikibooks.org/wiki/Java_Programming/Primitive_Types
*
*
*/
public class PrimitiveDataType {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//byte - 8 bits - 1 Byte - -128 to 127 - 2^7 - 1 bit for +/-
//short - 16 bits - 2 Byte - -32,768 to 32,767 - 2^15 - 1 bit for +/-
//int - 32 bits - 4 Byte - -2,147,483,648 to 2,147,483, 647 - 2^31
//long - 64 bits - 8 Byte - -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 - 2^63
//float - 32 bits - 4 Byte
//double - 64 bits - 8 Bytes
//boolean - 1 bit -
//char - 16 bits - 2 Byte - 0 to 65,536
/*
* byte data type
*/
System.out.println("---------------------byte Data Type---------------------");
byte byteDataType = 127; //8 bits - 1 Byte
System.out.println("Byte Data Type " + byteDataType);
/*
* short data type
*/
System.out.println("---------------------short Data Type---------------------");
short shortDataType = 32000; //16 bits - 1 Byte
System.out.println(shortDataType);
shortDataType = byteDataType;
/*
* int data type
*/
System.out.println("---------------------int Data Type---------------------");
int intDataType = 10; //32 bits - 4 Byte
//Printing with two different format
System.out.println(intDataType);
System.out.printf("Printing with white space with s option %5s\n", intDataType); //It will print left adjust 5 space and print integer value
System.out.printf("printing with white space with d option %5d\n", intDataType); //Same as above
intDataType = '1'; // It will assign ascii value for char '1' to intger. Which is 49
char converFromIntToChar = (char) intDataType; //
System.out.println("int value " + intDataType); //this will print 49
System.out.println("char value " + converFromIntToChar); // this will print '1'
System.out.println("int converted to String " + String.valueOf(intDataType));
/*
* char data type
*/
System.out.println("---------------------char Data Type---------------------");
char charDataType = 'b';
System.out.println(charDataType);
System.out.printf("character printing %c",charDataType);
System.out.println("char converted to String "+String.valueOf(charDataType)); //It will print b, but as a String
System.out.printf("char converted to int %d \n", (int)charDataType); // It will print 98, ascii value of 'b'
/*
* float data type
*/
System.out.println("---------------------float Data Type---------------------");
float floatDataType = 10.4f;
System.out.println("Printing Float Data Type " + floatDataType);
System.out.printf("Printing Float Data Type with white space %5.2f \n ", floatDataType);
//floatDataType = charDataType;
/*
* double data type
*/
System.out.println("---------------------double Data Type---------------------");
double doubleDataType = 10.4;
System.out.println("Printing double data type " + doubleDataType);
System.out.printf("printing double data type with white space %20.5f \n" , doubleDataType);
/*
* boolean data type
*/
System.out.println("---------------------boolean Data Type---------------------");
boolean booleanDataType = true;
System.out.println("Printing boolean data type " + booleanDataType);
}
}
| 3,520 | 0.605682 | 0.559943 | 111 | 30.711712 | 33.276722 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.135135 | false | false |
7
|
820cd82af93347ff06ac1c5f1dfa53d76ce5e999
| 18,975,165,568,232 |
ecf06eacc4ec069e52b2a915fa397944ca9c6071
|
/src/test/java/web/servlet/ModelAndViewTest.java
|
919f0387b45e443faddad358fc2197d2404e1041
|
[] |
no_license
|
KingCjy/jwp-was
|
https://github.com/KingCjy/jwp-was
|
a55c55b610701e3f193ee1605d5af9f531f23075
|
d51895439224306fc257608b0d67398628b10751
|
refs/heads/master
| 2022-10-11T05:39:38.368000 | 2020-06-09T10:52:20 | 2020-06-09T10:52:20 | 268,527,834 | 0 | 0 | null | true | 2020-06-01T13:18:51 | 2020-06-01T13:18:50 | 2020-05-27T06:11:19 | 2020-06-01T13:14:55 | 926 | 0 | 0 | 0 | null | false | false |
package web.servlet;
import org.junit.jupiter.api.Test;
import java.util.AbstractMap;
import static org.assertj.core.api.Assertions.assertThat;
public class ModelAndViewTest {
@Test
public void initTest() {
ModelAndView modelAndView = ModelAndView.from("test_view");
modelAndView.addAttribute("message", "Hello World");
assertThat(modelAndView.getViewName()).isEqualTo("test_view");
assertThat(modelAndView.getModel()).contains(new AbstractMap.SimpleEntry("message", "Hello World"));
}
}
|
UTF-8
|
Java
| 538 |
java
|
ModelAndViewTest.java
|
Java
|
[] | null |
[] |
package web.servlet;
import org.junit.jupiter.api.Test;
import java.util.AbstractMap;
import static org.assertj.core.api.Assertions.assertThat;
public class ModelAndViewTest {
@Test
public void initTest() {
ModelAndView modelAndView = ModelAndView.from("test_view");
modelAndView.addAttribute("message", "Hello World");
assertThat(modelAndView.getViewName()).isEqualTo("test_view");
assertThat(modelAndView.getModel()).contains(new AbstractMap.SimpleEntry("message", "Hello World"));
}
}
| 538 | 0.719331 | 0.719331 | 19 | 27.31579 | 30.757202 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false |
7
|
92a8f9165c52612262b660baf4b0677e54eddad0
| 19,172,734,069,991 |
b6103cef8dc3cc2a8cffe7d2372fee6b232a7f2e
|
/src/org/slive/number/memory/action/HelpAction.java
|
c133661e011d7ef2cfddef5300c207fdca65cc26
|
[] |
no_license
|
Slive/numbermemory
|
https://github.com/Slive/numbermemory
|
7f142a7a12ce2a12c993771022a9ea2326b597e1
|
e87cdbb5c3a7b6e2f315fd79f33debc5422afc05
|
refs/heads/master
| 2016-09-09T23:56:52.942000 | 2016-03-08T14:29:27 | 2016-03-08T14:29:27 | 22,519,791 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* @author slive
* 2014-8-3 ÏÂÎç02:30:34
*/
package org.slive.number.memory.action;
import org.slive.number.memory.command.Command;
/**
* @author Administrator
*
*/
public class HelpAction extends DefaultAction
{
/**
* @see org.slive.number.memory.action.DefaultAction#excute()
*/
@Override
public Command excute()
{
StringBuilder sbd = new StringBuilder();
sbd.append(" Supporting command:" + EN);
sbd.append("\thelp,login,logout,start,stop,setting,exit");
writeLine(sbd.toString());
return nextDefCmd();
}
}
|
WINDOWS-1252
|
Java
| 548 |
java
|
HelpAction.java
|
Java
|
[
{
"context": "/**\n * @author slive\n * 2014-8-3 ÏÂÎç02:30:34\n */\npackage org.slive.nu",
"end": 20,
"score": 0.999640941619873,
"start": 15,
"tag": "USERNAME",
"value": "slive"
},
{
"context": "ive.number.memory.command.Command;\n\n/**\n * @author Administrator\n *\n */\npublic class HelpAction extends DefaultAct",
"end": 168,
"score": 0.7639109492301941,
"start": 155,
"tag": "USERNAME",
"value": "Administrator"
}
] | null |
[] |
/**
* @author slive
* 2014-8-3 ÏÂÎç02:30:34
*/
package org.slive.number.memory.action;
import org.slive.number.memory.command.Command;
/**
* @author Administrator
*
*/
public class HelpAction extends DefaultAction
{
/**
* @see org.slive.number.memory.action.DefaultAction#excute()
*/
@Override
public Command excute()
{
StringBuilder sbd = new StringBuilder();
sbd.append(" Supporting command:" + EN);
sbd.append("\thelp,login,logout,start,stop,setting,exit");
writeLine(sbd.toString());
return nextDefCmd();
}
}
| 548 | 0.691176 | 0.669118 | 27 | 19.148148 | 19.708437 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.074074 | false | false |
7
|
509b0d038c80431a25b2e99c4b9e0d0632822660
| 20,822,001,509,552 |
255b506a8d60c8cb13a0ef6b0050b172dbab20e9
|
/src/main/java/won/bot/skeleton/SkeletonBotApp.java
|
16497ec00d0b8120f82b607509825626837e032e
|
[
"Apache-2.0"
] |
permissive
|
WoN-Hackathon-2019/won-LocationInformationBot
|
https://github.com/WoN-Hackathon-2019/won-LocationInformationBot
|
c4a6b1185659c655cc218beda9240bb59feb58a9
|
d2e5c14d884728effc05a19014188a02d43a6cd7
|
refs/heads/master
| 2022-12-24T08:08:20.463000 | 2020-02-18T12:56:41 | 2020-02-18T12:56:41 | 228,345,654 | 0 | 0 |
Apache-2.0
| false | 2022-12-10T03:28:23 | 2019-12-16T09:05:31 | 2020-02-18T12:56:44 | 2022-12-10T03:28:22 | 752 | 0 | 0 | 4 |
Java
| false | false |
package won.bot.skeleton;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import won.bot.framework.bot.utils.BotUtils;
@SpringBootConfiguration
@PropertySource("classpath:application.properties")
@ImportResource("classpath:/spring/app/botApp.xml")
public class SkeletonBotApp {
public static void main(String[] args) throws Exception {
if (!BotUtils.isValidRunConfig()) {
System.exit(1);
}
SpringApplication app = new SpringApplication(SkeletonBotApp.class);
app.setWebEnvironment(false);
app.run(args);
// ConfigurableApplicationContext applicationContext = app.run(args);
// Thread.sleep(5*60*1000);
// app.exit(applicationContext);
}
}
|
UTF-8
|
Java
| 933 |
java
|
SkeletonBotApp.java
|
Java
|
[] | null |
[] |
package won.bot.skeleton;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import won.bot.framework.bot.utils.BotUtils;
@SpringBootConfiguration
@PropertySource("classpath:application.properties")
@ImportResource("classpath:/spring/app/botApp.xml")
public class SkeletonBotApp {
public static void main(String[] args) throws Exception {
if (!BotUtils.isValidRunConfig()) {
System.exit(1);
}
SpringApplication app = new SpringApplication(SkeletonBotApp.class);
app.setWebEnvironment(false);
app.run(args);
// ConfigurableApplicationContext applicationContext = app.run(args);
// Thread.sleep(5*60*1000);
// app.exit(applicationContext);
}
}
| 933 | 0.722401 | 0.713826 | 24 | 36.875 | 22.741871 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false |
7
|
26658dca9804522434d761094593c0ecd767bee4
| 1,202,590,867,467 |
decae3d24fa35709b3a49277af299c3b8af1230f
|
/src/main/java/com/lifecreations/controller/PermissionController.java
|
38ae01a6b4ebb95f5178bfb176a9d1b5fabb815c
|
[] |
no_license
|
lc153127245178/portalSpring
|
https://github.com/lc153127245178/portalSpring
|
c91b4118b61a7b0460cb44b0997746eaa49e177c
|
36be28580271f07ebaacd11fd2a47d7f38f60485
|
refs/heads/master
| 2017-12-16T23:31:57.632000 | 2017-04-20T06:36:12 | 2017-04-20T06:36:12 | 77,430,526 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lifecreations.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.lifecreations.dao.*;
import com.lifecreations.model.*;
@Controller
public class PermissionController {
@Autowired
PermissionDAO permissionDAO;
@Autowired
RoleDAO roleDAO;
@Autowired
FunctionDAO functionDAO;
@Autowired
TestPermission test;
@Autowired
HomeController home;
ModelAndView mv = new ModelAndView();
public List<Permission> listPermission;
public List<Role> listRole;
public List<Function> listFunction;
// GET ALL
@RequestMapping(value = "/permission", method = RequestMethod.GET)
public ModelAndView showAll(HttpServletRequest request) {
if (test.Test(request, "permission") == true) {
try {
listPermission = permissionDAO.findAll();
listRole = roleDAO.findByStatus(Byte.parseByte("0"));
listFunction = functionDAO.findByStatus(Byte.parseByte("0"));
mv.addObject("listPermission", listPermission);
mv.addObject("listRole", listRole);
mv.addObject("listFunction", listFunction);
mv.addObject("page", "permission.jsp");
mv.setViewName("layout");
} catch (Exception e) {
e.printStackTrace();
}
} else {
request.getSession().setAttribute("ERROR_MESSAGE", "セッションタイムアウト");
mv = home.login();
}
return mv;
}
// CREATE NEW
@RequestMapping(value = "/permission/create", method = RequestMethod.POST)
public ModelAndView createCustomer(@RequestParam String roleID, @RequestParam String functionID,
@RequestParam String status, HttpSession session, Model model) {
Permission permission = new Permission();
Role role = new Role();
Function function = new Function();
role.setRoleID(Integer.parseInt(roleID));
function.setFunctionID(Integer.parseInt(functionID));
System.out.println("TEST CONTROLLER 1");
if (permissionDAO.findByRoleAndFunction(role, function).size() == 0) {
System.out.println("TEST CONTROLLER 2 - 0");
permission.setRole(role);
permission.setFunction(function);
permission.setStatus(Byte.parseByte(status));
System.out.println("TEST CONTROLLER 3 - 0");
permissionDAO.save(permission);
} else {
System.out.println("LOI");
}
mv.setViewName("redirect:/permission");
return mv;
}
// EDIT
@RequestMapping(value = "/permission/edit", method = RequestMethod.POST)
public ModelAndView editCustomer(@RequestParam String permissionId, @RequestParam String roleID,
@RequestParam String functionID, @RequestParam String status) {
try {
Permission permission = permissionDAO.getOne(Integer.parseInt(permissionId));
if (permission != null) {
Role role = new Role();
Function function = new Function();
role.setRoleID(Integer.parseInt(roleID));
function.setFunctionID(Integer.parseInt(functionID));
permission.setRole(role);
permission.setFunction(function);
permissionDAO.save(permission);
}
} catch (Exception e) {
e.printStackTrace();
}
mv.setViewName("redirect:/permission");
return mv;
}
// DELETE
@RequestMapping(value = "/permission/delete", method = RequestMethod.POST)
public ModelAndView removeRole(@RequestParam("id") int permissionID) {
permissionDAO.delete(permissionID);
mv.setViewName("redirect:/permission");
return mv;
}
// TEST DATA
@RequestMapping(value = "/permission/testdata", method = RequestMethod.POST)
public ModelAndView test(@RequestParam(value = "permissionID[]") String[] permissionIDs,
@RequestParam(value = "status[]") String[] statuses) {
int value = 0;
System.out.println(permissionIDs.length);
System.out.println(statuses.length);
for (String status : statuses) {
System.out.println(status);
for (String permissionID : permissionIDs) {
try {
Permission permission = permissionDAO.getOne(Integer.parseInt(permissionID));
if (permission != null) {
permission.setStatus(Byte.parseByte(statuses[value]));
value++;
permissionDAO.save(permission);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
mv.setViewName("redirect:/permission");
return mv;
}
}
|
UTF-8
|
Java
| 4,539 |
java
|
PermissionController.java
|
Java
|
[] | null |
[] |
package com.lifecreations.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.lifecreations.dao.*;
import com.lifecreations.model.*;
@Controller
public class PermissionController {
@Autowired
PermissionDAO permissionDAO;
@Autowired
RoleDAO roleDAO;
@Autowired
FunctionDAO functionDAO;
@Autowired
TestPermission test;
@Autowired
HomeController home;
ModelAndView mv = new ModelAndView();
public List<Permission> listPermission;
public List<Role> listRole;
public List<Function> listFunction;
// GET ALL
@RequestMapping(value = "/permission", method = RequestMethod.GET)
public ModelAndView showAll(HttpServletRequest request) {
if (test.Test(request, "permission") == true) {
try {
listPermission = permissionDAO.findAll();
listRole = roleDAO.findByStatus(Byte.parseByte("0"));
listFunction = functionDAO.findByStatus(Byte.parseByte("0"));
mv.addObject("listPermission", listPermission);
mv.addObject("listRole", listRole);
mv.addObject("listFunction", listFunction);
mv.addObject("page", "permission.jsp");
mv.setViewName("layout");
} catch (Exception e) {
e.printStackTrace();
}
} else {
request.getSession().setAttribute("ERROR_MESSAGE", "セッションタイムアウト");
mv = home.login();
}
return mv;
}
// CREATE NEW
@RequestMapping(value = "/permission/create", method = RequestMethod.POST)
public ModelAndView createCustomer(@RequestParam String roleID, @RequestParam String functionID,
@RequestParam String status, HttpSession session, Model model) {
Permission permission = new Permission();
Role role = new Role();
Function function = new Function();
role.setRoleID(Integer.parseInt(roleID));
function.setFunctionID(Integer.parseInt(functionID));
System.out.println("TEST CONTROLLER 1");
if (permissionDAO.findByRoleAndFunction(role, function).size() == 0) {
System.out.println("TEST CONTROLLER 2 - 0");
permission.setRole(role);
permission.setFunction(function);
permission.setStatus(Byte.parseByte(status));
System.out.println("TEST CONTROLLER 3 - 0");
permissionDAO.save(permission);
} else {
System.out.println("LOI");
}
mv.setViewName("redirect:/permission");
return mv;
}
// EDIT
@RequestMapping(value = "/permission/edit", method = RequestMethod.POST)
public ModelAndView editCustomer(@RequestParam String permissionId, @RequestParam String roleID,
@RequestParam String functionID, @RequestParam String status) {
try {
Permission permission = permissionDAO.getOne(Integer.parseInt(permissionId));
if (permission != null) {
Role role = new Role();
Function function = new Function();
role.setRoleID(Integer.parseInt(roleID));
function.setFunctionID(Integer.parseInt(functionID));
permission.setRole(role);
permission.setFunction(function);
permissionDAO.save(permission);
}
} catch (Exception e) {
e.printStackTrace();
}
mv.setViewName("redirect:/permission");
return mv;
}
// DELETE
@RequestMapping(value = "/permission/delete", method = RequestMethod.POST)
public ModelAndView removeRole(@RequestParam("id") int permissionID) {
permissionDAO.delete(permissionID);
mv.setViewName("redirect:/permission");
return mv;
}
// TEST DATA
@RequestMapping(value = "/permission/testdata", method = RequestMethod.POST)
public ModelAndView test(@RequestParam(value = "permissionID[]") String[] permissionIDs,
@RequestParam(value = "status[]") String[] statuses) {
int value = 0;
System.out.println(permissionIDs.length);
System.out.println(statuses.length);
for (String status : statuses) {
System.out.println(status);
for (String permissionID : permissionIDs) {
try {
Permission permission = permissionDAO.getOne(Integer.parseInt(permissionID));
if (permission != null) {
permission.setStatus(Byte.parseByte(statuses[value]));
value++;
permissionDAO.save(permission);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
mv.setViewName("redirect:/permission");
return mv;
}
}
| 4,539 | 0.734116 | 0.732123 | 139 | 31.496403 | 23.969517 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.647482 | false | false |
7
|
731de3121506d80ad8c58406e97e6b13699ea8f6
| 12,395,275,662,649 |
e4fdcb602227224313607e5da9cf5e51d313bb3f
|
/src/main/java/com/wzy/design/pattern/creational/simplefactory/practice/Rectangle.java
|
d1bd5b74fc134c18ba2cadfe570ee9ec97cacf3b
|
[] |
no_license
|
KongXinYu/design-pattern
|
https://github.com/KongXinYu/design-pattern
|
3aafec8d5c1ba16e75ae301bd2c8d0f7d689d14e
|
600ffa41a67c5aee087b673e51eed033db484cc6
|
refs/heads/master
| 2023-05-31T23:46:27.026000 | 2021-07-01T02:41:15 | 2021-07-01T02:41:15 | 297,809,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wzy.design.pattern.creational.simplefactory.practice;
/**
* @description:
* @author: WuZY
* @time: 2021/4/26 0026
*/
public class Rectangle extends Graph{
@Override
public void draw() {
System.out.println("绘制长方形...");
}
@Override
public void erase() {
System.out.println("擦除长方形...");
}
}
|
UTF-8
|
Java
| 367 |
java
|
Rectangle.java
|
Java
|
[
{
"context": "actory.practice;\n\n/**\n * @description:\n * @author: WuZY\n * @time: 2021/4/26 0026\n */\npublic class Rectang",
"end": 104,
"score": 0.9958140254020691,
"start": 100,
"tag": "NAME",
"value": "WuZY"
}
] | null |
[] |
package com.wzy.design.pattern.creational.simplefactory.practice;
/**
* @description:
* @author: WuZY
* @time: 2021/4/26 0026
*/
public class Rectangle extends Graph{
@Override
public void draw() {
System.out.println("绘制长方形...");
}
@Override
public void erase() {
System.out.println("擦除长方形...");
}
}
| 367 | 0.610951 | 0.579251 | 19 | 17.263159 | 17.274387 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.157895 | false | false |
7
|
c9b5b50d5bf3219cd5e97a0f13982cd2418078af
| 7,739,531,079,982 |
92882b852648bdbefceef8673cf03fe23382198c
|
/hrms/src/main/java/kodlama/io/hrms/business/concretes/SkillManager.java
|
14f93582c46e8510046c2bbef6103b900021cd05
|
[] |
no_license
|
ozgeeodabass/hrmsbackend
|
https://github.com/ozgeeodabass/hrmsbackend
|
361bc5b57560dee4be8a9b5d0a67efd117578157
|
21d0c04d80e7fbb3556f8802a44f96c566bf10d3
|
refs/heads/master
| 2023-06-29T14:26:54.979000 | 2021-08-03T09:34:01 | 2021-08-03T09:34:01 | 371,777,264 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kodlama.io.hrms.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kodlama.io.hrms.business.abstracts.SkillService;
import kodlama.io.hrms.core.utilities.results.DataResult;
import kodlama.io.hrms.core.utilities.results.Result;
import kodlama.io.hrms.core.utilities.results.SuccessDataResult;
import kodlama.io.hrms.core.utilities.results.SuccessResult;
import kodlama.io.hrms.dataAccess.abstracts.SkillDao;
import kodlama.io.hrms.entities.Skill;
@Service
public class SkillManager implements SkillService {
private SkillDao skillDao;
@Autowired
public SkillManager(SkillDao skillDao) {
super();
this.skillDao = skillDao;
}
@Override
public Result add(Skill skill) {
this.skillDao.save(skill);
return new SuccessResult();
}
@Override
public Result addAll(List<Skill> skills) {
for (Skill skill : skills) {
this.skillDao.save(skill);
}
return new SuccessResult();
}
@Override
public Result delete(Skill skill) {
this.skillDao.delete(skill);
return new SuccessResult();
}
@Override
public Result update(Skill skill) {
this.skillDao.save(skill);
return new SuccessResult();
}
@Override
public DataResult<List<Skill>> getAllByCandidateId(int candidateId) {
return new SuccessDataResult<List<Skill>>(this.skillDao.getAllByCandidateId(candidateId));
}
}
|
UTF-8
|
Java
| 1,429 |
java
|
SkillManager.java
|
Java
|
[] | null |
[] |
package kodlama.io.hrms.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kodlama.io.hrms.business.abstracts.SkillService;
import kodlama.io.hrms.core.utilities.results.DataResult;
import kodlama.io.hrms.core.utilities.results.Result;
import kodlama.io.hrms.core.utilities.results.SuccessDataResult;
import kodlama.io.hrms.core.utilities.results.SuccessResult;
import kodlama.io.hrms.dataAccess.abstracts.SkillDao;
import kodlama.io.hrms.entities.Skill;
@Service
public class SkillManager implements SkillService {
private SkillDao skillDao;
@Autowired
public SkillManager(SkillDao skillDao) {
super();
this.skillDao = skillDao;
}
@Override
public Result add(Skill skill) {
this.skillDao.save(skill);
return new SuccessResult();
}
@Override
public Result addAll(List<Skill> skills) {
for (Skill skill : skills) {
this.skillDao.save(skill);
}
return new SuccessResult();
}
@Override
public Result delete(Skill skill) {
this.skillDao.delete(skill);
return new SuccessResult();
}
@Override
public Result update(Skill skill) {
this.skillDao.save(skill);
return new SuccessResult();
}
@Override
public DataResult<List<Skill>> getAllByCandidateId(int candidateId) {
return new SuccessDataResult<List<Skill>>(this.skillDao.getAllByCandidateId(candidateId));
}
}
| 1,429 | 0.772568 | 0.772568 | 60 | 22.816668 | 22.774614 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.216667 | false | false |
7
|
89aa43033602db84eb1be1a0e90ba402b3e7aec2
| 29,729,763,666,976 |
3a00c5f5f8ff0e1795c41e543ea2d01f395b6ab5
|
/camel-routes/jms-samples/src/main/java/de/stone/camel/configuration/DatasourceProducer.java
|
4c749760947bf6e08765a48875c2b57a6a9e900c
|
[] |
no_license
|
Stone2279/camel-samples
|
https://github.com/Stone2279/camel-samples
|
4a0e93ffc4062f73ddaec5ec0cab47b8542d6f0c
|
620cb59720ade4518e4aafe88ebf48b2d54a4db4
|
refs/heads/master
| 2020-04-17T12:22:45.156000 | 2019-02-16T09:14:49 | 2019-02-16T09:14:49 | 166,577,057 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.stone.camel.configuration;
import javax.annotation.Resource;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
import javax.sql.DataSource;
public class DatasourceProducer {
@Resource(lookup = "java:jboss/datasources/jms-samples/postgres-ds")
DataSource dataSource;
@Produces
@Named("postgres-ds")
public DataSource getDataSource()
{
return dataSource;
}
}
|
UTF-8
|
Java
| 435 |
java
|
DatasourceProducer.java
|
Java
|
[] | null |
[] |
package de.stone.camel.configuration;
import javax.annotation.Resource;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
import javax.sql.DataSource;
public class DatasourceProducer {
@Resource(lookup = "java:jboss/datasources/jms-samples/postgres-ds")
DataSource dataSource;
@Produces
@Named("postgres-ds")
public DataSource getDataSource()
{
return dataSource;
}
}
| 435 | 0.71954 | 0.71954 | 19 | 21.894737 | 18.850924 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false |
7
|
bc604d904a8a931bd24562db6132cfb714b3d1fb
| 22,600,117,961,269 |
42bf3ad9106c0c0bb14ea36d204cf8da0f016ac5
|
/src/main/java/com/hsy/hrxcy/testhrx/model/ChatInformation.java
|
df27138fbd4bfe8941051ecb2194f9d50cb4b819
|
[] |
no_license
|
HHHHsy/InstantMessaging-
|
https://github.com/HHHHsy/InstantMessaging-
|
c8cedb94dc716ae9d8db52e979ef09ea4814f385
|
f0b8f4c669ca427d21f4c0a9fd78b1f617a3ee90
|
refs/heads/master
| 2020-09-09T06:30:47.056000 | 2019-11-24T23:47:01 | 2019-11-24T23:47:01 | 221,375,518 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hsy.hrxcy.testhrx.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@EntityListeners(AuditingEntityListener.class)
//聊天信息表
public class ChatInformation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long informationid;
private Long fromidaid;
private Long toid;
private String content;
@CreatedDate
private LocalDateTime date;
}
|
UTF-8
|
Java
| 673 |
java
|
ChatInformation.java
|
Java
|
[] | null |
[] |
package com.hsy.hrxcy.testhrx.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@EntityListeners(AuditingEntityListener.class)
//聊天信息表
public class ChatInformation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long informationid;
private Long fromidaid;
private Long toid;
private String content;
@CreatedDate
private LocalDateTime date;
}
| 673 | 0.779789 | 0.779789 | 29 | 21.827587 | 18.651188 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false |
7
|
3187edf62330ee36c29e06ccd62356c1966a919a
| 8,727,373,572,153 |
49f33d3a8ebabcc16bfa18d6d4be455340f7a0e3
|
/src/com/remindme/ui/SpinnerRepeat.java
|
a98d705a569cbd2b2ea50da810be69e037980880
|
[] |
no_license
|
GitSioke/RemindMee
|
https://github.com/GitSioke/RemindMee
|
342340312cd4b7021470e4077d230ab94e9d297d
|
7b4ab3410f703040203d599cdcf3dc9958543c86
|
refs/heads/master
| 2021-01-10T17:43:24.878000 | 2013-11-18T15:49:07 | 2013-11-18T15:49:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.remindme.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
public class SpinnerRepeat extends Spinner implements OnItemSelectedListener{
public SpinnerRepeat(Context context,AttributeSet attb)
{
super(context,attb);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id)
{
parent.getItemAtPosition(pos);
TextView selectedText = (TextView) parent.getChildAt(0);
selectedText.setTextColor(getResources().getColor(R.color.newedit_normalText));
selectedText.setTextSize(getResources().getDimension(R.dimen.new_textSpinner));
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
UTF-8
|
Java
| 859 |
java
|
SpinnerRepeat.java
|
Java
|
[] | null |
[] |
package com.remindme.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
public class SpinnerRepeat extends Spinner implements OnItemSelectedListener{
public SpinnerRepeat(Context context,AttributeSet attb)
{
super(context,attb);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id)
{
parent.getItemAtPosition(pos);
TextView selectedText = (TextView) parent.getChildAt(0);
selectedText.setTextColor(getResources().getColor(R.color.newedit_normalText));
selectedText.setTextSize(getResources().getDimension(R.dimen.new_textSpinner));
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
| 859 | 0.788126 | 0.786962 | 33 | 25.030304 | 26.974157 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false |
7
|
d5ae3a444b9e0e4726c88bcc86e006d025756f47
| 14,869,176,807,157 |
a087107e88b7827efbaeda73c065d0520020efbe
|
/src/src/test/java/com/github/visgeek/utils/collections/test/testcase/collection/list/enumerablelist/Constructor.java
|
44c3bbfe37c2b0902984e6911a03f162186cf0f0
|
[
"MIT"
] |
permissive
|
visGeek/JavaVisGeekCollections
|
https://github.com/visGeek/JavaVisGeekCollections
|
bd2dd94b7e6aec1b69649512579c77d7f2b73d8f
|
9ffa6736e4f076f7667126bcd0eac54b6bc6fae5
|
refs/heads/master
| 2016-09-14T14:56:30.166000 | 2016-05-17T09:27:00 | 2016-05-17T09:27:00 | 58,067,761 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.visgeek.utils.collections.test.testcase.collection.list.enumerablelist;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.visgeek.utils.collections.EnumerableList;
import com.github.visgeek.utils.testing.Assert2;
public class Constructor {
@Rule
public final ExpectedException expectedException = ExpectedException.none();
@Test
public void noArgs() {
EnumerableList<Integer> actual = new EnumerableList<>(1, 2, 3);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void collectionNullArg() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage("collection");
Collection<Integer> collection = null;
new EnumerableList<>(collection);
}
@Test
public void collection() {
Collection<Integer> values = Arrays.asList(1, 2, 3);
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void iterableNullArg() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage("collection");
Iterable<Integer> collection = null;
new EnumerableList<>(collection);
}
@Test
public void iterable_Collection() {
Iterable<Integer> values = Arrays.asList(1, 2, 3);
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void iterable_Iterable() {
Iterable<Integer> values = () -> Arrays.asList(1, 2, 3).iterator();
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void arrayNullArg() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage("values");
Integer[] collection = null;
new EnumerableList<>(collection);
}
@Test
public void array() {
Integer[] values = new Integer[] { 1, 2, 3 };
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void capacity() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
EnumerableList<Integer> list = new EnumerableList<>(3);
int actual = getCapacity(list);
Assert.assertEquals(actual, 3);
}
static int getCapacity(ArrayList<?> list) {
try {
// リフレクションで無理矢理キャパシティを取得する。
Field field = ArrayList.class.getDeclaredField("elementData");
field.setAccessible(true);
Object[] elementData = (Object[]) field.get(list);
return elementData.length;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
UTF-8
|
Java
| 2,883 |
java
|
Constructor.java
|
Java
|
[
{
"context": "it.rules.ExpectedException;\n\nimport com.github.visgeek.utils.collections.EnumerableList;\nimport com.gith",
"end": 346,
"score": 0.5915025472640991,
"start": 342,
"tag": "USERNAME",
"value": "geek"
}
] | null |
[] |
package com.github.visgeek.utils.collections.test.testcase.collection.list.enumerablelist;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.visgeek.utils.collections.EnumerableList;
import com.github.visgeek.utils.testing.Assert2;
public class Constructor {
@Rule
public final ExpectedException expectedException = ExpectedException.none();
@Test
public void noArgs() {
EnumerableList<Integer> actual = new EnumerableList<>(1, 2, 3);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void collectionNullArg() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage("collection");
Collection<Integer> collection = null;
new EnumerableList<>(collection);
}
@Test
public void collection() {
Collection<Integer> values = Arrays.asList(1, 2, 3);
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void iterableNullArg() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage("collection");
Iterable<Integer> collection = null;
new EnumerableList<>(collection);
}
@Test
public void iterable_Collection() {
Iterable<Integer> values = Arrays.asList(1, 2, 3);
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void iterable_Iterable() {
Iterable<Integer> values = () -> Arrays.asList(1, 2, 3).iterator();
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void arrayNullArg() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage("values");
Integer[] collection = null;
new EnumerableList<>(collection);
}
@Test
public void array() {
Integer[] values = new Integer[] { 1, 2, 3 };
EnumerableList<Integer> actual = new EnumerableList<>(values);
Assert2.assertSequanceEquals(actual, 1, 2, 3);
}
@Test
public void capacity() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
EnumerableList<Integer> list = new EnumerableList<>(3);
int actual = getCapacity(list);
Assert.assertEquals(actual, 3);
}
static int getCapacity(ArrayList<?> list) {
try {
// リフレクションで無理矢理キャパシティを取得する。
Field field = ArrayList.class.getDeclaredField("elementData");
field.setAccessible(true);
Object[] elementData = (Object[]) field.get(list);
return elementData.length;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 2,883 | 0.744268 | 0.730864 | 104 | 26.259615 | 25.468304 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.807692 | false | false |
7
|
78f1f9dab934dfa12897251d56cbdd48c3cff9a7
| 5,858,335,443,913 |
2f8cea9ee616d144be4597ec770095aeb3081147
|
/app/src/main/java/com/example/machenike/treasure8/treatrue/hide/HideTreasureView.java
|
d871a4fc801a622dc0b788a7d3a9ecd3007f3ca9
|
[] |
no_license
|
jthug/Treasure8
|
https://github.com/jthug/Treasure8
|
5a6cdf9177184626a227f2bdccdfa449608fc8bf
|
d2bc107d6825488aad9fe644278ab16dd5d1fd5e
|
refs/heads/master
| 2018-02-09T10:42:50.899000 | 2017-07-21T04:59:05 | 2017-07-21T04:59:05 | 96,723,892 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.machenike.treasure8.treatrue.hide;
/**
* Created by MACHENIKE on 2017/7/19.
*
* 埋藏宝藏的视图接口
*/
public interface HideTreasureView {
void showMessage(String message);//显示信息
void navigateToHomeActivity(); //跳转到HomeActivity
void showProgress();//展示进度条
void hideProgress(); //隐藏进度条
}
|
UTF-8
|
Java
| 375 |
java
|
HideTreasureView.java
|
Java
|
[
{
"context": "henike.treasure8.treatrue.hide;\n\n/**\n * Created by MACHENIKE on 2017/7/19.\n *\n * 埋藏宝藏的视图接口\n */\n\npublic interfa",
"end": 83,
"score": 0.9278867840766907,
"start": 74,
"tag": "USERNAME",
"value": "MACHENIKE"
}
] | null |
[] |
package com.example.machenike.treasure8.treatrue.hide;
/**
* Created by MACHENIKE on 2017/7/19.
*
* 埋藏宝藏的视图接口
*/
public interface HideTreasureView {
void showMessage(String message);//显示信息
void navigateToHomeActivity(); //跳转到HomeActivity
void showProgress();//展示进度条
void hideProgress(); //隐藏进度条
}
| 375 | 0.708978 | 0.684211 | 18 | 16.944445 | 19.786282 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false |
7
|
fafe11312b0bacc84fb9bf52b3b92deba3ac5335
| 17,918,603,591,702 |
fd22d2719804750410bc1e569839c7b9993fec17
|
/android/Memoling/src/app/memoling/android/webservice/helper/PublishedMemoUpload.java
|
6f1e5294fe13fecae9d18acd5d961cbb4301c730
|
[] |
no_license
|
interjaz/Memoling
|
https://github.com/interjaz/Memoling
|
5aa81f45dc61ab2f88041e0fac5a639a12207539
|
736056f32922f6b5454c780963d6f7dfa9d8da59
|
refs/heads/master
| 2021-01-10T10:21:49.716000 | 2016-02-14T16:54:19 | 2016-02-14T16:54:19 | 51,702,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package app.memoling.android.webservice.helper;
import java.util.UUID;
import app.memoling.android.adapter.MemoAdapter;
import app.memoling.android.entity.Memo;
import app.memoling.android.entity.PublishedMemo;
import app.memoling.android.facebook.FacebookUser;
import app.memoling.android.facebook.FacebookWrapper.IFacebookGetUserComplete;
import app.memoling.android.ui.FacebookFragment;
import app.memoling.android.webservice.WsFacebookUsers;
import app.memoling.android.webservice.WsFacebookUsers.ILoginComplete;
import app.memoling.android.webservice.WsPublishedLibraries;
import app.memoling.android.webservice.WsPublishedLibraries.IUploadMemoShareComplete;
public class PublishedMemoUpload {
private FacebookFragment m_facebookFragment;
private PublishedMemo m_published;
private IPublishedMemoUpload m_publishedMemoUploadInterface;
public static interface IPublishedMemoUpload {
void onSuccess(String url);
void onException(Exception ex);
}
public static class ExceptionReasons {
public final static String NoMemoToUpload = "NoMemoToUpload";
public final static String WsAuthError = "WsAuthError";
public final static String WsUploadError = "WsUploadError";
public final static String Generic = "Generic";
}
public PublishedMemoUpload(FacebookFragment facebookFragment, IPublishedMemoUpload publishedMemoUpload) {
m_facebookFragment = facebookFragment;
m_publishedMemoUploadInterface = publishedMemoUpload;
}
public void upload(final String memoId) {
m_facebookFragment.getFacebookUser(new IFacebookGetUserComplete() {
@Override
public void onGetUserComplete(FacebookUser user) {
m_published = new PublishedMemo();
m_published.setPublishedMemoId(UUID.randomUUID().toString());
m_published.setMemoId(memoId);
MemoAdapter memoAdapter = new MemoAdapter(m_facebookFragment.getActivity());
Memo memo = memoAdapter.getDeep(m_published.getMemoId());
if (memo == null) {
m_publishedMemoUploadInterface.onException(new Exception(ExceptionReasons.NoMemoToUpload));
return;
}
m_published.setMemo(memo);
m_published.setFacebookUserId(user.getId());
loginWs(user);
}
});
}
private void loginWs(FacebookUser user) {
WsFacebookUsers.login(user, new ILoginComplete() {
@Override
public void onLoginComplete(Boolean result) {
if (result != true) {
// forward exception
m_publishedMemoUploadInterface.onException(new Exception(ExceptionReasons.WsAuthError));
return;
}
uploadContent();
}
});
}
private void uploadContent() {
WsPublishedLibraries.uploadMemoShare(m_published, new IUploadMemoShareComplete() {
@Override
public void onUploadMemoShareComplete(boolean result, String url) {
if (result != true) {
// forward exception
m_publishedMemoUploadInterface.onException(new Exception(ExceptionReasons.WsUploadError));
return;
}
complete(url);
}
});
}
private void complete(String url) {
m_publishedMemoUploadInterface.onSuccess(url);
}
}
|
UTF-8
|
Java
| 3,031 |
java
|
PublishedMemoUpload.java
|
Java
|
[] | null |
[] |
package app.memoling.android.webservice.helper;
import java.util.UUID;
import app.memoling.android.adapter.MemoAdapter;
import app.memoling.android.entity.Memo;
import app.memoling.android.entity.PublishedMemo;
import app.memoling.android.facebook.FacebookUser;
import app.memoling.android.facebook.FacebookWrapper.IFacebookGetUserComplete;
import app.memoling.android.ui.FacebookFragment;
import app.memoling.android.webservice.WsFacebookUsers;
import app.memoling.android.webservice.WsFacebookUsers.ILoginComplete;
import app.memoling.android.webservice.WsPublishedLibraries;
import app.memoling.android.webservice.WsPublishedLibraries.IUploadMemoShareComplete;
public class PublishedMemoUpload {
private FacebookFragment m_facebookFragment;
private PublishedMemo m_published;
private IPublishedMemoUpload m_publishedMemoUploadInterface;
public static interface IPublishedMemoUpload {
void onSuccess(String url);
void onException(Exception ex);
}
public static class ExceptionReasons {
public final static String NoMemoToUpload = "NoMemoToUpload";
public final static String WsAuthError = "WsAuthError";
public final static String WsUploadError = "WsUploadError";
public final static String Generic = "Generic";
}
public PublishedMemoUpload(FacebookFragment facebookFragment, IPublishedMemoUpload publishedMemoUpload) {
m_facebookFragment = facebookFragment;
m_publishedMemoUploadInterface = publishedMemoUpload;
}
public void upload(final String memoId) {
m_facebookFragment.getFacebookUser(new IFacebookGetUserComplete() {
@Override
public void onGetUserComplete(FacebookUser user) {
m_published = new PublishedMemo();
m_published.setPublishedMemoId(UUID.randomUUID().toString());
m_published.setMemoId(memoId);
MemoAdapter memoAdapter = new MemoAdapter(m_facebookFragment.getActivity());
Memo memo = memoAdapter.getDeep(m_published.getMemoId());
if (memo == null) {
m_publishedMemoUploadInterface.onException(new Exception(ExceptionReasons.NoMemoToUpload));
return;
}
m_published.setMemo(memo);
m_published.setFacebookUserId(user.getId());
loginWs(user);
}
});
}
private void loginWs(FacebookUser user) {
WsFacebookUsers.login(user, new ILoginComplete() {
@Override
public void onLoginComplete(Boolean result) {
if (result != true) {
// forward exception
m_publishedMemoUploadInterface.onException(new Exception(ExceptionReasons.WsAuthError));
return;
}
uploadContent();
}
});
}
private void uploadContent() {
WsPublishedLibraries.uploadMemoShare(m_published, new IUploadMemoShareComplete() {
@Override
public void onUploadMemoShareComplete(boolean result, String url) {
if (result != true) {
// forward exception
m_publishedMemoUploadInterface.onException(new Exception(ExceptionReasons.WsUploadError));
return;
}
complete(url);
}
});
}
private void complete(String url) {
m_publishedMemoUploadInterface.onSuccess(url);
}
}
| 3,031 | 0.771363 | 0.771363 | 102 | 28.715687 | 28.413397 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.205882 | false | false |
7
|
69f11909c1a4cef3b2672fa2e2988a4ea3230620
| 21,912,923,173,752 |
c70cc44001229b555c06d3e0ac0925a74d69e138
|
/app/src/main/java/com/tencent/moonsandbox/MoonApplication.java
|
e099f4fb59c24e1e115557c6dcfa23e34b0344c7
|
[] |
no_license
|
powerolive2019/shahe
|
https://github.com/powerolive2019/shahe
|
5fc9309f0268110c225f566fbc7a37b3ca54da21
|
92f1f2f9a671ed03a9a8eae501782b41da1fcf0b
|
refs/heads/master
| 2020-09-10T09:03:51.854000 | 2017-03-20T06:39:21 | 2017-03-20T06:39:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tencent.moonsandbox;
import android.app.Application;
import android.content.Intent;
import android.widget.Toast;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.core.ILiveLoginManager;
import com.tencent.ilivesdk.core.ILiveRoomConfig;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.moonsandbox.model.MoonConstants;
import com.tencent.moonsandbox.model.UserInfo;
import com.tencent.moonsandbox.utils.MLog;
/**
* Created by xkazerzhang on 2016/8/24.
*/
public class MoonApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ILiveSDK.getInstance().initSdk(getApplicationContext(), MoonConstants.SDK_APPID, MoonConstants.ACCOUNT_TYPE);
ILiveRoomManager.getInstance().init(new ILiveRoomConfig());
MLog.setLogLevel(MLog.SxbLogLevel.DEBUG);
ILiveLoginManager.getInstance().setUserStatusListener(new ILiveLoginManager.TILVBStatusListener() {
@Override
public void onForceOffline(int error, String message) {
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.tip_force_offline), Toast.LENGTH_SHORT).show();
// 清除用户信息
UserInfo.getInstance().clearCache(getApplicationContext());
getApplicationContext().sendBroadcast(new Intent(MoonConstants.BD_EXIT_APP));
}
});
}
}
|
UTF-8
|
Java
| 1,456 |
java
|
MoonApplication.java
|
Java
|
[
{
"context": "tencent.moonsandbox.utils.MLog;\n\n/**\n * Created by xkazerzhang on 2016/8/24.\n */\n\npublic class MoonApplication e",
"end": 490,
"score": 0.9996882081031799,
"start": 479,
"tag": "USERNAME",
"value": "xkazerzhang"
}
] | null |
[] |
package com.tencent.moonsandbox;
import android.app.Application;
import android.content.Intent;
import android.widget.Toast;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.core.ILiveLoginManager;
import com.tencent.ilivesdk.core.ILiveRoomConfig;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.moonsandbox.model.MoonConstants;
import com.tencent.moonsandbox.model.UserInfo;
import com.tencent.moonsandbox.utils.MLog;
/**
* Created by xkazerzhang on 2016/8/24.
*/
public class MoonApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ILiveSDK.getInstance().initSdk(getApplicationContext(), MoonConstants.SDK_APPID, MoonConstants.ACCOUNT_TYPE);
ILiveRoomManager.getInstance().init(new ILiveRoomConfig());
MLog.setLogLevel(MLog.SxbLogLevel.DEBUG);
ILiveLoginManager.getInstance().setUserStatusListener(new ILiveLoginManager.TILVBStatusListener() {
@Override
public void onForceOffline(int error, String message) {
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.tip_force_offline), Toast.LENGTH_SHORT).show();
// 清除用户信息
UserInfo.getInstance().clearCache(getApplicationContext());
getApplicationContext().sendBroadcast(new Intent(MoonConstants.BD_EXIT_APP));
}
});
}
}
| 1,456 | 0.724377 | 0.719529 | 39 | 36.025642 | 34.903152 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false |
7
|
84a2e27f8d056f1733f75a68c9cc6ea7657e6e7f
| 32,530,082,354,298 |
3a1906577f51eeaad7957f84dba242b662d23ab6
|
/src/test/java/maps/StatusMap.java
|
30bf475f0ba63c6edfed1ccf06f569d88265c184
|
[] |
no_license
|
luiz-cp07/candidaturaBancoTalentos
|
https://github.com/luiz-cp07/candidaturaBancoTalentos
|
6d7c0a5fe051569413e4254c2989f7ec5c3cd924
|
93fbeb4c9acb61a45800057da5c9a514f42c7552
|
refs/heads/master
| 2023-07-01T14:21:03.737000 | 2021-08-01T18:53:18 | 2021-08-01T18:53:18 | 391,199,360 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package maps;
|
UTF-8
|
Java
| 16 |
java
|
StatusMap.java
|
Java
|
[] | null |
[] |
package maps;
| 16 | 0.6875 | 0.6875 | 1 | 13 | 0 | 13 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
7
|
a5cf6149821bd5efb1b686634ce112345df84562
| 34,136,400,086,456 |
756c7b20518595011befb1c3631da8645e8dab37
|
/src/main/java/program7/Page.java
|
7b2d1e0e93aa7b62d3b470359ecdb523fcdeff56
|
[] |
no_license
|
Traple/TableExtraction
|
https://github.com/Traple/TableExtraction
|
9d86030c92766310c7cd8482b26089678550cf6c
|
39102641398c16d981e334afbbb1eb290d2f903f
|
refs/heads/master
| 2020-05-19T16:24:18.290000 | 2014-05-09T14:16:22 | 2014-05-09T14:16:22 | 13,798,940 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package program7;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;
/*
* The Page class is simply the page as it is being read by the main class. As soon as it detects a table it
* will create a Table2 class. It will parse the Table2 class it's own attributes to make sure the table can search in it's
* Location etc.
*/
public class Page {
private final boolean debugging;
private Elements spans;
private String workLocation;
private File file;
private double spaceDistance;
private double lineDistance;
public static Logger LOGGER = Logger.getLogger(Page.class.getName());
/**
* The constructor of this class sets the local variables for this class and creates a Jsoup document.
* @param file The HTML file created by the OCR.
* @param workLocation The work location as specified by the user.
* @param debugging if the program is in debugging mode.
* @throws java.io.IOException
*/
public Page(File file, String workLocation, boolean debugging) throws IOException {
Document doc = Jsoup.parse(file, "UTF-8", "http://example.com/");
this.spans = doc.select("span.ocrx_word");
this.workLocation = workLocation;
this.file = file;
this.spaceDistance = findSpaceDistance();
this.debugging = debugging;
setLineDistance();
LOGGER.info("The found average length of a character is: " + getSpaceDistance());
LOGGER.info("The found average distance between lines is: " +getLineDistance());
}
/**
* This method will find the tables in the content. It creates a table object for every table it finds.
* Do note that it creates a substring of the span(word) it finds. So if it finds <span>(table</span> it will not be detected.
* This has been done to reduce the amount of false positives (for referring to a table in the text).
* @param horizontalThresholdModifier The horizontal Threshold modifier.
* @param verticalThresholdModifier The vertical threshold modifier.
* @return The Table2 object. This method returns an empty list if no table was found.
* @throws java.io.IOException
*/
public ArrayList<Table2> createTables(double horizontalThresholdModifier, double verticalThresholdModifier) throws IOException {
String word;
boolean foundATable = false;
Elements tableSpans = new Elements();
ArrayList<Table2> foundTables = new ArrayList<Table2>();
int tableID = 0;
for (Element span : spans) {
word = span.text();
try {
if(word.substring(0, 5).equals("TABLE") || word.substring(0, 5).equals("table") || word.substring(0, 5).equals("Table")&&foundATable){
foundTables.add(new Table2(tableSpans, spaceDistance, file, workLocation, tableID, verticalThresholdModifier, horizontalThresholdModifier, lineDistance, debugging)); //make a new table from the collected spans
tableSpans = new Elements(); //reset the spans for the new Table2
tableSpans.add(span);
}
else if (foundATable) {
tableSpans.add(span);
}
if (word.substring(0, 5).equals("TABLE") || word.substring(0, 5).equals("table") || word.substring(0, 5).equals("Table")&&!foundATable) {
foundATable = true;
tableSpans.add(span);
}
} catch (StringIndexOutOfBoundsException e) {
if (foundATable) {
tableSpans.add(span);
}
}
tableID++;
}
if (foundATable) {
foundTables.add(new Table2(tableSpans, spaceDistance, file, workLocation, tableID, verticalThresholdModifier, horizontalThresholdModifier, lineDistance, debugging));
}
if(!foundATable){
LOGGER.info("There was no table found. ");
}
return foundTables;
}
/**
* This method tries to find the average space/distance of a character in a table. This can be used to determine
* the columns in a table.
* @return the average distance/space of a character.
*/
private double findSpaceDistance(){
double totalCharLength = 0.0;
for(Element span : spans){
String pos = span.attr("title");
String[] positions = pos.split("\\s+");
String word = span.text();
int X1 = Integer.parseInt(positions[1]);
int X2 = Integer.parseInt(positions[3]);
int length = X2 -X1;
if(word.length() > 0){
double charLength = length/word.length();
totalCharLength = totalCharLength + charLength;
}
}
return totalCharLength/spans.size();
}
/**
* This method sets the average distance between lines. First it creates lines using the second constructor of the Line
* class, then it calculates the distances between them.
*/
private void setLineDistance(){
double lineDistance;
String pos;
String[] positions;
int lastX2 = 0;
Elements currentLine = new Elements();
ArrayList<Line> lines = new ArrayList<Line>();
for(Element span : spans){
pos = span.attr("title");
positions = pos.split("\\s+");
int x1 = Integer.parseInt(positions[1]);
int x2 = Integer.parseInt(positions[3]);
if(!(x1>=lastX2)){
Line line = new Line(currentLine);
lines.add(line);
currentLine = new Elements();
}
lastX2 = x2;
currentLine.add(span);
}
double lastY2 = 0.0;
double totalDistance = 0.0;
for(Line line : lines){
if(lines.indexOf(line) == 0){
lastY2 = line.getAverageY2();
continue;
}
double distance = CommonMethods.calcDistance(lastY2 , line.getAverageY1());
totalDistance += distance;
lastY2 = line.getAverageY2();
}
lineDistance = totalDistance/lines.size();
this.lineDistance = lineDistance;
}
public double getSpaceDistance(){
return spaceDistance;
}
public double getLineDistance(){
return lineDistance;
}
}
|
UTF-8
|
Java
| 6,647 |
java
|
Page.java
|
Java
|
[] | null |
[] |
package program7;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;
/*
* The Page class is simply the page as it is being read by the main class. As soon as it detects a table it
* will create a Table2 class. It will parse the Table2 class it's own attributes to make sure the table can search in it's
* Location etc.
*/
public class Page {
private final boolean debugging;
private Elements spans;
private String workLocation;
private File file;
private double spaceDistance;
private double lineDistance;
public static Logger LOGGER = Logger.getLogger(Page.class.getName());
/**
* The constructor of this class sets the local variables for this class and creates a Jsoup document.
* @param file The HTML file created by the OCR.
* @param workLocation The work location as specified by the user.
* @param debugging if the program is in debugging mode.
* @throws java.io.IOException
*/
public Page(File file, String workLocation, boolean debugging) throws IOException {
Document doc = Jsoup.parse(file, "UTF-8", "http://example.com/");
this.spans = doc.select("span.ocrx_word");
this.workLocation = workLocation;
this.file = file;
this.spaceDistance = findSpaceDistance();
this.debugging = debugging;
setLineDistance();
LOGGER.info("The found average length of a character is: " + getSpaceDistance());
LOGGER.info("The found average distance between lines is: " +getLineDistance());
}
/**
* This method will find the tables in the content. It creates a table object for every table it finds.
* Do note that it creates a substring of the span(word) it finds. So if it finds <span>(table</span> it will not be detected.
* This has been done to reduce the amount of false positives (for referring to a table in the text).
* @param horizontalThresholdModifier The horizontal Threshold modifier.
* @param verticalThresholdModifier The vertical threshold modifier.
* @return The Table2 object. This method returns an empty list if no table was found.
* @throws java.io.IOException
*/
public ArrayList<Table2> createTables(double horizontalThresholdModifier, double verticalThresholdModifier) throws IOException {
String word;
boolean foundATable = false;
Elements tableSpans = new Elements();
ArrayList<Table2> foundTables = new ArrayList<Table2>();
int tableID = 0;
for (Element span : spans) {
word = span.text();
try {
if(word.substring(0, 5).equals("TABLE") || word.substring(0, 5).equals("table") || word.substring(0, 5).equals("Table")&&foundATable){
foundTables.add(new Table2(tableSpans, spaceDistance, file, workLocation, tableID, verticalThresholdModifier, horizontalThresholdModifier, lineDistance, debugging)); //make a new table from the collected spans
tableSpans = new Elements(); //reset the spans for the new Table2
tableSpans.add(span);
}
else if (foundATable) {
tableSpans.add(span);
}
if (word.substring(0, 5).equals("TABLE") || word.substring(0, 5).equals("table") || word.substring(0, 5).equals("Table")&&!foundATable) {
foundATable = true;
tableSpans.add(span);
}
} catch (StringIndexOutOfBoundsException e) {
if (foundATable) {
tableSpans.add(span);
}
}
tableID++;
}
if (foundATable) {
foundTables.add(new Table2(tableSpans, spaceDistance, file, workLocation, tableID, verticalThresholdModifier, horizontalThresholdModifier, lineDistance, debugging));
}
if(!foundATable){
LOGGER.info("There was no table found. ");
}
return foundTables;
}
/**
* This method tries to find the average space/distance of a character in a table. This can be used to determine
* the columns in a table.
* @return the average distance/space of a character.
*/
private double findSpaceDistance(){
double totalCharLength = 0.0;
for(Element span : spans){
String pos = span.attr("title");
String[] positions = pos.split("\\s+");
String word = span.text();
int X1 = Integer.parseInt(positions[1]);
int X2 = Integer.parseInt(positions[3]);
int length = X2 -X1;
if(word.length() > 0){
double charLength = length/word.length();
totalCharLength = totalCharLength + charLength;
}
}
return totalCharLength/spans.size();
}
/**
* This method sets the average distance between lines. First it creates lines using the second constructor of the Line
* class, then it calculates the distances between them.
*/
private void setLineDistance(){
double lineDistance;
String pos;
String[] positions;
int lastX2 = 0;
Elements currentLine = new Elements();
ArrayList<Line> lines = new ArrayList<Line>();
for(Element span : spans){
pos = span.attr("title");
positions = pos.split("\\s+");
int x1 = Integer.parseInt(positions[1]);
int x2 = Integer.parseInt(positions[3]);
if(!(x1>=lastX2)){
Line line = new Line(currentLine);
lines.add(line);
currentLine = new Elements();
}
lastX2 = x2;
currentLine.add(span);
}
double lastY2 = 0.0;
double totalDistance = 0.0;
for(Line line : lines){
if(lines.indexOf(line) == 0){
lastY2 = line.getAverageY2();
continue;
}
double distance = CommonMethods.calcDistance(lastY2 , line.getAverageY1());
totalDistance += distance;
lastY2 = line.getAverageY2();
}
lineDistance = totalDistance/lines.size();
this.lineDistance = lineDistance;
}
public double getSpaceDistance(){
return spaceDistance;
}
public double getLineDistance(){
return lineDistance;
}
}
| 6,647 | 0.60689 | 0.598616 | 163 | 39.77914 | 37.005062 | 229 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705521 | false | false |
7
|
9e3fa0113b16c724cb24722ad71cb2b638e6d4db
| 23,596,550,327,188 |
ea6a36158d0c3d55b7cd4ad53d50ea1e7e44e385
|
/src/main/java/com/example/userservice/exception/ValidationExceptionHandler.java
|
f3a02f5fdd3cbd74e936982f4bdd5f34b064674c
|
[] |
no_license
|
yutthagarn/user-service
|
https://github.com/yutthagarn/user-service
|
66932109598bf1780ad02f45b530f5425994e032
|
41b14f16005e0c960c6fa8dd62afc5a33471e563
|
refs/heads/master
| 2020-04-19T17:10:12.224000 | 2019-01-31T04:50:19 | 2019-01-31T04:50:19 | 168,326,543 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.userservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by IntelliJ IDEA.
* User: Cyl3erPunKz
* Date: 30 January 2019
* Time: 16:19
**/
@ControllerAdvice
public class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Map<String, Object> handleValidation(MethodArgumentNotValidException ex) {
Map<String, Object> error = new HashMap<>();
error.put("type", "validation");
error.put("violations", extractError(ex));
return error;
}
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Map<String, Object> handleValidation(BindException ex) {
Map<String, Object> error = new HashMap<>();
error.put("type", "validation");
error.put("violations", extractError(ex));
return error;
}
private Map<String, ValidationErrorMessage> extractError(MethodArgumentNotValidException ex) {
Map<String, ValidationErrorMessage> errorMessageMap = new HashMap<>();
for (ObjectError e : ex.getBindingResult().getAllErrors()) {
if (e instanceof FieldError) {
errorMessageMap.put(((FieldError) e).getField(), new ValidationErrorMessage((FieldError) e));
}
if (e instanceof ObjectError) {
errorMessageMap.put(e.getCodes()[0], new ValidationErrorMessage(e));
}
}
return errorMessageMap;
}
private Map<String, ValidationErrorMessage> extractError(BindException ex) {
return ex.getBindingResult().getAllErrors().stream()
.filter(e -> e instanceof FieldError)
.map(e -> (FieldError) e)
.collect(Collectors.toMap(FieldError::getField, ValidationErrorMessage::new));
}
public static class ValidationErrorMessage {
private String message;
private String type;
public ValidationErrorMessage(FieldError fieldError) {
this.message = fieldError.getDefaultMessage();
this.type = fieldError.getObjectName();
}
public ValidationErrorMessage(ObjectError objectError) {
this.message = objectError.getDefaultMessage();
this.type = objectError.getObjectName();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
}
|
UTF-8
|
Java
| 3,310 |
java
|
ValidationExceptionHandler.java
|
Java
|
[
{
"context": "ectors;\n\n/**\n * Created by IntelliJ IDEA.\n * User: Cyl3erPunKz\n * Date: 30 January 2019\n * Time: 16:19\n **/\n@Con",
"end": 704,
"score": 0.9993419647216797,
"start": 693,
"tag": "USERNAME",
"value": "Cyl3erPunKz"
}
] | null |
[] |
package com.example.userservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by IntelliJ IDEA.
* User: Cyl3erPunKz
* Date: 30 January 2019
* Time: 16:19
**/
@ControllerAdvice
public class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Map<String, Object> handleValidation(MethodArgumentNotValidException ex) {
Map<String, Object> error = new HashMap<>();
error.put("type", "validation");
error.put("violations", extractError(ex));
return error;
}
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Map<String, Object> handleValidation(BindException ex) {
Map<String, Object> error = new HashMap<>();
error.put("type", "validation");
error.put("violations", extractError(ex));
return error;
}
private Map<String, ValidationErrorMessage> extractError(MethodArgumentNotValidException ex) {
Map<String, ValidationErrorMessage> errorMessageMap = new HashMap<>();
for (ObjectError e : ex.getBindingResult().getAllErrors()) {
if (e instanceof FieldError) {
errorMessageMap.put(((FieldError) e).getField(), new ValidationErrorMessage((FieldError) e));
}
if (e instanceof ObjectError) {
errorMessageMap.put(e.getCodes()[0], new ValidationErrorMessage(e));
}
}
return errorMessageMap;
}
private Map<String, ValidationErrorMessage> extractError(BindException ex) {
return ex.getBindingResult().getAllErrors().stream()
.filter(e -> e instanceof FieldError)
.map(e -> (FieldError) e)
.collect(Collectors.toMap(FieldError::getField, ValidationErrorMessage::new));
}
public static class ValidationErrorMessage {
private String message;
private String type;
public ValidationErrorMessage(FieldError fieldError) {
this.message = fieldError.getDefaultMessage();
this.type = fieldError.getObjectName();
}
public ValidationErrorMessage(ObjectError objectError) {
this.message = objectError.getDefaultMessage();
this.type = objectError.getObjectName();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
}
| 3,310 | 0.673414 | 0.669789 | 101 | 31.772278 | 27.022133 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.49505 | false | false |
7
|
13622f23892041c4076f2e2fb07230e5b93ae237
| 36,335,423,328,251 |
db21b28ec9e64c33cf8f2a725d56cd8585720a91
|
/leetcode_284.java
|
1da12920324b07591f6696f2750e4994ebfe084d
|
[] |
no_license
|
2018hsridhar/Leetcode_Solutions
|
https://github.com/2018hsridhar/Leetcode_Solutions
|
afb6a88f2b1075af3f6339956e499f228cde0ba3
|
f6b356ff5393113d0a6cc29118e6ef6c45a4f0ee
|
refs/heads/master
| 2023-08-30T22:43:23.308000 | 2023-08-29T04:15:31 | 2023-08-29T04:15:31 | 78,995,027 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
/*
284. Peeking Iterator
URL = https://leetcode.com/problems/peeking-iterator/
Extends the Iterator<T> interface -> write impl of methods to override too.
Handle of edge cases ( e..g you had no data in the input )
LinkedList<T> should suffice underneath.
No need to support explicit removal.
Let N := #-elements in the iterator. Constructor is a O(N) = T, O(N) = S operation
All other operations of class PeekingIterator are O(1) Time, O(1) Space
Let us aim to avoid a lot of calls to member data ; in lieu, keep a state and update over time.
Edge Cases
(A)
(B)
(C)
(D)
(E)
*/
class PeekingIterator implements Iterator<Integer> {
Iterator<Integer> originalIterator;
private List<Integer> myData;
private int size;
public PeekingIterator(Iterator<Integer> iterator) {
originalIterator = iterator;
myData = new LinkedList<Integer>();
size = 0;
while(iterator.hasNext()){
myData.add(iterator.next());
size++;
}
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
int res = (size > 0 )? myData.get(0) : -1;
return res;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
int res;
if(size > 0){
res = myData.get(0);
myData.remove(0);
size--;
} else {
res = -1;
}
return res;
}
@Override
public boolean hasNext() {
return (size > 0);
}
}
|
UTF-8
|
Java
| 1,707 |
java
|
leetcode_284.java
|
Java
|
[] | null |
[] |
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
/*
284. Peeking Iterator
URL = https://leetcode.com/problems/peeking-iterator/
Extends the Iterator<T> interface -> write impl of methods to override too.
Handle of edge cases ( e..g you had no data in the input )
LinkedList<T> should suffice underneath.
No need to support explicit removal.
Let N := #-elements in the iterator. Constructor is a O(N) = T, O(N) = S operation
All other operations of class PeekingIterator are O(1) Time, O(1) Space
Let us aim to avoid a lot of calls to member data ; in lieu, keep a state and update over time.
Edge Cases
(A)
(B)
(C)
(D)
(E)
*/
class PeekingIterator implements Iterator<Integer> {
Iterator<Integer> originalIterator;
private List<Integer> myData;
private int size;
public PeekingIterator(Iterator<Integer> iterator) {
originalIterator = iterator;
myData = new LinkedList<Integer>();
size = 0;
while(iterator.hasNext()){
myData.add(iterator.next());
size++;
}
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
int res = (size > 0 )? myData.get(0) : -1;
return res;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
int res;
if(size > 0){
res = myData.get(0);
myData.remove(0);
size--;
} else {
res = -1;
}
return res;
}
@Override
public boolean hasNext() {
return (size > 0);
}
}
| 1,707 | 0.626831 | 0.618043 | 68 | 24.102942 | 24.472157 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false |
7
|
57b2ff81675acf093e75b61beb0a97bb252ee089
| 19,430,432,082,279 |
539c74fe781483c6e0cdea8e288618dfcee8815b
|
/middleware/middleware-service/src/main/java/net/deepdragon/dao/weipu/GhjRedenvelopRuleDao.java
|
7532a235faa09cb47bf3a26b1846d918a5e35f10
|
[
"Apache-2.0"
] |
permissive
|
FireInTheHotel/B2BShop
|
https://github.com/FireInTheHotel/B2BShop
|
3fd105e4698ec9df611424242f10b31050bf0e44
|
0a48c74339be5ae2c0e3f9c7d989aef8e720e07a
|
refs/heads/master
| 2020-03-18T22:49:59.588000 | 2018-05-30T00:52:02 | 2018-05-30T00:52:02 | 135,367,895 | 0 | 1 |
Apache-2.0
| false | 2020-04-16T05:18:55 | 2018-05-30T00:44:04 | 2020-04-16T05:17:37 | 2020-04-16T05:18:55 | 80,353 | 0 | 1 | 7 |
FreeMarker
| false | false |
package net.deepdragon.dao.weipu;
import net.deepdragon.condition.Criteria;
import net.deepdragon.entity.weipu.GhjRedenvelopRule;
import java.util.List;
import java.util.Map;
public interface GhjRedenvelopRuleDao extends BaseDao<GhjRedenvelopRule, String> {
List<GhjRedenvelopRule> getRedEnvelopId(Map<String, Object> paramMap, Criteria criteria);
}
|
UTF-8
|
Java
| 358 |
java
|
GhjRedenvelopRuleDao.java
|
Java
|
[] | null |
[] |
package net.deepdragon.dao.weipu;
import net.deepdragon.condition.Criteria;
import net.deepdragon.entity.weipu.GhjRedenvelopRule;
import java.util.List;
import java.util.Map;
public interface GhjRedenvelopRuleDao extends BaseDao<GhjRedenvelopRule, String> {
List<GhjRedenvelopRule> getRedEnvelopId(Map<String, Object> paramMap, Criteria criteria);
}
| 358 | 0.818436 | 0.818436 | 12 | 28.833334 | 31.492945 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false |
7
|
80602a6401e54e25f8c6f3c333471c1bd97d8623
| 24,206,435,696,025 |
a5a27c080e3d7b001ae6c7fbee8c8db4f5c49044
|
/2-java/3-junit-5 & mockito/src/test/java/com/example/specs/Ex2.java
|
b2543e869602c39cb16fd1288745fe4a90815d66
|
[] |
no_license
|
nagabhushanamn/airbus-automation
|
https://github.com/nagabhushanamn/airbus-automation
|
c12a27dcc8874b95b7f18693df0f36c8cf572294
|
2c933720228550f76d783af22ceaf6e1b99801d4
|
refs/heads/master
| 2023-01-06T18:45:07.362000 | 2019-09-11T14:01:04 | 2019-09-11T14:01:04 | 206,237,421 | 0 | 0 | null | false | 2022-12-10T06:03:10 | 2019-09-04T05:19:43 | 2019-09-11T14:01:13 | 2022-12-10T06:03:10 | 2,758 | 0 | 0 | 25 |
HTML
| false | false |
package com.example.specs;
import static org.mockito.Mockito.*;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
/**
*
* @author nag-training
*
* 2. How about some stubbing?
*
*/
public class Ex2 {
@Test
public void test1() {
// You can mock concrete classes, not just interfaces
LinkedList mockedList = mock(LinkedList.class);
// stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
// following prints "first"
// System.out.println(mockedList.get(0));
// // following throws runtime exception
// System.out.println(mockedList.get(1));
//
// // following prints "null" because get(999) was not stubbed
// System.out.println(mockedList.get(999));
// Although it is possible to verify a stubbed invocation, usually it's just
// redundant
// If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
// If your code doesn't care what get(0) returns, then it should not be stubbed.
verify(mockedList).get(0);
}
}
|
UTF-8
|
Java
| 1,101 |
java
|
Ex2.java
|
Java
|
[
{
"context": "rt org.junit.jupiter.api.Test;\n\n/**\n * \n * @author nag-training\n *\n * 2. How about some stubbing?\n *\n */\n",
"end": 163,
"score": 0.9995028972625732,
"start": 151,
"tag": "USERNAME",
"value": "nag-training"
}
] | null |
[] |
package com.example.specs;
import static org.mockito.Mockito.*;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
/**
*
* @author nag-training
*
* 2. How about some stubbing?
*
*/
public class Ex2 {
@Test
public void test1() {
// You can mock concrete classes, not just interfaces
LinkedList mockedList = mock(LinkedList.class);
// stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
// following prints "first"
// System.out.println(mockedList.get(0));
// // following throws runtime exception
// System.out.println(mockedList.get(1));
//
// // following prints "null" because get(999) was not stubbed
// System.out.println(mockedList.get(999));
// Although it is possible to verify a stubbed invocation, usually it's just
// redundant
// If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
// If your code doesn't care what get(0) returns, then it should not be stubbed.
verify(mockedList).get(0);
}
}
| 1,101 | 0.693915 | 0.679382 | 47 | 22.425531 | 26.667171 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.148936 | false | false |
7
|
7539b2d0dd7ee1017c3112ff153f0079a7eed3dc
| 18,562,848,655,486 |
c0fd8dfc41a6385180e23c064f555b9a3f465004
|
/app/src/main/java/br/edu/uepb/nutes/haniot/adapter/base/BaseRecyclerViewHolder.java
|
cd4e21498a7522e24f509727b70bbcb6a50c2835
|
[
"Apache-2.0"
] |
permissive
|
Bernarsh/android-app
|
https://github.com/Bernarsh/android-app
|
c45e25dbd85d680ba0c873bdebf5e648478b21e1
|
ceca7119995397c58f453b93ff44772cbd88d6d6
|
refs/heads/master
| 2023-03-16T10:34:36.104000 | 2020-01-20T23:00:26 | 2020-01-20T23:00:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.edu.uepb.nutes.haniot.adapter.base;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Class Base Recycler.ViewHolder.
*
* @author Douglas Rafael <douglasrafaelcg@gmail.com>
* @version 1.0
* @copyright Copyright (c) 2017, NUTES UEPB
*/
public class BaseRecyclerViewHolder extends RecyclerView.ViewHolder {
public BaseRecyclerViewHolder(View itemView) {
super(itemView);
}
}
|
UTF-8
|
Java
| 437 |
java
|
BaseRecyclerViewHolder.java
|
Java
|
[
{
"context": "*\n * Class Base Recycler.ViewHolder.\n *\n * @author Douglas Rafael <douglasrafaelcg@gmail.com>\n * @version 1.0\n * @c",
"end": 189,
"score": 0.9998838305473328,
"start": 175,
"tag": "NAME",
"value": "Douglas Rafael"
},
{
"context": "ecycler.ViewHolder.\n *\n * @author Douglas Rafael <douglasrafaelcg@gmail.com>\n * @version 1.0\n * @copyright Copyright (c) 2017",
"end": 216,
"score": 0.9999284744262695,
"start": 191,
"tag": "EMAIL",
"value": "douglasrafaelcg@gmail.com"
}
] | null |
[] |
package br.edu.uepb.nutes.haniot.adapter.base;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Class Base Recycler.ViewHolder.
*
* @author <NAME> <<EMAIL>>
* @version 1.0
* @copyright Copyright (c) 2017, NUTES UEPB
*/
public class BaseRecyclerViewHolder extends RecyclerView.ViewHolder {
public BaseRecyclerViewHolder(View itemView) {
super(itemView);
}
}
| 411 | 0.741419 | 0.7254 | 17 | 24.705883 | 22.349535 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false |
7
|
efda7e4d513213bae3e255a282280bbe14631ce0
| 18,562,848,657,714 |
04a992c26d07269bb6963a8c46f7ddaaf7887349
|
/src/dao/SuppliersDao.java
|
4a081cd41f303320b6683fa7f4c7444934b3af3b
|
[] |
no_license
|
jyajyamaru114/RemoteInventoryManager
|
https://github.com/jyajyamaru114/RemoteInventoryManager
|
a7e0628571cca7dba9eef0e02ae276d46e6a6630
|
16af7001236ec20a794fac968f3a0160b8d36d47
|
refs/heads/master
| 2023-05-31T04:51:19.177000 | 2021-06-08T04:48:35 | 2021-06-08T04:48:35 | 356,147,987 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dao;
import java.util.List;
import domain.Suppliers;
public interface SuppliersDao {
List<Suppliers> findAll() throws Exception;
Suppliers findById(Integer id) throws Exception;
void insert(Suppliers suppliers) throws Exception;
void update(Suppliers suppliers) throws Exception;
void delete(Suppliers suppliers) throws Exception;
}
|
UTF-8
|
Java
| 355 |
java
|
SuppliersDao.java
|
Java
|
[] | null |
[] |
package dao;
import java.util.List;
import domain.Suppliers;
public interface SuppliersDao {
List<Suppliers> findAll() throws Exception;
Suppliers findById(Integer id) throws Exception;
void insert(Suppliers suppliers) throws Exception;
void update(Suppliers suppliers) throws Exception;
void delete(Suppliers suppliers) throws Exception;
}
| 355 | 0.791549 | 0.791549 | 19 | 17.68421 | 20.981327 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false |
7
|
95e3f8eae0e31a24c2a1801f3425acd525ddf927
| 27,951,647,182,408 |
d8cb9007a2a2cdaa01657e2208f0ee4d10096b9a
|
/src/pl/altkom/zad6_10/Rekurencja.java
|
088e81e31ab17a880a2cfae2988b3140cecb84ca
|
[] |
no_license
|
java-programator/2019-09-15
|
https://github.com/java-programator/2019-09-15
|
4576c7fee1f3e2cb94378162c67679fb7cf87777
|
c9fe9fbc35b387f7f26a87f88acb219ebe93cce6
|
refs/heads/master
| 2020-07-26T05:52:42.801000 | 2019-10-05T10:40:54 | 2019-10-05T10:40:54 | 208,555,669 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.altkom.zad6_10;
public class Rekurencja {
static int silnia(int n) {
if (n == 0) {
return 1;
} else {
return n * silnia(n - 1);
}
}
static int fib(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fib(n-1) + fib(n-2);
}
}
public static void main(String[] args) {
// int m = silnia(5);
// = 5 * silnia(4)
// = 5 * 4 * silnia(3) =
// = 5 * 4 * 3 * silnia(2) =
// = 5 * 4 * 3 * 2 * silnia(1) =
// = 5 * 4 * 3 * 2 * 1 * silnia(0) =
// = 5 * 4 * 3 * 2 * 1 * 1
int begin = 123;
int end = 2345;
int f;
int n = 0;
int counter = 0;
do {
f = fib(n);
n++;
if (f >= begin && f <= end) {
counter++;
}
} while (f <= end);
System.out.println(counter);
}
}
|
UTF-8
|
Java
| 1,025 |
java
|
Rekurencja.java
|
Java
|
[] | null |
[] |
package pl.altkom.zad6_10;
public class Rekurencja {
static int silnia(int n) {
if (n == 0) {
return 1;
} else {
return n * silnia(n - 1);
}
}
static int fib(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fib(n-1) + fib(n-2);
}
}
public static void main(String[] args) {
// int m = silnia(5);
// = 5 * silnia(4)
// = 5 * 4 * silnia(3) =
// = 5 * 4 * 3 * silnia(2) =
// = 5 * 4 * 3 * 2 * silnia(1) =
// = 5 * 4 * 3 * 2 * 1 * silnia(0) =
// = 5 * 4 * 3 * 2 * 1 * 1
int begin = 123;
int end = 2345;
int f;
int n = 0;
int counter = 0;
do {
f = fib(n);
n++;
if (f >= begin && f <= end) {
counter++;
}
} while (f <= end);
System.out.println(counter);
}
}
| 1,025 | 0.341463 | 0.294634 | 61 | 15.803279 | 14.265423 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.278689 | false | false |
7
|
9a90a695df70fa6bce81c9bd1a41d8baf12452ce
| 13,245,679,158,057 |
69cb4526bf16597cc14ef1b1ef9a4186193279cb
|
/src/musique/ChargeurGestionnaireMusique.java
|
c812bb5c8d89b8ec0d85fc794eb60243645802a0
|
[] |
no_license
|
lanaflonPerso/technowide_java
|
https://github.com/lanaflonPerso/technowide_java
|
716860887a0353d7d5cee5a5e994f524febad93a
|
cba199a5948f50d2af2d173c1216633e0f38e05f
|
refs/heads/master
| 2020-11-28T19:46:48.945000 | 2019-05-02T15:35:32 | 2019-05-02T15:35:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package musique;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChargeurGestionnaireMusique {
private Map<String, Artiste> artistesMap = new HashMap<>();
private List<Album> albums = new ArrayList<Album>();
public List<Album> getAlbums() {
return albums;
}
public void charger(Path path) throws IOException {
Album albumCourant = null;
for (String ligne : Files.readAllLines(path)) {
String[] colonnes = ligne.split(";");
if (colonnes.length > 0) {
if (isLigneAlbum(colonnes)) {
albumCourant = creerAlbum(colonnes);
} else if (isLignePiste(colonnes)) {
creerPiste(albumCourant, colonnes);
}
}
}
}
private void creerPiste(Album albumCourant, String[] colonnes) {
Piste piste = new Piste(colonnes[1], Duree.valueOf(colonnes[2]));
albumCourant.ajouter(piste);
}
private Album creerAlbum(String[] colonnes) {
Album albumCourant;
albumCourant = new Album(colonnes[1]);
albums.add(albumCourant);
if (colonnes.length >= 3) {
String nomArtiste = colonnes[2];
Artiste artiste = creerArtiste(nomArtiste);
albumCourant.setArtiste(artiste);
}
return albumCourant;
}
private Artiste creerArtiste(String nomArtiste) {
Artiste artiste = null;
if (artistesMap.containsKey(nomArtiste)) {
artiste = artistesMap.get(nomArtiste);
} else {
artiste = new Artiste(nomArtiste);
artistesMap.put(nomArtiste, artiste);
}
return artiste;
}
private boolean isLigneAlbum(String[] colonnes) {
return colonnes[0].equals("A") && colonnes.length >=2;
}
private boolean isLignePiste(String[] colonnes) {
return colonnes[0].equals("P") && colonnes.length >=3;
}
}
|
UTF-8
|
Java
| 1,793 |
java
|
ChargeurGestionnaireMusique.java
|
Java
|
[] | null |
[] |
package musique;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChargeurGestionnaireMusique {
private Map<String, Artiste> artistesMap = new HashMap<>();
private List<Album> albums = new ArrayList<Album>();
public List<Album> getAlbums() {
return albums;
}
public void charger(Path path) throws IOException {
Album albumCourant = null;
for (String ligne : Files.readAllLines(path)) {
String[] colonnes = ligne.split(";");
if (colonnes.length > 0) {
if (isLigneAlbum(colonnes)) {
albumCourant = creerAlbum(colonnes);
} else if (isLignePiste(colonnes)) {
creerPiste(albumCourant, colonnes);
}
}
}
}
private void creerPiste(Album albumCourant, String[] colonnes) {
Piste piste = new Piste(colonnes[1], Duree.valueOf(colonnes[2]));
albumCourant.ajouter(piste);
}
private Album creerAlbum(String[] colonnes) {
Album albumCourant;
albumCourant = new Album(colonnes[1]);
albums.add(albumCourant);
if (colonnes.length >= 3) {
String nomArtiste = colonnes[2];
Artiste artiste = creerArtiste(nomArtiste);
albumCourant.setArtiste(artiste);
}
return albumCourant;
}
private Artiste creerArtiste(String nomArtiste) {
Artiste artiste = null;
if (artistesMap.containsKey(nomArtiste)) {
artiste = artistesMap.get(nomArtiste);
} else {
artiste = new Artiste(nomArtiste);
artistesMap.put(nomArtiste, artiste);
}
return artiste;
}
private boolean isLigneAlbum(String[] colonnes) {
return colonnes[0].equals("A") && colonnes.length >=2;
}
private boolean isLignePiste(String[] colonnes) {
return colonnes[0].equals("P") && colonnes.length >=3;
}
}
| 1,793 | 0.707752 | 0.702175 | 70 | 24.614286 | 20.043734 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.028571 | false | false |
7
|
2d14b398f827c70a49f1603bf4459b25cc746a09
| 3,770,981,328,944 |
203c84e458e1a0cb1a9b5c7c0d0774ec832f0ced
|
/mq/src/main/java/com/nova/lyn/dlx/DlxHandler.java
|
1381bed2799e822e4550b348304f9c87d556cdcb
|
[] |
no_license
|
justein/oopmap
|
https://github.com/justein/oopmap
|
32efd0b745acfa66074b0e8988322fffca851f0f
|
6476433ba8a3a565a61dc92423c3c7336e11f075
|
refs/heads/master
| 2022-12-22T01:29:16.431000 | 2019-12-05T14:43:54 | 2019-12-05T14:43:54 | 176,244,369 | 0 | 0 | null | false | 2022-12-16T08:59:51 | 2019-03-18T09:12:21 | 2019-12-05T14:44:12 | 2022-12-16T08:59:48 | 36 | 0 | 0 | 4 |
Java
| false | false |
package com.nova.lyn.dlx;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @ClassName DlxHandler
* @Description TODO
* @Author Lyn
* @Date 2019/4/15 0015 上午 9:01
* @Version 1.0
*/
@Component
public class DlxHandler {
// @RabbitHandler
@RabbitListener(queues = {"REDIRECT-QUEUE"})
public void redirect(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
System.out.println("收到死信消息,正在处理" + new String(message.getBody()));
}
}
|
UTF-8
|
Java
| 815 |
java
|
DlxHandler.java
|
Java
|
[
{
"context": "assName DlxHandler\n * @Description TODO\n * @Author Lyn\n * @Date 2019/4/15 0015 上午 9:01\n * @Version 1.0\n ",
"end": 383,
"score": 0.9995876550674438,
"start": 380,
"tag": "USERNAME",
"value": "Lyn"
}
] | null |
[] |
package com.nova.lyn.dlx;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @ClassName DlxHandler
* @Description TODO
* @Author Lyn
* @Date 2019/4/15 0015 上午 9:01
* @Version 1.0
*/
@Component
public class DlxHandler {
// @RabbitHandler
@RabbitListener(queues = {"REDIRECT-QUEUE"})
public void redirect(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
System.out.println("收到死信消息,正在处理" + new String(message.getBody()));
}
}
| 815 | 0.749049 | 0.728771 | 27 | 28.222221 | 25.699594 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false |
7
|
9f30b9615b8f1e6539a11605fa674270fff8b96e
| 6,279,242,222,251 |
765aa51a367f792e52b3a29ba2148b63b2419522
|
/drygoodsshare/src/main/java/com/issp/association/presenters/ReadShareInfoPresenter.java
|
61a28fa2e45191c7172f201dda53757d8bc41790
|
[] |
no_license
|
ljh-dobest/CommunityAlliance
|
https://github.com/ljh-dobest/CommunityAlliance
|
3944cd413949ca25eacbddb8cce7ccc085e749e0
|
e8bcc2a196ca9073995f0bf6f167a0e80bc4a618
|
refs/heads/master
| 2023-04-13T00:36:18.507000 | 2023-04-11T03:07:16 | 2023-04-11T03:07:16 | 83,652,989 | 4 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.issp.association.presenters;
import com.issp.association.base.presenter.BasePersenter;
import com.issp.association.bean.ShareBean;
import com.issp.association.interfaces.IReadShareView;
import com.issp.association.interfaces.IShareListView;
import com.issp.association.listeners.OnReadShareListener;
import com.issp.association.listeners.OnShareListener;
import com.issp.association.model.ReadShareInfoModel;
import com.issp.association.model.ShareInfoModel;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by T-BayMax on 2017/3/13.
*/
public class ReadShareInfoPresenter extends BasePersenter<IReadShareView> implements OnReadShareListener {
private ReadShareInfoModel recommendInfoMoudle;
public ReadShareInfoPresenter() {
recommendInfoMoudle = new ReadShareInfoModel();
}
public void ReadShareInfoPresenter(Map<String, String> formData) {
recommendInfoMoudle.getReadShareInfo(formData, this);
}
public void sharePraiseInfoPresenter(Map<String, String> formData) {
recommendInfoMoudle.getSharePraiseInfo(formData, this);
}
@Override
public void getReadShareInfo(ShareBean data) {
mView.setReadShareData(data);
}
@Override
public void sharePraiseInfo(String data) {
mView.sharePraise(data);
}
@Override
public void showError(String errorString) {
mView.showError(errorString);
}
}
|
UTF-8
|
Java
| 1,434 |
java
|
ReadShareInfoPresenter.java
|
Java
|
[
{
"context": "rrayList;\nimport java.util.Map;\n\n/**\n * Created by T-BayMax on 2017/3/13.\n */\n\npublic class ReadShareInfoPres",
"end": 550,
"score": 0.999095618724823,
"start": 542,
"tag": "USERNAME",
"value": "T-BayMax"
}
] | null |
[] |
package com.issp.association.presenters;
import com.issp.association.base.presenter.BasePersenter;
import com.issp.association.bean.ShareBean;
import com.issp.association.interfaces.IReadShareView;
import com.issp.association.interfaces.IShareListView;
import com.issp.association.listeners.OnReadShareListener;
import com.issp.association.listeners.OnShareListener;
import com.issp.association.model.ReadShareInfoModel;
import com.issp.association.model.ShareInfoModel;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by T-BayMax on 2017/3/13.
*/
public class ReadShareInfoPresenter extends BasePersenter<IReadShareView> implements OnReadShareListener {
private ReadShareInfoModel recommendInfoMoudle;
public ReadShareInfoPresenter() {
recommendInfoMoudle = new ReadShareInfoModel();
}
public void ReadShareInfoPresenter(Map<String, String> formData) {
recommendInfoMoudle.getReadShareInfo(formData, this);
}
public void sharePraiseInfoPresenter(Map<String, String> formData) {
recommendInfoMoudle.getSharePraiseInfo(formData, this);
}
@Override
public void getReadShareInfo(ShareBean data) {
mView.setReadShareData(data);
}
@Override
public void sharePraiseInfo(String data) {
mView.sharePraise(data);
}
@Override
public void showError(String errorString) {
mView.showError(errorString);
}
}
| 1,434 | 0.762204 | 0.757322 | 48 | 28.875 | 26.509924 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false |
7
|
0035188a025f18c54a22b5b9d894ebd1291bc8ac
| 30,210,799,990,544 |
a957d8ee653971be80afb282b0bfac00be6c83d2
|
/java/src/Changshi3.java
|
425e781d595700c2e8583fc9cc371adaa6c0c937
|
[] |
no_license
|
caipan4511363/test
|
https://github.com/caipan4511363/test
|
da5c56e12f2cbc3860f0bdbae91e5929a2edde23
|
48960593802f6fae9249c1a730ac78c9c46deb91
|
refs/heads/master
| 2020-04-30T13:10:52.923000 | 2019-03-21T02:04:53 | 2019-03-21T02:04:53 | 176,848,541 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* @author caipan
* @create 2019/3/21
* @since 1.0.0
*/
public class Changshi3 {
public static void main(String[] args) {
System.out.println("222,hello,333!!!");
}
}
|
UTF-8
|
Java
| 190 |
java
|
Changshi3.java
|
Java
|
[
{
"context": "/**\n * @author caipan\n * @create 2019/3/21\n * @since 1.0.0\n */\npublic c",
"end": 21,
"score": 0.9991915822029114,
"start": 15,
"tag": "USERNAME",
"value": "caipan"
}
] | null |
[] |
/**
* @author caipan
* @create 2019/3/21
* @since 1.0.0
*/
public class Changshi3 {
public static void main(String[] args) {
System.out.println("222,hello,333!!!");
}
}
| 190 | 0.578947 | 0.489474 | 11 | 16.272728 | 15.85784 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false |
7
|
c7b012908872ddf2937954b5adcee937e58670a7
| 20,306,605,427,043 |
7ceafb307d6a72fc705ffd40f0b6fb62e1bc3be7
|
/appointments-impl/src/main/java/com/liferay/appointments/internal/graphql/mutation/v1_0/Mutation.java
|
5fedc5c5aa1e9647cb643bff4205d8ba55baf1b3
|
[] |
no_license
|
dhivakar-sengottaiyan/liferay-devcon-appointment
|
https://github.com/dhivakar-sengottaiyan/liferay-devcon-appointment
|
1ff4ab68e63e9d4704831bf1bc4516fb0ec2d063
|
7ca43365ead8036463f29492a044b3c9ec9248ac
|
refs/heads/master
| 2023-06-02T18:03:08.716000 | 2019-11-17T22:59:17 | 2019-11-17T22:59:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.liferay.appointments.internal.graphql.mutation.v1_0;
import com.liferay.appointments.dto.v1_0.Appointment;
import com.liferay.appointments.resource.v1_0.AppointmentResource;
import com.liferay.petra.function.UnsafeConsumer;
import com.liferay.petra.function.UnsafeFunction;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.vulcan.accept.language.AcceptLanguage;
import com.liferay.portal.vulcan.graphql.annotation.GraphQLField;
import com.liferay.portal.vulcan.graphql.annotation.GraphQLName;
import javax.annotation.Generated;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.UriInfo;
import org.osgi.service.component.ComponentServiceObjects;
/**
* @author Javier Gamarra
* @generated
*/
@Generated("")
public class Mutation {
public static void setAppointmentResourceComponentServiceObjects(
ComponentServiceObjects<AppointmentResource>
appointmentResourceComponentServiceObjects) {
_appointmentResourceComponentServiceObjects =
appointmentResourceComponentServiceObjects;
}
@GraphQLField
public boolean deleteAppointment(
@GraphQLName("appointmentId") Long appointmentId)
throws Exception {
_applyVoidComponentServiceObjects(
_appointmentResourceComponentServiceObjects,
this::_populateResourceContext,
appointmentResource -> appointmentResource.deleteAppointment(
appointmentId));
return true;
}
@GraphQLField
public Appointment updateAppointment(
@GraphQLName("appointmentId") Long appointmentId,
@GraphQLName("appointment") Appointment appointment)
throws Exception {
return _applyComponentServiceObjects(
_appointmentResourceComponentServiceObjects,
this::_populateResourceContext,
appointmentResource -> appointmentResource.putAppointment(
appointmentId, appointment));
}
@GraphQLField
public Appointment createSiteAppointment(
@GraphQLName("siteId") Long siteId,
@GraphQLName("siteKey") String siteKey,
@GraphQLName("appointment") Appointment appointment)
throws Exception {
return _applyComponentServiceObjects(
_appointmentResourceComponentServiceObjects,
this::_populateResourceContext,
appointmentResource -> appointmentResource.postSiteAppointment(
siteId, appointment));
}
private <T, R, E1 extends Throwable, E2 extends Throwable> R
_applyComponentServiceObjects(
ComponentServiceObjects<T> componentServiceObjects,
UnsafeConsumer<T, E1> unsafeConsumer,
UnsafeFunction<T, R, E2> unsafeFunction)
throws E1, E2 {
T resource = componentServiceObjects.getService();
try {
unsafeConsumer.accept(resource);
return unsafeFunction.apply(resource);
}
finally {
componentServiceObjects.ungetService(resource);
}
}
private <T, E1 extends Throwable, E2 extends Throwable> void
_applyVoidComponentServiceObjects(
ComponentServiceObjects<T> componentServiceObjects,
UnsafeConsumer<T, E1> unsafeConsumer,
UnsafeConsumer<T, E2> unsafeFunction)
throws E1, E2 {
T resource = componentServiceObjects.getService();
try {
unsafeConsumer.accept(resource);
unsafeFunction.accept(resource);
}
finally {
componentServiceObjects.ungetService(resource);
}
}
private void _populateResourceContext(
AppointmentResource appointmentResource)
throws Exception {
appointmentResource.setContextAcceptLanguage(_acceptLanguage);
appointmentResource.setContextCompany(_company);
appointmentResource.setContextHttpServletRequest(_httpServletRequest);
appointmentResource.setContextHttpServletResponse(_httpServletResponse);
appointmentResource.setContextUriInfo(_uriInfo);
appointmentResource.setContextUser(_user);
}
private static ComponentServiceObjects<AppointmentResource>
_appointmentResourceComponentServiceObjects;
private AcceptLanguage _acceptLanguage;
private Company _company;
private HttpServletRequest _httpServletRequest;
private HttpServletResponse _httpServletResponse;
private UriInfo _uriInfo;
private User _user;
}
|
UTF-8
|
Java
| 4,090 |
java
|
Mutation.java
|
Java
|
[
{
"context": "component.ComponentServiceObjects;\n\n/**\n * @author Javier Gamarra\n * @generated\n */\n@Generated(\"\")\npublic class Mut",
"end": 830,
"score": 0.9998487234115601,
"start": 816,
"tag": "NAME",
"value": "Javier Gamarra"
}
] | null |
[] |
package com.liferay.appointments.internal.graphql.mutation.v1_0;
import com.liferay.appointments.dto.v1_0.Appointment;
import com.liferay.appointments.resource.v1_0.AppointmentResource;
import com.liferay.petra.function.UnsafeConsumer;
import com.liferay.petra.function.UnsafeFunction;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.vulcan.accept.language.AcceptLanguage;
import com.liferay.portal.vulcan.graphql.annotation.GraphQLField;
import com.liferay.portal.vulcan.graphql.annotation.GraphQLName;
import javax.annotation.Generated;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.UriInfo;
import org.osgi.service.component.ComponentServiceObjects;
/**
* @author <NAME>
* @generated
*/
@Generated("")
public class Mutation {
public static void setAppointmentResourceComponentServiceObjects(
ComponentServiceObjects<AppointmentResource>
appointmentResourceComponentServiceObjects) {
_appointmentResourceComponentServiceObjects =
appointmentResourceComponentServiceObjects;
}
@GraphQLField
public boolean deleteAppointment(
@GraphQLName("appointmentId") Long appointmentId)
throws Exception {
_applyVoidComponentServiceObjects(
_appointmentResourceComponentServiceObjects,
this::_populateResourceContext,
appointmentResource -> appointmentResource.deleteAppointment(
appointmentId));
return true;
}
@GraphQLField
public Appointment updateAppointment(
@GraphQLName("appointmentId") Long appointmentId,
@GraphQLName("appointment") Appointment appointment)
throws Exception {
return _applyComponentServiceObjects(
_appointmentResourceComponentServiceObjects,
this::_populateResourceContext,
appointmentResource -> appointmentResource.putAppointment(
appointmentId, appointment));
}
@GraphQLField
public Appointment createSiteAppointment(
@GraphQLName("siteId") Long siteId,
@GraphQLName("siteKey") String siteKey,
@GraphQLName("appointment") Appointment appointment)
throws Exception {
return _applyComponentServiceObjects(
_appointmentResourceComponentServiceObjects,
this::_populateResourceContext,
appointmentResource -> appointmentResource.postSiteAppointment(
siteId, appointment));
}
private <T, R, E1 extends Throwable, E2 extends Throwable> R
_applyComponentServiceObjects(
ComponentServiceObjects<T> componentServiceObjects,
UnsafeConsumer<T, E1> unsafeConsumer,
UnsafeFunction<T, R, E2> unsafeFunction)
throws E1, E2 {
T resource = componentServiceObjects.getService();
try {
unsafeConsumer.accept(resource);
return unsafeFunction.apply(resource);
}
finally {
componentServiceObjects.ungetService(resource);
}
}
private <T, E1 extends Throwable, E2 extends Throwable> void
_applyVoidComponentServiceObjects(
ComponentServiceObjects<T> componentServiceObjects,
UnsafeConsumer<T, E1> unsafeConsumer,
UnsafeConsumer<T, E2> unsafeFunction)
throws E1, E2 {
T resource = componentServiceObjects.getService();
try {
unsafeConsumer.accept(resource);
unsafeFunction.accept(resource);
}
finally {
componentServiceObjects.ungetService(resource);
}
}
private void _populateResourceContext(
AppointmentResource appointmentResource)
throws Exception {
appointmentResource.setContextAcceptLanguage(_acceptLanguage);
appointmentResource.setContextCompany(_company);
appointmentResource.setContextHttpServletRequest(_httpServletRequest);
appointmentResource.setContextHttpServletResponse(_httpServletResponse);
appointmentResource.setContextUriInfo(_uriInfo);
appointmentResource.setContextUser(_user);
}
private static ComponentServiceObjects<AppointmentResource>
_appointmentResourceComponentServiceObjects;
private AcceptLanguage _acceptLanguage;
private Company _company;
private HttpServletRequest _httpServletRequest;
private HttpServletResponse _httpServletResponse;
private UriInfo _uriInfo;
private User _user;
}
| 4,082 | 0.803423 | 0.799022 | 138 | 28.644928 | 22.9223 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.913043 | false | false |
7
|
5242512499233893101e581e960f246e1b85f9d6
| 7,576,322,351,183 |
1d386a6156dddc5dfe9b88a367047dc941588da1
|
/TablasBase/src/main/java/dao/ClienteDAO.java
|
7249ff63a6e7ec62d95733573ff4418d122415fb
|
[] |
no_license
|
WookieeFer/Lopez-Fernandez-APPDIS
|
https://github.com/WookieeFer/Lopez-Fernandez-APPDIS
|
4d847a3ee7d7a5dd01fac5b4254549910cd4cd6a
|
da2da3b51082ba440478ed4792a0de276f12b776
|
refs/heads/master
| 2020-04-22T06:42:07.448000 | 2019-02-11T20:48:27 | 2019-02-11T20:48:27 | 170,049,228 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Cliente;
@Stateless
public class ClienteDAO {
@Inject
private EntityManager em;
public void insertar(Cliente c) {
em.persist(c);
}
public void actualizar(Cliente c) {
em.merge(c);
}
public void eliminar(int codigo) {
em.remove(leer(codigo));
}
public Cliente leer(int codigo) {
Cliente aux = em.find(Cliente.class, codigo);
return aux;
}
public Cliente leerCedula(String cedula) {
String jpql = "SELECT c FROM Cliente c WHERE c.cedula LIKE ?1";
Query query = em.createQuery(jpql, Cliente.class);
query.setParameter(1, cedula);
Cliente aux = (Cliente) query.getSingleResult();
return aux;
}
public Cliente login(String usuario, String contrasenia) {
String jpql = "SELECT c FROM Cliente c WHERE c.correo LIKE ?1 AND c.cedula LIKE ?2";
Query query = em.createQuery(jpql, Cliente.class);
query.setParameter(1, usuario);
query.setParameter(2, contrasenia);
Cliente aux = (Cliente) query.getSingleResult();
return aux;
}
public List<Cliente> listarClientes() {
String jpql = "Select c From Cliente c";
Query query = em.createQuery(jpql, Cliente.class);
List<Cliente> clientes = query.getResultList();
return clientes;
}
}
|
UTF-8
|
Java
| 1,364 |
java
|
ClienteDAO.java
|
Java
|
[] | null |
[] |
package dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Cliente;
@Stateless
public class ClienteDAO {
@Inject
private EntityManager em;
public void insertar(Cliente c) {
em.persist(c);
}
public void actualizar(Cliente c) {
em.merge(c);
}
public void eliminar(int codigo) {
em.remove(leer(codigo));
}
public Cliente leer(int codigo) {
Cliente aux = em.find(Cliente.class, codigo);
return aux;
}
public Cliente leerCedula(String cedula) {
String jpql = "SELECT c FROM Cliente c WHERE c.cedula LIKE ?1";
Query query = em.createQuery(jpql, Cliente.class);
query.setParameter(1, cedula);
Cliente aux = (Cliente) query.getSingleResult();
return aux;
}
public Cliente login(String usuario, String contrasenia) {
String jpql = "SELECT c FROM Cliente c WHERE c.correo LIKE ?1 AND c.cedula LIKE ?2";
Query query = em.createQuery(jpql, Cliente.class);
query.setParameter(1, usuario);
query.setParameter(2, contrasenia);
Cliente aux = (Cliente) query.getSingleResult();
return aux;
}
public List<Cliente> listarClientes() {
String jpql = "Select c From Cliente c";
Query query = em.createQuery(jpql, Cliente.class);
List<Cliente> clientes = query.getResultList();
return clientes;
}
}
| 1,364 | 0.722874 | 0.718475 | 60 | 21.733334 | 21.005449 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.533333 | false | false |
7
|
7b8246701a0730a933b29d177c148eec9af035bf
| 19,335,942,806,593 |
c774d25f74d7128b247ae2c1569fd5046c41bce8
|
/org.tolven.dataextract/ejb/source/org/tolven/app/DataField.java
|
30850a56d748a33dced96e39593154cc5ab8fa5e
|
[] |
no_license
|
dubrsl/tolven
|
https://github.com/dubrsl/tolven
|
f42744237333447a5dd8348ae991bb5ffcb5a2d3
|
0e292799b42ae7364050749705eff79952c1b5d3
|
refs/heads/master
| 2021-01-01T18:38:36.978000 | 2011-11-11T14:40:13 | 2011-11-11T14:40:13 | 40,418,393 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (C) 2009 Tolven Inc
* 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 2.1 of the License, or (at your option) 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.
*
* Contact: info@tolvenhealth.com
*
* @author John Churin
* @version $Id: DataField.java,v 1.2 2009/08/21 04:27:51 jchurin Exp $
*/
package org.tolven.app;
import java.io.Serializable;
/**
* A compact representation of fields to be queried including both internal and external fields.
* The natural sort order is by external field name, which can have dot separated segments.
* A field is also assigned a presentation order which can be used to change the order in which
* fields are later returned.
* @author John Churin
*
*/
@SuppressWarnings("serial")
public class DataField implements Serializable, Comparable<DataField> {
private String internal[];
private String external[];
private boolean enabled;
private String displayFunction;
/**
* Construct a new DataField. the field is initially enabled and assigned a presentationOrder of zero.
* @param external
* @param internal
*/
public DataField( String external, String internal, boolean enabled, String displayFunction) {
this.internal = internal.split("\\.");
this.external = external.split("\\.");
this.enabled = enabled;
this.displayFunction = displayFunction;
}
public String getDisplayFunction() {
return displayFunction;
}
public String[] getInternalSegments() {
return internal;
}
/**
* Return the final field, irrespective of the path to that field. For example,
* parent01.string01 means return string01.
* @return The field name
*/
public String getInternalField() {
return internal[internal.length-1];
}
public String[] getExternalSegments() {
return external;
}
public String getInternal() {
StringBuffer sb = new StringBuffer();
for (int x = 0; x < internal.length; x++) {
if (x > 0) {
sb.append('.');
}
sb.append(internal[x]);
}
return sb.toString();
}
public String getExternal() {
StringBuffer sb = new StringBuffer();
for (int x = 0; x < external.length; x++) {
if (x > 0) {
sb.append('.');
}
sb.append(external[x]);
}
return sb.toString();
}
/**
* Compare a DataField which means comparing each string segment of the internal name.
* id sorts first in the group. Level of indirection controls major sort.
*/
@Override
public int compareTo(DataField other) {
if (other==null) {
throw new RuntimeException( "Cannot compare null to a " + this.getClass().getSimpleName());
}
int thisLength = external.length;
if ("id".equals(external[thisLength-1])) {
thisLength--;
}
int otherLength = other.external.length;
if ("id".equals(other.external[otherLength-1])) {
otherLength--;
}
int lenDiff = thisLength - otherLength;
if (lenDiff!=0) {
return lenDiff;
}
for (int x = 0; x < thisLength; x++) {
int r = external[x].compareToIgnoreCase(other.external[x]);
if (r!=0) return r;
}
return thisLength - otherLength;
}
@Override
public boolean equals(Object obj) {
return (getLabel().equals(((DataField)obj).getLabel()));
}
@Override
public int hashCode() {
return internal.hashCode();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getLabel() {
return getExternal() + " (" + getInternal() + ")";
}
@Override
public String toString() {
return getLabel();
}
}
|
UTF-8
|
Java
| 4,020 |
java
|
DataField.java
|
Java
|
[
{
"context": " Public License for more details.\r\n *\r\n * Contact: info@tolvenhealth.com \r\n *\r\n * @author John Churin\r\n * @version $Id: Da",
"end": 599,
"score": 0.9999229311943054,
"start": 578,
"tag": "EMAIL",
"value": "info@tolvenhealth.com"
},
{
"context": " * Contact: info@tolvenhealth.com \r\n *\r\n * @author John Churin\r\n * @version $Id: DataField.java,v 1.2 2009/08/21",
"end": 628,
"score": 0.9998645782470703,
"start": 617,
"tag": "NAME",
"value": "John Churin"
},
{
"context": "n which\r\n * fields are later returned.\r\n * @author John Churin\r\n *\r\n */\r\n@SuppressWarnings(\"serial\")\r\npublic cla",
"end": 1118,
"score": 0.9998676776885986,
"start": 1107,
"tag": "NAME",
"value": "John Churin"
}
] | null |
[] |
/*
* Copyright (C) 2009 Tolven Inc
* 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 2.1 of the License, or (at your option) 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.
*
* Contact: <EMAIL>
*
* @author <NAME>
* @version $Id: DataField.java,v 1.2 2009/08/21 04:27:51 jchurin Exp $
*/
package org.tolven.app;
import java.io.Serializable;
/**
* A compact representation of fields to be queried including both internal and external fields.
* The natural sort order is by external field name, which can have dot separated segments.
* A field is also assigned a presentation order which can be used to change the order in which
* fields are later returned.
* @author <NAME>
*
*/
@SuppressWarnings("serial")
public class DataField implements Serializable, Comparable<DataField> {
private String internal[];
private String external[];
private boolean enabled;
private String displayFunction;
/**
* Construct a new DataField. the field is initially enabled and assigned a presentationOrder of zero.
* @param external
* @param internal
*/
public DataField( String external, String internal, boolean enabled, String displayFunction) {
this.internal = internal.split("\\.");
this.external = external.split("\\.");
this.enabled = enabled;
this.displayFunction = displayFunction;
}
public String getDisplayFunction() {
return displayFunction;
}
public String[] getInternalSegments() {
return internal;
}
/**
* Return the final field, irrespective of the path to that field. For example,
* parent01.string01 means return string01.
* @return The field name
*/
public String getInternalField() {
return internal[internal.length-1];
}
public String[] getExternalSegments() {
return external;
}
public String getInternal() {
StringBuffer sb = new StringBuffer();
for (int x = 0; x < internal.length; x++) {
if (x > 0) {
sb.append('.');
}
sb.append(internal[x]);
}
return sb.toString();
}
public String getExternal() {
StringBuffer sb = new StringBuffer();
for (int x = 0; x < external.length; x++) {
if (x > 0) {
sb.append('.');
}
sb.append(external[x]);
}
return sb.toString();
}
/**
* Compare a DataField which means comparing each string segment of the internal name.
* id sorts first in the group. Level of indirection controls major sort.
*/
@Override
public int compareTo(DataField other) {
if (other==null) {
throw new RuntimeException( "Cannot compare null to a " + this.getClass().getSimpleName());
}
int thisLength = external.length;
if ("id".equals(external[thisLength-1])) {
thisLength--;
}
int otherLength = other.external.length;
if ("id".equals(other.external[otherLength-1])) {
otherLength--;
}
int lenDiff = thisLength - otherLength;
if (lenDiff!=0) {
return lenDiff;
}
for (int x = 0; x < thisLength; x++) {
int r = external[x].compareToIgnoreCase(other.external[x]);
if (r!=0) return r;
}
return thisLength - otherLength;
}
@Override
public boolean equals(Object obj) {
return (getLabel().equals(((DataField)obj).getLabel()));
}
@Override
public int hashCode() {
return internal.hashCode();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getLabel() {
return getExternal() + " (" + getInternal() + ")";
}
@Override
public String toString() {
return getLabel();
}
}
| 3,996 | 0.667662 | 0.658209 | 146 | 25.534246 | 27.06111 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.568493 | false | false |
7
|
5d8968cff39a2c11750309c4a9a34618597e13ab
| 3,642,132,307,365 |
9f8c874ebca18ab65d18f1f4d6a2aad7ff74d37e
|
/ repsystestbed/RepSysTestbedConsole/src/cu/rst/tests/ARFFTest.java
|
2e3bb4ab66ff47ed50077567519bae85c19f910d
|
[] |
no_license
|
codeaudit/repsystestbed
|
https://github.com/codeaudit/repsystestbed
|
d326eed79ed1110cb4245b867a2540bd4b89a2b0
|
871cf3db52c5288ee038c3d013db8d479f2db475
|
refs/heads/master
| 2021-01-23T05:10:35.884000 | 2015-09-15T02:09:13 | 2015-09-15T02:09:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cu.rst.tests;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.log4j.BasicConfigurator;
import cu.rst.core.graphs.Feedback;
import cu.rst.util.FeedbackGenerator;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class ARFFTest {
public static void testbedARFF() throws Exception
{
//header
FastVector attributes = new FastVector();
Attribute groupID = new Attribute("groupID");
Attribute agentID = new Attribute("agentID");
FastVector strategyAttributes = new FastVector();
Attribute feedbackMean = new Attribute("feedbackMean");
Attribute feedbackStdDev = new Attribute("feedbackStdDev");
Attribute targetGroupdID = new Attribute("targetGroupID");
strategyAttributes.addElement(feedbackMean);
strategyAttributes.addElement(feedbackStdDev);
strategyAttributes.addElement(targetGroupdID);
Instances temp = new Instances("strategy", strategyAttributes, 3);
Attribute strategy = new Attribute("strategy", temp);
attributes.addElement(groupID);
attributes.addElement(agentID);
attributes.addElement(strategy);
//instances
Instances data = new Instances("mydataset", attributes, 0);
double[] values = new double[data.numAttributes()];
values[0] = 0;
values[1] = 0;
Instances strategyData = new Instances(data.attribute(2).relation(), 0);
double[] values4Strategy = new double[3];
values4Strategy[0] = 0.8;
values4Strategy[1] = 0.1;
values4Strategy[2] = 0;
strategyData.add(new Instance(1.0, values4Strategy));
values[2] = data.attribute(2).addRelation(strategyData);
data.add(new Instance(1.0, values));
System.out.println(data);
}
public static void testbedARFFfromFile() throws Exception
{
Attribute groupID = new Attribute("groupID", (FastVector) null);
DataSource source = new DataSource("testMe.arff");
Instances instances = source.getDataSet();
//System.out.println(instances);
System.out.println(instances.instance(0));
Enumeration enu = instances.enumerateInstances();
while(enu.hasMoreElements())
{
Instance temp = (Instance)enu.nextElement();
for(int i=0;i<temp.numValues();i++)
{
System.out.println(temp.stringValue(i));
}
}
//System.out.println(instances.instance(0).stringValue(2));
}
public static void sampleFromWeka() throws Exception
{
FastVector atts;
FastVector attsRel;
FastVector attVals;
FastVector attValsRel;
Instances data;
Instances dataRel;
double[] vals;
double[] valsRel;
int i;
// 1. set up attributes
atts = new FastVector();
// - numeric
atts.addElement(new Attribute("att1"));
// - nominal
attVals = new FastVector();
for (i = 0; i < 5; i++)
attVals.addElement("val" + (i+1));
atts.addElement(new Attribute("att2", attVals));
// - string
atts.addElement(new Attribute("att3", (FastVector) null));
// - date
atts.addElement(new Attribute("att4", "yyyy-MM-dd"));
// - relational
attsRel = new FastVector();
// -- numeric
attsRel.addElement(new Attribute("att5.1"));
// -- nominal
attValsRel = new FastVector();
for (i = 0; i < 5; i++)
attValsRel.addElement("val5." + (i+1));
attsRel.addElement(new Attribute("att5.2", attValsRel));
dataRel = new Instances("att5", attsRel, 0);
atts.addElement(new Attribute("att5", dataRel, 0));
// 2. create Instances object
data = new Instances("MyRelation", atts, 0);
// 3. fill with data
// first instance
vals = new double[data.numAttributes()];
// - numeric
vals[0] = Math.PI;
// - nominal
vals[1] = attVals.indexOf("val3");
// - string
vals[2] = data.attribute(2).addStringValue("This is a string!");
// - date
vals[3] = data.attribute(3).parseDate("2001-11-09");
// - relational
dataRel = new Instances(data.attribute(4).relation(), 0);
// -- first instance
valsRel = new double[2];
valsRel[0] = Math.PI + 1;
valsRel[1] = attValsRel.indexOf("val5.3");
dataRel.add(new Instance(1.0, valsRel));
// -- second instance
valsRel = new double[2];
valsRel[0] = Math.PI + 2;
valsRel[1] = attValsRel.indexOf("val5.2");
dataRel.add(new Instance(1.0, valsRel));
vals[4] = data.attribute(4).addRelation(dataRel);
// add
data.add(new Instance(1.0, vals));
// second instance
vals = new double[data.numAttributes()]; // important: needs NEW array!
// - numeric
vals[0] = Math.E;
// - nominal
vals[1] = attVals.indexOf("val1");
// - string
//vals[2] = data.attribute(2).addStringValue("And another one!");
vals[2] = Instance.missingValue();
// - date
vals[3] = data.attribute(3).parseDate("2000-12-01");
// - relational
dataRel = new Instances(data.attribute(4).relation(), 0);
// -- first instance
valsRel = new double[2];
valsRel[0] = Math.E + 1;
valsRel[1] = attValsRel.indexOf("val5.4");
dataRel.add(new Instance(1.0, valsRel));
// -- second instance
valsRel = new double[2];
valsRel[0] = Math.E + 2;
valsRel[1] = attValsRel.indexOf("val5.1");
dataRel.add(new Instance(1.0, valsRel));
vals[4] = data.attribute(4).addRelation(dataRel);
// add
Instance inst = new Instance(1.0, vals);
inst.setMissing(2);
data.add(inst);
// 4. output data
System.out.println(data);
}
public static ArrayList<Feedback> readFeedbacksArff() throws Exception
{
FeedbackGenerator feedbackGen = new FeedbackGenerator();
ArrayList<Feedback> feedbacks = (ArrayList<Feedback>) feedbackGen.generateHardcoded("feedbacks.arff");
System.out.println(feedbacks.size());
return feedbacks;
}
public static void main(String[] args) throws Exception
{
//sampleFromWeka();
//testbedARFF();
//testbedARFFfromFile();
BasicConfigurator.configure();
//readFeedbacksArff();
//DefaultArffFeedbackGenerator.writeToArff(readFeedbacksArff(), "output.arff");
FeedbackGenerator feedbackgen = new FeedbackGenerator();
feedbackgen.writeToArff((ArrayList<Feedback>) feedbackgen.generate("feedbackgen.properties"),
"autofeedbacks.arff");
}
}
|
UTF-8
|
Java
| 6,637 |
java
|
ARFFTest.java
|
Java
|
[] | null |
[] |
package cu.rst.tests;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.log4j.BasicConfigurator;
import cu.rst.core.graphs.Feedback;
import cu.rst.util.FeedbackGenerator;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class ARFFTest {
public static void testbedARFF() throws Exception
{
//header
FastVector attributes = new FastVector();
Attribute groupID = new Attribute("groupID");
Attribute agentID = new Attribute("agentID");
FastVector strategyAttributes = new FastVector();
Attribute feedbackMean = new Attribute("feedbackMean");
Attribute feedbackStdDev = new Attribute("feedbackStdDev");
Attribute targetGroupdID = new Attribute("targetGroupID");
strategyAttributes.addElement(feedbackMean);
strategyAttributes.addElement(feedbackStdDev);
strategyAttributes.addElement(targetGroupdID);
Instances temp = new Instances("strategy", strategyAttributes, 3);
Attribute strategy = new Attribute("strategy", temp);
attributes.addElement(groupID);
attributes.addElement(agentID);
attributes.addElement(strategy);
//instances
Instances data = new Instances("mydataset", attributes, 0);
double[] values = new double[data.numAttributes()];
values[0] = 0;
values[1] = 0;
Instances strategyData = new Instances(data.attribute(2).relation(), 0);
double[] values4Strategy = new double[3];
values4Strategy[0] = 0.8;
values4Strategy[1] = 0.1;
values4Strategy[2] = 0;
strategyData.add(new Instance(1.0, values4Strategy));
values[2] = data.attribute(2).addRelation(strategyData);
data.add(new Instance(1.0, values));
System.out.println(data);
}
public static void testbedARFFfromFile() throws Exception
{
Attribute groupID = new Attribute("groupID", (FastVector) null);
DataSource source = new DataSource("testMe.arff");
Instances instances = source.getDataSet();
//System.out.println(instances);
System.out.println(instances.instance(0));
Enumeration enu = instances.enumerateInstances();
while(enu.hasMoreElements())
{
Instance temp = (Instance)enu.nextElement();
for(int i=0;i<temp.numValues();i++)
{
System.out.println(temp.stringValue(i));
}
}
//System.out.println(instances.instance(0).stringValue(2));
}
public static void sampleFromWeka() throws Exception
{
FastVector atts;
FastVector attsRel;
FastVector attVals;
FastVector attValsRel;
Instances data;
Instances dataRel;
double[] vals;
double[] valsRel;
int i;
// 1. set up attributes
atts = new FastVector();
// - numeric
atts.addElement(new Attribute("att1"));
// - nominal
attVals = new FastVector();
for (i = 0; i < 5; i++)
attVals.addElement("val" + (i+1));
atts.addElement(new Attribute("att2", attVals));
// - string
atts.addElement(new Attribute("att3", (FastVector) null));
// - date
atts.addElement(new Attribute("att4", "yyyy-MM-dd"));
// - relational
attsRel = new FastVector();
// -- numeric
attsRel.addElement(new Attribute("att5.1"));
// -- nominal
attValsRel = new FastVector();
for (i = 0; i < 5; i++)
attValsRel.addElement("val5." + (i+1));
attsRel.addElement(new Attribute("att5.2", attValsRel));
dataRel = new Instances("att5", attsRel, 0);
atts.addElement(new Attribute("att5", dataRel, 0));
// 2. create Instances object
data = new Instances("MyRelation", atts, 0);
// 3. fill with data
// first instance
vals = new double[data.numAttributes()];
// - numeric
vals[0] = Math.PI;
// - nominal
vals[1] = attVals.indexOf("val3");
// - string
vals[2] = data.attribute(2).addStringValue("This is a string!");
// - date
vals[3] = data.attribute(3).parseDate("2001-11-09");
// - relational
dataRel = new Instances(data.attribute(4).relation(), 0);
// -- first instance
valsRel = new double[2];
valsRel[0] = Math.PI + 1;
valsRel[1] = attValsRel.indexOf("val5.3");
dataRel.add(new Instance(1.0, valsRel));
// -- second instance
valsRel = new double[2];
valsRel[0] = Math.PI + 2;
valsRel[1] = attValsRel.indexOf("val5.2");
dataRel.add(new Instance(1.0, valsRel));
vals[4] = data.attribute(4).addRelation(dataRel);
// add
data.add(new Instance(1.0, vals));
// second instance
vals = new double[data.numAttributes()]; // important: needs NEW array!
// - numeric
vals[0] = Math.E;
// - nominal
vals[1] = attVals.indexOf("val1");
// - string
//vals[2] = data.attribute(2).addStringValue("And another one!");
vals[2] = Instance.missingValue();
// - date
vals[3] = data.attribute(3).parseDate("2000-12-01");
// - relational
dataRel = new Instances(data.attribute(4).relation(), 0);
// -- first instance
valsRel = new double[2];
valsRel[0] = Math.E + 1;
valsRel[1] = attValsRel.indexOf("val5.4");
dataRel.add(new Instance(1.0, valsRel));
// -- second instance
valsRel = new double[2];
valsRel[0] = Math.E + 2;
valsRel[1] = attValsRel.indexOf("val5.1");
dataRel.add(new Instance(1.0, valsRel));
vals[4] = data.attribute(4).addRelation(dataRel);
// add
Instance inst = new Instance(1.0, vals);
inst.setMissing(2);
data.add(inst);
// 4. output data
System.out.println(data);
}
public static ArrayList<Feedback> readFeedbacksArff() throws Exception
{
FeedbackGenerator feedbackGen = new FeedbackGenerator();
ArrayList<Feedback> feedbacks = (ArrayList<Feedback>) feedbackGen.generateHardcoded("feedbacks.arff");
System.out.println(feedbacks.size());
return feedbacks;
}
public static void main(String[] args) throws Exception
{
//sampleFromWeka();
//testbedARFF();
//testbedARFFfromFile();
BasicConfigurator.configure();
//readFeedbacksArff();
//DefaultArffFeedbackGenerator.writeToArff(readFeedbacksArff(), "output.arff");
FeedbackGenerator feedbackgen = new FeedbackGenerator();
feedbackgen.writeToArff((ArrayList<Feedback>) feedbackgen.generate("feedbackgen.properties"),
"autofeedbacks.arff");
}
}
| 6,637 | 0.641404 | 0.621365 | 227 | 28.237885 | 21.965046 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.977974 | false | false |
7
|
45089de5203a76978fbda0eb17fd762a867134ba
| 26,860,725,487,572 |
333f094f136b377bf229f6b96da36d1d6dbb2e60
|
/publiy/src/org/msrg/publiy/pubsub/core/messagequeue/PSSessionLocal.java
|
b01b695be1a9ff17617267de4cc4c3d87c040c9d
|
[] |
no_license
|
dhungvi/publiy
|
https://github.com/dhungvi/publiy
|
50cda93b3985326ebe2992e73fef914e063b5dc8
|
3704c580b7b949d6fd565df9f4ae2e11177c9d80
|
refs/heads/master
| 2021-01-23T07:16:05.972000 | 2012-12-09T15:24:21 | 2012-12-09T15:24:21 | 35,463,036 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.msrg.publiy.pubsub.core.messagequeue;
import java.net.InetSocketAddress;
import org.msrg.publiy.communication.core.packet.IRawPacket;
import org.msrg.publiy.communication.core.sessions.ISession;
import org.msrg.publiy.communication.core.sessions.ISessionLocal;
import org.msrg.publiy.communication.core.sessions.SessionConnectionType;
public class PSSessionLocal extends PSSession {
private ISessionLocal _session;
public String toString(){
return "PSSessionLocal: \t" + _session.getRemoteAddress() + "::" + _session.getSessionConnectionType();// + " _ " + _session;
}
public InetSocketAddress getRemoteAddress(){
return _session.getRemoteAddress();
}
public ISession getISession(){
return _session;
}
public SessionConnectionType getSessionConnectionType(){
return _session.getSessionConnectionType();
}
protected PSSessionLocal(ISessionLocal sessionLocal, MessageQueue mQ){
super(sessionLocal, mQ);
_session = sessionLocal;
}
void swapMessageQueue(IMessageQueue newMQ){
throw new UnsupportedOperationException();
}
void resetSession(ISession session, InetSocketAddress[] nodesInBetween){
return;
}
boolean advance(){
return false;
}
@Override
public int hashCode(){
return _session.hashCode();
}
@Override
public boolean equals(Object obj){
if ( obj == null )
return false;
if ( !this.getClass().isInstance(obj) )
return false;
PSSessionLocal pssObj = (PSSessionLocal) obj;
if ( pssObj._session.getRemoteAddress().equals(this._session.getRemoteAddress()) )
return true;
return false;
}
public boolean send(IRawPacket raw){
throw new UnsupportedOperationException("PSSessionLocal does not support the send operation.");
}
public void cancel(){
return;
}
}
|
UTF-8
|
Java
| 1,784 |
java
|
PSSessionLocal.java
|
Java
|
[] | null |
[] |
package org.msrg.publiy.pubsub.core.messagequeue;
import java.net.InetSocketAddress;
import org.msrg.publiy.communication.core.packet.IRawPacket;
import org.msrg.publiy.communication.core.sessions.ISession;
import org.msrg.publiy.communication.core.sessions.ISessionLocal;
import org.msrg.publiy.communication.core.sessions.SessionConnectionType;
public class PSSessionLocal extends PSSession {
private ISessionLocal _session;
public String toString(){
return "PSSessionLocal: \t" + _session.getRemoteAddress() + "::" + _session.getSessionConnectionType();// + " _ " + _session;
}
public InetSocketAddress getRemoteAddress(){
return _session.getRemoteAddress();
}
public ISession getISession(){
return _session;
}
public SessionConnectionType getSessionConnectionType(){
return _session.getSessionConnectionType();
}
protected PSSessionLocal(ISessionLocal sessionLocal, MessageQueue mQ){
super(sessionLocal, mQ);
_session = sessionLocal;
}
void swapMessageQueue(IMessageQueue newMQ){
throw new UnsupportedOperationException();
}
void resetSession(ISession session, InetSocketAddress[] nodesInBetween){
return;
}
boolean advance(){
return false;
}
@Override
public int hashCode(){
return _session.hashCode();
}
@Override
public boolean equals(Object obj){
if ( obj == null )
return false;
if ( !this.getClass().isInstance(obj) )
return false;
PSSessionLocal pssObj = (PSSessionLocal) obj;
if ( pssObj._session.getRemoteAddress().equals(this._session.getRemoteAddress()) )
return true;
return false;
}
public boolean send(IRawPacket raw){
throw new UnsupportedOperationException("PSSessionLocal does not support the send operation.");
}
public void cancel(){
return;
}
}
| 1,784 | 0.742713 | 0.742713 | 76 | 22.473684 | 26.843834 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.605263 | false | false |
7
|
3a7c024022002028a029894511b47034c2fed41f
| 19,816,979,133,908 |
fc74e78e7fffc90dd7e325032b1a9dc767935eb8
|
/src/main/java/net/ebook/web/logic/impl/MenuLogicImpl.java
|
1879dbb7d8a75218580b12daf336e74394a2cf9a
|
[] |
no_license
|
hwedwin/ebook-site
|
https://github.com/hwedwin/ebook-site
|
ca8c323884216bed3fde97e4bed1d67dafea9b0d
|
194fc8c5e521ce1761a8c943981da270f955f600
|
refs/heads/master
| 2020-03-06T18:32:00.413000 | 2018-02-09T08:17:08 | 2018-02-09T08:17:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.ebook.web.logic.impl;
import net.ebook.service.MenuService;
import net.ebook.web.data.MenuVO;
import net.ebook.web.logic.MenuLogic;
import net.ebook.web.wrapper.MenuVOWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @Author ROKG
* @Description
* @Date: Created in 下午2:04 2018/1/23
* @Modified By:
*/
@Service
public class MenuLogicImpl implements MenuLogic {
@Autowired
MenuService menuService;
@Autowired
MenuVOWrapper menuVOWrapper;
@Override
public List<MenuVO> getMenusForLogin(Long roleId){
List<MenuVO> menuVOS=new ArrayList<>();
List<MenuVO> menuVOList=menuVOWrapper.wrap(menuService.getMenusByRoleId(roleId));
for (MenuVO m: menuVOList) {
if (!menuVOS.stream().anyMatch(menuVO -> menuVO.getUrl().equals(m.getUrl()))){
menuVOS.add(m);
}
}
return menuVOS;
}
}
|
UTF-8
|
Java
| 1,028 |
java
|
MenuLogicImpl.java
|
Java
|
[
{
"context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @Author ROKG\n * @Description\n * @Date: Created in 下午2:04 2018/",
"end": 371,
"score": 0.9996537566184998,
"start": 367,
"tag": "USERNAME",
"value": "ROKG"
}
] | null |
[] |
package net.ebook.web.logic.impl;
import net.ebook.service.MenuService;
import net.ebook.web.data.MenuVO;
import net.ebook.web.logic.MenuLogic;
import net.ebook.web.wrapper.MenuVOWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* @Author ROKG
* @Description
* @Date: Created in 下午2:04 2018/1/23
* @Modified By:
*/
@Service
public class MenuLogicImpl implements MenuLogic {
@Autowired
MenuService menuService;
@Autowired
MenuVOWrapper menuVOWrapper;
@Override
public List<MenuVO> getMenusForLogin(Long roleId){
List<MenuVO> menuVOS=new ArrayList<>();
List<MenuVO> menuVOList=menuVOWrapper.wrap(menuService.getMenusByRoleId(roleId));
for (MenuVO m: menuVOList) {
if (!menuVOS.stream().anyMatch(menuVO -> menuVO.getUrl().equals(m.getUrl()))){
menuVOS.add(m);
}
}
return menuVOS;
}
}
| 1,028 | 0.693359 | 0.683594 | 39 | 25.256411 | 22.755915 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false |
7
|
bd9875e4f1f39bedb640b57c060ee224ef59acce
| 19,061,064,887,317 |
5ae1f8f973d351caf16f50c175585b9caee859b1
|
/Meal/src/DB/Inserts.java
|
1b07666a021f9f570ea6e00e4062231fa6d676a9
|
[] |
no_license
|
d4731qjs/greduate
|
https://github.com/d4731qjs/greduate
|
6056248aaf6c9744f54d47b388b88f9c4ddc9aa6
|
c39a43b34e2ad8f72ab263eda088f6dab86626bb
|
refs/heads/master
| 2023-01-05T03:46:47.370000 | 2020-11-07T14:13:49 | 2020-11-07T14:13:49 | 310,858,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package DB;
import java.io.*;
import java.util.*;
import java.sql.*;
public class Inserts {
String[] address = {"식권발매//식권발매//DataFiles//member.txt",
"식권발매//식권발매//DataFiles//cuisine.txt",
"식권발매//식권발매//DataFiles//meal.txt",
"식권발매//식권발매//DataFiles//orderlist.txt"
};
String[] insert_Sentance = {"INSERT INTO member VALUES(?,?,?,?)",
"INSERT INTO cuisine VALUES(?,?)",
"INSERT INTO meal VALUES(?,?,?,?,?,?)",
"INSERT INTO orderlist VALUES(?,?,?,?,?,?,?)"};
PreparedStatement ps = null;
Connection con = null;
int count;
public Inserts() {
con = Driver_Connect.makeConnection("/meal");
for(int i = 0; i <4; i++) {
try {
Scanner fscanner = new Scanner(new FileInputStream(address[i]));
ps = con.prepareStatement(insert_Sentance[i]);
fscanner.nextLine();
while(fscanner.hasNext()) {
String text = fscanner.nextLine();
StringTokenizer st = new StringTokenizer(text,"\t");
Vector<String> data = new Vector<String>();
while(st.hasMoreTokens()) {
String token = st.nextToken();
data.add(token);
}
for(int j = 0; j < data.size(); j++) {
ps.setString(j+1,data.get(j));
}
int result = ps.executeUpdate();
if(result == 1) {
System.out.println("추가 성공");
}else {
System.out.println("추가 실패");
}
}
}catch(IOException e) {
System.out.println(e.getMessage());
}catch(SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
new Create_Table();
new Inserts();
}
}
|
UTF-8
|
Java
| 1,782 |
java
|
Inserts.java
|
Java
|
[] | null |
[] |
package DB;
import java.io.*;
import java.util.*;
import java.sql.*;
public class Inserts {
String[] address = {"식권발매//식권발매//DataFiles//member.txt",
"식권발매//식권발매//DataFiles//cuisine.txt",
"식권발매//식권발매//DataFiles//meal.txt",
"식권발매//식권발매//DataFiles//orderlist.txt"
};
String[] insert_Sentance = {"INSERT INTO member VALUES(?,?,?,?)",
"INSERT INTO cuisine VALUES(?,?)",
"INSERT INTO meal VALUES(?,?,?,?,?,?)",
"INSERT INTO orderlist VALUES(?,?,?,?,?,?,?)"};
PreparedStatement ps = null;
Connection con = null;
int count;
public Inserts() {
con = Driver_Connect.makeConnection("/meal");
for(int i = 0; i <4; i++) {
try {
Scanner fscanner = new Scanner(new FileInputStream(address[i]));
ps = con.prepareStatement(insert_Sentance[i]);
fscanner.nextLine();
while(fscanner.hasNext()) {
String text = fscanner.nextLine();
StringTokenizer st = new StringTokenizer(text,"\t");
Vector<String> data = new Vector<String>();
while(st.hasMoreTokens()) {
String token = st.nextToken();
data.add(token);
}
for(int j = 0; j < data.size(); j++) {
ps.setString(j+1,data.get(j));
}
int result = ps.executeUpdate();
if(result == 1) {
System.out.println("추가 성공");
}else {
System.out.println("추가 실패");
}
}
}catch(IOException e) {
System.out.println(e.getMessage());
}catch(SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
new Create_Table();
new Inserts();
}
}
| 1,782 | 0.551704 | 0.548766 | 73 | 21.315069 | 18.381704 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.767123 | false | false |
7
|
962fc7ee6ca3d518e0d73c4ee2276a6b32680c89
| 489,626,312,291 |
e904752834df4f17ead40fadd234f4a512048a32
|
/Hello.java
|
9272d15353b2ddea11ae554200565f695d302f17
|
[] |
no_license
|
kommanab/practice
|
https://github.com/kommanab/practice
|
23d43966c553ec0550a62b0a103de6dbd95a5175
|
b9aedf3cfef260e092bb9bc0d881ffb4a95f52e0
|
refs/heads/master
| 2020-08-22T05:59:23.345000 | 2019-10-20T08:51:50 | 2019-10-20T08:51:50 | 216,332,568 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Hello
{
public static void main(String args [])
{
System.out.println("hello i am your lLove Bharath");
}
}
|
UTF-8
|
Java
| 132 |
java
|
Hello.java
|
Java
|
[
{
"context": "\n System.out.println(\"hello i am your lLove Bharath\");\n }\n}",
"end": 121,
"score": 0.9108902812004089,
"start": 114,
"tag": "NAME",
"value": "Bharath"
}
] | null |
[] |
class Hello
{
public static void main(String args [])
{
System.out.println("hello i am your lLove Bharath");
}
}
| 132 | 0.606061 | 0.606061 | 7 | 18 | 21.889332 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false |
7
|
f3eb6acdb12f8d0d0cc58ca5182a7225691d452b
| 9,423,158,289,730 |
3ee988fe7bd8824bbb1e03a6f8fedd0a368562bb
|
/src/me/redraskaldoesgaming/BungeeReset/ConfigManager.java
|
563517c2164751f49af5b38bd6f084807b1eb3c2
|
[] |
no_license
|
xiTzJardix/BungeeReset
|
https://github.com/xiTzJardix/BungeeReset
|
9929aa759cc98c41bf203b07dcc36056f65e2434
|
ed198b6c787396b10c6a471b967a74985b4b6997
|
refs/heads/master
| 2020-02-04T19:15:28.711000 | 2014-11-24T22:51:54 | 2014-11-24T22:51:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package me.redraskaldoesgaming.BungeeReset;
import org.bukkit.configuration.Configuration;
public class ConfigManager {
Configuration config = BungeeReset.getInstance().getConfig();
static ConfigManager configmanager = new ConfigManager();
public static ConfigManager getInstance() {
return configmanager;
}
public void saveConfig() {
BungeeReset.getInstance().saveConfig();
}
public void addVariable(String name, Object value) {
config.addDefault(name, value);
config.options().copyDefaults(true);
saveConfig();
}
public void setVariable(String name, Object value) {
config.set(name, value);
saveConfig();
}
public void removeVariable(String name) {
config.set(name, "");
saveConfig();
}
public String getVariable(String name) {
return config.getString(name);
}
public boolean isSetup() {
if(config.getString("BungeeReset") == null) {
return true;
} else {
return false;
}
}
public void setup() {
addVariable("BungeeReset", "");
addVariable("BungeeReset.world", "world");
addVariable("BungeeReset.kick-message", "&4&lThat game is in progress!");
addVariable("BungeeReset.restart-message", "&4&lThe game is now restarting!");
}
}
|
UTF-8
|
Java
| 1,207 |
java
|
ConfigManager.java
|
Java
|
[
{
"context": "package me.redraskaldoesgaming.BungeeReset;\n\nimport org.bukkit.configuration.Con",
"end": 30,
"score": 0.956210196018219,
"start": 11,
"tag": "USERNAME",
"value": "redraskaldoesgaming"
}
] | null |
[] |
package me.redraskaldoesgaming.BungeeReset;
import org.bukkit.configuration.Configuration;
public class ConfigManager {
Configuration config = BungeeReset.getInstance().getConfig();
static ConfigManager configmanager = new ConfigManager();
public static ConfigManager getInstance() {
return configmanager;
}
public void saveConfig() {
BungeeReset.getInstance().saveConfig();
}
public void addVariable(String name, Object value) {
config.addDefault(name, value);
config.options().copyDefaults(true);
saveConfig();
}
public void setVariable(String name, Object value) {
config.set(name, value);
saveConfig();
}
public void removeVariable(String name) {
config.set(name, "");
saveConfig();
}
public String getVariable(String name) {
return config.getString(name);
}
public boolean isSetup() {
if(config.getString("BungeeReset") == null) {
return true;
} else {
return false;
}
}
public void setup() {
addVariable("BungeeReset", "");
addVariable("BungeeReset.world", "world");
addVariable("BungeeReset.kick-message", "&4&lThat game is in progress!");
addVariable("BungeeReset.restart-message", "&4&lThe game is now restarting!");
}
}
| 1,207 | 0.713339 | 0.711682 | 52 | 22.211538 | 21.830057 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.826923 | false | false |
7
|
a50e3ad149b4eed0a74c1f499a53c27684f4ab3f
| 4,982,162,094,785 |
e8d0308dd2a76d4f2965b5ba90fae6ff848a304f
|
/SPPSP/SPPSPExamenTema01/src/cat/paucasesnovescifp/sppsp/Compara2.java
|
81d6cbcea43dc0daceb82d08ecb3b255880cbfc9
|
[] |
no_license
|
MartaCorVa/DAM2
|
https://github.com/MartaCorVa/DAM2
|
8b79a37b6ed848cc1309a7460d29266d4b1dcb8e
|
e142059989b2f86b607b815d6cb791e2df8a49af
|
refs/heads/master
| 2023-06-09T20:50:19.617000 | 2020-01-30T19:06:02 | 2020-01-30T19:06:02 | 215,861,836 | 0 | 0 | null | false | 2023-07-22T19:04:36 | 2019-10-17T18:39:47 | 2020-01-30T19:07:16 | 2023-07-22T19:04:35 | 651,710 | 0 | 0 | 15 |
Python
| false | false |
package cat.paucasesnovescifp.sppsp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author marta
*/
public class Compara2 {
public static void main(String[] args) {
String nom = "";
// Utilitzam un BufferedReader per lletgir el nom del proces que indicam a la clase pare
try (BufferedReader sc = new BufferedReader(new InputStreamReader(System.in))){
nom = sc.readLine();
} catch (IOException ex) {
Logger.getLogger(Compara2.class.getName()).log(Level.SEVERE, null, ex);
}
// Cream la variable num1 i l'hi afegim el primer argument
int num1 = Integer.parseInt(args[0]);
// Cream la variable num2 i l'hi afegim el segon argument
int num2 = Integer.parseInt(args[1]);
// Feim un if() amb les tres condicions possibles
if (num1 > num2) {
System.out.println("Proces fill " + nom + " - El primer nombre " + num1 + " es major que el segon nombre " + num2);
} else if (num1 < num2) {
System.out.println("Proces fill " + nom + " - El primer nombre " + num1 + " es menor que el segon nombre " + num2);
} else {
System.out.println("Proces fill " + nom + " - El primer nombre " + num1 + " es igual que el segon nombre " + num2);
}
}
}
|
UTF-8
|
Java
| 1,462 |
java
|
Compara2.java
|
Java
|
[
{
"context": "mport java.util.logging.Logger;\n\n/**\n *\n * @author marta\n */\npublic class Compara2 {\n\n public static vo",
"end": 220,
"score": 0.9974379539489746,
"start": 215,
"tag": "USERNAME",
"value": "marta"
}
] | null |
[] |
package cat.paucasesnovescifp.sppsp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author marta
*/
public class Compara2 {
public static void main(String[] args) {
String nom = "";
// Utilitzam un BufferedReader per lletgir el nom del proces que indicam a la clase pare
try (BufferedReader sc = new BufferedReader(new InputStreamReader(System.in))){
nom = sc.readLine();
} catch (IOException ex) {
Logger.getLogger(Compara2.class.getName()).log(Level.SEVERE, null, ex);
}
// Cream la variable num1 i l'hi afegim el primer argument
int num1 = Integer.parseInt(args[0]);
// Cream la variable num2 i l'hi afegim el segon argument
int num2 = Integer.parseInt(args[1]);
// Feim un if() amb les tres condicions possibles
if (num1 > num2) {
System.out.println("Proces fill " + nom + " - El primer nombre " + num1 + " es major que el segon nombre " + num2);
} else if (num1 < num2) {
System.out.println("Proces fill " + nom + " - El primer nombre " + num1 + " es menor que el segon nombre " + num2);
} else {
System.out.println("Proces fill " + nom + " - El primer nombre " + num1 + " es igual que el segon nombre " + num2);
}
}
}
| 1,462 | 0.603967 | 0.591655 | 38 | 37.473682 | 36.075024 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false |
7
|
cb810538dddea3f493054d5834ea2850798d5580
| 19,164,144,139,721 |
037637a2c0d177362285e0608d4f4f00dc4cfce9
|
/core/camel-api/src/main/java/org/apache/camel/spi/SendDynamicAware.java
|
dfe7d7a1f62c4bddd5b60dcbaf6ddb3a06de423b
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
dmgerman/camel
|
https://github.com/dmgerman/camel
|
07379b6a1d191078b085b62bbb0a6732141994aa
|
cab53c57b3e58871df1f96d54b2a2ad5a73ce220
|
refs/heads/master
| 2023-01-03T23:00:15.190000 | 2019-12-20T08:30:29 | 2019-12-20T08:30:29 | 230,528,998 | 0 | 0 |
Apache-2.0
| false | 2023-01-02T22:14:35 | 2019-12-27T22:50:51 | 2019-12-28T01:30:10 | 2023-01-02T22:14:34 | 129,843 | 0 | 0 | 3 |
Java
| false | false |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.spi
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|spi
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Exchange
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Processor
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Producer
import|;
end_import
begin_comment
comment|/** * Used for components that can optimise the usage of {@link org.apache.camel.processor.SendDynamicProcessor} (toD) * to reuse a static {@link org.apache.camel.Endpoint} and {@link Producer} that supports * using headers to provide the dynamic parts. For example many of the HTTP components supports this. */
end_comment
begin_interface
DECL|interface|SendDynamicAware
specifier|public
interface|interface
name|SendDynamicAware
block|{
comment|/** * Sets the component name. * * @param scheme name of the component */
DECL|method|setScheme (String scheme)
name|void
name|setScheme
parameter_list|(
name|String
name|scheme
parameter_list|)
function_decl|;
comment|/** * Gets the component name */
DECL|method|getScheme ()
name|String
name|getScheme
parameter_list|()
function_decl|;
comment|/** * An entry of detailed information from the recipient uri, which allows the {@link SendDynamicAware} * implementation to prepare pre- and post- processor and the static uri to be used for the optimised dynamic to. */
DECL|class|DynamicAwareEntry
class|class
name|DynamicAwareEntry
block|{
DECL|field|uri
specifier|private
specifier|final
name|String
name|uri
decl_stmt|;
DECL|field|originalUri
specifier|private
specifier|final
name|String
name|originalUri
decl_stmt|;
DECL|field|properties
specifier|private
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|properties
decl_stmt|;
DECL|field|lenientProperties
specifier|private
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|lenientProperties
decl_stmt|;
DECL|method|DynamicAwareEntry (String uri, String originalUri, Map<String, String> properties, Map<String, String> lenientProperties)
specifier|public
name|DynamicAwareEntry
parameter_list|(
name|String
name|uri
parameter_list|,
name|String
name|originalUri
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|properties
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|lenientProperties
parameter_list|)
block|{
name|this
operator|.
name|uri
operator|=
name|uri
expr_stmt|;
name|this
operator|.
name|originalUri
operator|=
name|originalUri
expr_stmt|;
name|this
operator|.
name|properties
operator|=
name|properties
expr_stmt|;
name|this
operator|.
name|lenientProperties
operator|=
name|lenientProperties
expr_stmt|;
block|}
DECL|method|getUri ()
specifier|public
name|String
name|getUri
parameter_list|()
block|{
return|return
name|uri
return|;
block|}
DECL|method|getOriginalUri ()
specifier|public
name|String
name|getOriginalUri
parameter_list|()
block|{
return|return
name|originalUri
return|;
block|}
DECL|method|getProperties ()
specifier|public
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|getProperties
parameter_list|()
block|{
return|return
name|properties
return|;
block|}
DECL|method|getLenientProperties ()
specifier|public
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|getLenientProperties
parameter_list|()
block|{
return|return
name|lenientProperties
return|;
block|}
block|}
comment|/** * Prepares for using optimised dynamic to by parsing the uri and returning an entry of details that are * used for creating the pre and post processors, and the static uri. * * @param exchange the exchange * @param uri the resolved uri which is intended to be used * @param originalUri the original uri of the endpoint before any dynamic evaluation * @return prepared information about the dynamic endpoint to use * @throws Exception is thrown if error parsing the uri */
DECL|method|prepare (Exchange exchange, String uri, String originalUri)
name|DynamicAwareEntry
name|prepare
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|String
name|uri
parameter_list|,
name|String
name|originalUri
parameter_list|)
throws|throws
name|Exception
function_decl|;
comment|/** * Resolves the static part of the uri that are used for creating a single {@link org.apache.camel.Endpoint} * and {@link Producer} that will be reused for processing the optimised toD. * * @param exchange the exchange * @param entry prepared information about the dynamic endpoint to use * @return the static uri, or<tt>null</tt> to not let toD use this optimisation. * @throws Exception is thrown if error resolving the static uri. */
DECL|method|resolveStaticUri (Exchange exchange, DynamicAwareEntry entry)
name|String
name|resolveStaticUri
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|DynamicAwareEntry
name|entry
parameter_list|)
throws|throws
name|Exception
function_decl|;
comment|/** * Creates the pre {@link Processor} that will prepare the {@link Exchange} * with dynamic details from the given recipient. * * @param exchange the exchange * @param entry prepared information about the dynamic endpoint to use * @return the processor, or<tt>null</tt> to not let toD use this optimisation. * @throws Exception is thrown if error creating the pre processor. */
DECL|method|createPreProcessor (Exchange exchange, DynamicAwareEntry entry)
name|Processor
name|createPreProcessor
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|DynamicAwareEntry
name|entry
parameter_list|)
throws|throws
name|Exception
function_decl|;
comment|/** * Creates an optional post {@link Processor} that will be executed afterwards * when the message has been sent dynamic. * * @param exchange the exchange * @param entry prepared information about the dynamic endpoint to use * @return the post processor, or<tt>null</tt> if no post processor is needed. * @throws Exception is thrown if error creating the post processor. */
DECL|method|createPostProcessor (Exchange exchange, DynamicAwareEntry entry)
name|Processor
name|createPostProcessor
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|DynamicAwareEntry
name|entry
parameter_list|)
throws|throws
name|Exception
function_decl|;
block|}
end_interface
end_unit
|
UTF-8
|
Java
| 7,861 |
java
|
SendDynamicAware.java
|
Java
|
[] | null |
[] |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.spi
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|spi
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Exchange
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Processor
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Producer
import|;
end_import
begin_comment
comment|/** * Used for components that can optimise the usage of {@link org.apache.camel.processor.SendDynamicProcessor} (toD) * to reuse a static {@link org.apache.camel.Endpoint} and {@link Producer} that supports * using headers to provide the dynamic parts. For example many of the HTTP components supports this. */
end_comment
begin_interface
DECL|interface|SendDynamicAware
specifier|public
interface|interface
name|SendDynamicAware
block|{
comment|/** * Sets the component name. * * @param scheme name of the component */
DECL|method|setScheme (String scheme)
name|void
name|setScheme
parameter_list|(
name|String
name|scheme
parameter_list|)
function_decl|;
comment|/** * Gets the component name */
DECL|method|getScheme ()
name|String
name|getScheme
parameter_list|()
function_decl|;
comment|/** * An entry of detailed information from the recipient uri, which allows the {@link SendDynamicAware} * implementation to prepare pre- and post- processor and the static uri to be used for the optimised dynamic to. */
DECL|class|DynamicAwareEntry
class|class
name|DynamicAwareEntry
block|{
DECL|field|uri
specifier|private
specifier|final
name|String
name|uri
decl_stmt|;
DECL|field|originalUri
specifier|private
specifier|final
name|String
name|originalUri
decl_stmt|;
DECL|field|properties
specifier|private
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|properties
decl_stmt|;
DECL|field|lenientProperties
specifier|private
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|lenientProperties
decl_stmt|;
DECL|method|DynamicAwareEntry (String uri, String originalUri, Map<String, String> properties, Map<String, String> lenientProperties)
specifier|public
name|DynamicAwareEntry
parameter_list|(
name|String
name|uri
parameter_list|,
name|String
name|originalUri
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|properties
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|lenientProperties
parameter_list|)
block|{
name|this
operator|.
name|uri
operator|=
name|uri
expr_stmt|;
name|this
operator|.
name|originalUri
operator|=
name|originalUri
expr_stmt|;
name|this
operator|.
name|properties
operator|=
name|properties
expr_stmt|;
name|this
operator|.
name|lenientProperties
operator|=
name|lenientProperties
expr_stmt|;
block|}
DECL|method|getUri ()
specifier|public
name|String
name|getUri
parameter_list|()
block|{
return|return
name|uri
return|;
block|}
DECL|method|getOriginalUri ()
specifier|public
name|String
name|getOriginalUri
parameter_list|()
block|{
return|return
name|originalUri
return|;
block|}
DECL|method|getProperties ()
specifier|public
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|getProperties
parameter_list|()
block|{
return|return
name|properties
return|;
block|}
DECL|method|getLenientProperties ()
specifier|public
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|getLenientProperties
parameter_list|()
block|{
return|return
name|lenientProperties
return|;
block|}
block|}
comment|/** * Prepares for using optimised dynamic to by parsing the uri and returning an entry of details that are * used for creating the pre and post processors, and the static uri. * * @param exchange the exchange * @param uri the resolved uri which is intended to be used * @param originalUri the original uri of the endpoint before any dynamic evaluation * @return prepared information about the dynamic endpoint to use * @throws Exception is thrown if error parsing the uri */
DECL|method|prepare (Exchange exchange, String uri, String originalUri)
name|DynamicAwareEntry
name|prepare
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|String
name|uri
parameter_list|,
name|String
name|originalUri
parameter_list|)
throws|throws
name|Exception
function_decl|;
comment|/** * Resolves the static part of the uri that are used for creating a single {@link org.apache.camel.Endpoint} * and {@link Producer} that will be reused for processing the optimised toD. * * @param exchange the exchange * @param entry prepared information about the dynamic endpoint to use * @return the static uri, or<tt>null</tt> to not let toD use this optimisation. * @throws Exception is thrown if error resolving the static uri. */
DECL|method|resolveStaticUri (Exchange exchange, DynamicAwareEntry entry)
name|String
name|resolveStaticUri
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|DynamicAwareEntry
name|entry
parameter_list|)
throws|throws
name|Exception
function_decl|;
comment|/** * Creates the pre {@link Processor} that will prepare the {@link Exchange} * with dynamic details from the given recipient. * * @param exchange the exchange * @param entry prepared information about the dynamic endpoint to use * @return the processor, or<tt>null</tt> to not let toD use this optimisation. * @throws Exception is thrown if error creating the pre processor. */
DECL|method|createPreProcessor (Exchange exchange, DynamicAwareEntry entry)
name|Processor
name|createPreProcessor
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|DynamicAwareEntry
name|entry
parameter_list|)
throws|throws
name|Exception
function_decl|;
comment|/** * Creates an optional post {@link Processor} that will be executed afterwards * when the message has been sent dynamic. * * @param exchange the exchange * @param entry prepared information about the dynamic endpoint to use * @return the post processor, or<tt>null</tt> if no post processor is needed. * @throws Exception is thrown if error creating the post processor. */
DECL|method|createPostProcessor (Exchange exchange, DynamicAwareEntry entry)
name|Processor
name|createPostProcessor
parameter_list|(
name|Exchange
name|exchange
parameter_list|,
name|DynamicAwareEntry
name|entry
parameter_list|)
throws|throws
name|Exception
function_decl|;
block|}
end_interface
end_unit
| 7,861 | 0.765043 | 0.763771 | 294 | 25.734694 | 74.984337 | 810 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.176871 | false | false |
7
|
3c9c9cce9cc17d9ce82169de0b8d4ec05953657a
| 28,037,546,571,300 |
41ef5d56d07204630a975f1401ee80bc6be6cea8
|
/ArrayLists/src/BasicArrayLists3.java
|
07d64a5f420c3e35dcbf2b79b4390a6d48a8bb2a
|
[] |
no_license
|
Gam8itG4mes/Java
|
https://github.com/Gam8itG4mes/Java
|
06ce318c978a6194cee62a53e8c8c1e7e2d13ca2
|
e3e44adee56b1008595feee845fa01caadacda55
|
refs/heads/master
| 2022-03-18T21:36:24.987000 | 2019-10-10T17:42:39 | 2019-10-10T17:42:39 | 198,085,071 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Random;
import java.util.ArrayList;
public class BasicArrayLists3 {
public static void main (String [] args) {
Random r = new Random();
ArrayList<Integer> arrli = new ArrayList<Integer>(1000);
while (arrli.size() < 1000) {
arrli.add(r.nextInt(99-10)+10);
}
System.out.println(arrli);
}
}
|
UTF-8
|
Java
| 339 |
java
|
BasicArrayLists3.java
|
Java
|
[] | null |
[] |
import java.util.Random;
import java.util.ArrayList;
public class BasicArrayLists3 {
public static void main (String [] args) {
Random r = new Random();
ArrayList<Integer> arrli = new ArrayList<Integer>(1000);
while (arrli.size() < 1000) {
arrli.add(r.nextInt(99-10)+10);
}
System.out.println(arrli);
}
}
| 339 | 0.651917 | 0.60767 | 14 | 22.214285 | 17.263416 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.714286 | false | false |
7
|
50964b4298719233eb100865e2a11e460bc87f28
| 5,695,126,697,831 |
9379fe93b4dda488929fdcf233564325050c3843
|
/utils/src/main/java/com/wq/utils/util/ImageLoader.java
|
21a1bbb4893a5b3b9f125b13841d4d5fc8b0d494
|
[] |
no_license
|
yaosongcai/students
|
https://github.com/yaosongcai/students
|
3e749f6b16a43071863131af08a899dcef1f0c37
|
d12ad66a59a8b66fd6eb365c629700d1760aedf3
|
refs/heads/master
| 2020-04-07T22:21:01.254000 | 2018-11-23T01:35:49 | 2018-11-23T01:35:49 | 158,766,377 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wq.utils.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
/**
* 项目名称: com.wq.smartcampus.utils
* 类描述
* <pre>
* 一个简易的图片异步加载工具,待完善
* </pre>
* 创建人: 139061759@qq.com
* 创建时间: 2018/9/27
* 修改人: 1392061759@qq.com
* 修改时间: 2018/9/27
* 修改备注:
*/
public class ImageLoader {
private ImageView mImageview;
private String mUrl;
//创建缓存
private LruCache<String, Bitmap> mCaches;
private ListView mListView;
private Set<NewsAsyncTask> mTask;
public ImageLoader() {
mTask = new HashSet<>();
//获得最大的缓存空间
int maxMemory = (int) Runtime.getRuntime().maxMemory();
//赋予缓存区最大缓存的四分之一进行缓存
int cacheSize = maxMemory / 4;
mCaches = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
//在每次存入缓存的时候调用
return value.getByteCount();
}
};
}
public ImageLoader(ListView listView) {
mListView = listView;
mTask = new HashSet<>();
//获得最大的缓存空间
int maxMemory = (int) Runtime.getRuntime().maxMemory();
//赋予缓存区最大缓存的四分之一进行缓存
int cacheSize = maxMemory / 4;
mCaches = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
//在每次存入缓存的时候调用
return value.getByteCount();
}
};
}
//将图片通过url与bitmap的键值对形式添加到缓存中
public void addBitmapToCache(String url, Bitmap bitmap) {
if (getBitmapFromCache(url) == null) {
mCaches.put(url, bitmap);
}
}
//通过缓存得到图片
public Bitmap getBitmapFromCache(String url) {
return mCaches.get(url);
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mImageview.getTag().equals(mUrl))
mImageview.setImageBitmap((Bitmap) msg.obj);
}
};
//通过线程的方式去展示图片
public void showImageByThread(ImageView imageView, String url) {
mImageview = imageView;
mUrl = url;
new Thread() {
@Override
public void run() {
super.run();
Bitmap bitmap = getBitmapFromUrl(mUrl);
Message message = Message.obtain();
message.obj = bitmap;
mHandler.sendMessage(message);
}
}.start();
}
/**
* 异步请求加载图片
*
* @author ysc
* @time 2018/9/27 16:07
*/
public void showImageByAsync(ImageView imageView, String url) {
//先从缓存中获取图片
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap == null) {
NewAsyncTask task = new NewAsyncTask(imageView, url);
task.execute(url);
} else {
imageView.setImageBitmap(bitmap);
}
}
//通过异步任务的方式去加载图片
public void showImageByAsyncTask(ImageView imageView, String url) {
//先从缓存中获取图片
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap == null) {
// imageView.setImageResource(R.mipmap.ic_launcher);
} else {
imageView.setImageBitmap(bitmap);
}
}
private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap> {
// private ImageView mImageView;
private String mUrl;
public NewsAsyncTask(String url) {
// mImageview = imageView;
mUrl = url;
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
//从网络获取图片
Bitmap bitmap = getBitmapFromUrl(url);
//将图片加入缓存中
if (bitmap != null) {
addBitmapToCache(url, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
ImageView imageView = (ImageView) mListView.findViewWithTag(mUrl);
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
mTask.remove(this);
}
}
private class NewAsyncTask extends AsyncTask<String, Void, Bitmap> {
// private ImageView mImageView;
private String mUrl;
private ImageView img;
public NewAsyncTask(ImageView img, String url) {
// mImageview = imageView;
mUrl = url;
this.img = img;
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
//从网络获取图片
Bitmap bitmap = getBitmapFromUrl(url);
//将图片加入缓存中
if (bitmap != null) {
addBitmapToCache(url, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (img != null && bitmap != null) {
img.setImageBitmap(bitmap);
}
}
}
//滑动时加载图片
// public void loadImages(int start, int end) {
// for (int i = start; i < end; i++) {
// String url = NewsAdapter.URLS[i];
// //先从缓存中获取图片
// Bitmap bitmap = getBitmapFromCache(url);
// if (bitmap == null) {
// NewsAsyncTask task = new NewsAsyncTask(url);
// task.execute(url);
// mTask.add(task);
// } else {
// ImageView imageView = (ImageView) mListView.findViewWithTag(url);
// imageView.setImageBitmap(bitmap);
// }
// }
// }
//停止时取消所有任务加载
public void cancelAllTasks() {
if (mTask != null) {
for (NewsAsyncTask task : mTask) {
task.cancel(false);
}
}
}
//网络获取图片
private Bitmap getBitmapFromUrl(String urlString) {
Bitmap bitmap;
InputStream is = null;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
connection.disconnect();
return bitmap;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert is != null;
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
|
UTF-8
|
Java
| 7,700 |
java
|
ImageLoader.java
|
Java
|
[
{
"context": ">\n * 一个简易的图片异步加载工具,待完善\n * </pre>\n * 创建人: 139061759@qq.com\n * 创建时间: 2018/9/27\n * 修改人: 1392061759@qq.",
"end": 596,
"score": 0.9999030232429504,
"start": 580,
"tag": "EMAIL",
"value": "139061759@qq.com"
},
{
"context": "9061759@qq.com\n * 创建时间: 2018/9/27\n * 修改人: 1392061759@qq.com\n * 修改时间: 2018/9/27\n * 修改备注:\n */\npublic class I",
"end": 649,
"score": 0.9999055862426758,
"start": 632,
"tag": "EMAIL",
"value": "1392061759@qq.com"
},
{
"context": " }\n\n /**\n * 异步请求加载图片\n *\n * @author ysc\n * @time 2018/9/27 16:07\n */\n public v",
"end": 2986,
"score": 0.9996424317359924,
"start": 2983,
"tag": "USERNAME",
"value": "ysc"
}
] | null |
[] |
package com.wq.utils.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
/**
* 项目名称: com.wq.smartcampus.utils
* 类描述
* <pre>
* 一个简易的图片异步加载工具,待完善
* </pre>
* 创建人: <EMAIL>
* 创建时间: 2018/9/27
* 修改人: <EMAIL>
* 修改时间: 2018/9/27
* 修改备注:
*/
public class ImageLoader {
private ImageView mImageview;
private String mUrl;
//创建缓存
private LruCache<String, Bitmap> mCaches;
private ListView mListView;
private Set<NewsAsyncTask> mTask;
public ImageLoader() {
mTask = new HashSet<>();
//获得最大的缓存空间
int maxMemory = (int) Runtime.getRuntime().maxMemory();
//赋予缓存区最大缓存的四分之一进行缓存
int cacheSize = maxMemory / 4;
mCaches = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
//在每次存入缓存的时候调用
return value.getByteCount();
}
};
}
public ImageLoader(ListView listView) {
mListView = listView;
mTask = new HashSet<>();
//获得最大的缓存空间
int maxMemory = (int) Runtime.getRuntime().maxMemory();
//赋予缓存区最大缓存的四分之一进行缓存
int cacheSize = maxMemory / 4;
mCaches = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
//在每次存入缓存的时候调用
return value.getByteCount();
}
};
}
//将图片通过url与bitmap的键值对形式添加到缓存中
public void addBitmapToCache(String url, Bitmap bitmap) {
if (getBitmapFromCache(url) == null) {
mCaches.put(url, bitmap);
}
}
//通过缓存得到图片
public Bitmap getBitmapFromCache(String url) {
return mCaches.get(url);
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mImageview.getTag().equals(mUrl))
mImageview.setImageBitmap((Bitmap) msg.obj);
}
};
//通过线程的方式去展示图片
public void showImageByThread(ImageView imageView, String url) {
mImageview = imageView;
mUrl = url;
new Thread() {
@Override
public void run() {
super.run();
Bitmap bitmap = getBitmapFromUrl(mUrl);
Message message = Message.obtain();
message.obj = bitmap;
mHandler.sendMessage(message);
}
}.start();
}
/**
* 异步请求加载图片
*
* @author ysc
* @time 2018/9/27 16:07
*/
public void showImageByAsync(ImageView imageView, String url) {
//先从缓存中获取图片
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap == null) {
NewAsyncTask task = new NewAsyncTask(imageView, url);
task.execute(url);
} else {
imageView.setImageBitmap(bitmap);
}
}
//通过异步任务的方式去加载图片
public void showImageByAsyncTask(ImageView imageView, String url) {
//先从缓存中获取图片
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap == null) {
// imageView.setImageResource(R.mipmap.ic_launcher);
} else {
imageView.setImageBitmap(bitmap);
}
}
private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap> {
// private ImageView mImageView;
private String mUrl;
public NewsAsyncTask(String url) {
// mImageview = imageView;
mUrl = url;
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
//从网络获取图片
Bitmap bitmap = getBitmapFromUrl(url);
//将图片加入缓存中
if (bitmap != null) {
addBitmapToCache(url, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
ImageView imageView = (ImageView) mListView.findViewWithTag(mUrl);
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
mTask.remove(this);
}
}
private class NewAsyncTask extends AsyncTask<String, Void, Bitmap> {
// private ImageView mImageView;
private String mUrl;
private ImageView img;
public NewAsyncTask(ImageView img, String url) {
// mImageview = imageView;
mUrl = url;
this.img = img;
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
//从网络获取图片
Bitmap bitmap = getBitmapFromUrl(url);
//将图片加入缓存中
if (bitmap != null) {
addBitmapToCache(url, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (img != null && bitmap != null) {
img.setImageBitmap(bitmap);
}
}
}
//滑动时加载图片
// public void loadImages(int start, int end) {
// for (int i = start; i < end; i++) {
// String url = NewsAdapter.URLS[i];
// //先从缓存中获取图片
// Bitmap bitmap = getBitmapFromCache(url);
// if (bitmap == null) {
// NewsAsyncTask task = new NewsAsyncTask(url);
// task.execute(url);
// mTask.add(task);
// } else {
// ImageView imageView = (ImageView) mListView.findViewWithTag(url);
// imageView.setImageBitmap(bitmap);
// }
// }
// }
//停止时取消所有任务加载
public void cancelAllTasks() {
if (mTask != null) {
for (NewsAsyncTask task : mTask) {
task.cancel(false);
}
}
}
//网络获取图片
private Bitmap getBitmapFromUrl(String urlString) {
Bitmap bitmap;
InputStream is = null;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
connection.disconnect();
return bitmap;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert is != null;
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
| 7,681 | 0.546089 | 0.539385 | 253 | 27.304348 | 19.479956 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470356 | false | false |
7
|
5caf4ee6f428bb12b124e053d44f54027b784ae4
| 21,706,764,767,814 |
74e62d5bdea942d31e840f510f5988fe4e41f044
|
/src/main/java/danger/orespawn/MyEntityAIWanderALot.java
|
b004c7f30b7323d1a01e40a07da8cd9adb09b895
|
[] |
no_license
|
rogeliomateo7/OreSpawn
|
https://github.com/rogeliomateo7/OreSpawn
|
896cf92ffdea97a9899f12818536a7f0b70d9b2b
|
4f800e6a7050c29acc42db6b795671ca3770b300
|
refs/heads/master
| 2021-10-24T12:10:25.616000 | 2019-03-26T01:08:04 | 2019-03-26T01:08:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package danger.orespawn;
import net.minecraft.entity.*;
import net.minecraft.entity.passive.*;
import net.minecraft.entity.ai.*;
import net.minecraft.util.*;
public class MyEntityAIWanderALot extends EntityAIBase
{
private EntityCreature entity;
private double xPosition;
private double yPosition;
private double zPosition;
private double speed;
private int xzRange;
private int busy;
public MyEntityAIWanderALot(final EntityCreature par1EntityCreature, final int par1, final double par2) {
this.xzRange = 10;
this.busy = 0;
this.entity = par1EntityCreature;
this.xzRange = par1;
this.speed = par2;
this.setMutexBits(1);
}
public void setBusy(final int i) {
this.busy = i;
}
public boolean shouldExecute() {
if (this.busy != 0) {
return false;
}
if (this.entity.worldObj.rand.nextInt(30) != 0) {
return false;
}
if (this.entity instanceof EntityTameable && ((EntityTameable)this.entity).isSitting()) {
return false;
}
final Vec3 var1 = RandomPositionGenerator.findRandomTarget(this.entity, this.xzRange, 7);
if (var1 == null) {
return false;
}
this.xPosition = var1.xCoord;
this.yPosition = var1.yCoord;
this.zPosition = var1.zCoord;
return true;
}
public boolean continueExecuting() {
return !this.entity.getNavigator().noPath();
}
public void startExecuting() {
this.entity.getNavigator().tryMoveToXYZ(this.xPosition, this.yPosition, this.zPosition, this.speed);
}
}
|
UTF-8
|
Java
| 1,688 |
java
|
MyEntityAIWanderALot.java
|
Java
|
[] | null |
[] |
package danger.orespawn;
import net.minecraft.entity.*;
import net.minecraft.entity.passive.*;
import net.minecraft.entity.ai.*;
import net.minecraft.util.*;
public class MyEntityAIWanderALot extends EntityAIBase
{
private EntityCreature entity;
private double xPosition;
private double yPosition;
private double zPosition;
private double speed;
private int xzRange;
private int busy;
public MyEntityAIWanderALot(final EntityCreature par1EntityCreature, final int par1, final double par2) {
this.xzRange = 10;
this.busy = 0;
this.entity = par1EntityCreature;
this.xzRange = par1;
this.speed = par2;
this.setMutexBits(1);
}
public void setBusy(final int i) {
this.busy = i;
}
public boolean shouldExecute() {
if (this.busy != 0) {
return false;
}
if (this.entity.worldObj.rand.nextInt(30) != 0) {
return false;
}
if (this.entity instanceof EntityTameable && ((EntityTameable)this.entity).isSitting()) {
return false;
}
final Vec3 var1 = RandomPositionGenerator.findRandomTarget(this.entity, this.xzRange, 7);
if (var1 == null) {
return false;
}
this.xPosition = var1.xCoord;
this.yPosition = var1.yCoord;
this.zPosition = var1.zCoord;
return true;
}
public boolean continueExecuting() {
return !this.entity.getNavigator().noPath();
}
public void startExecuting() {
this.entity.getNavigator().tryMoveToXYZ(this.xPosition, this.yPosition, this.zPosition, this.speed);
}
}
| 1,688 | 0.623815 | 0.611374 | 58 | 28.103449 | 24.833021 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.637931 | false | false |
7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.