blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
80634fb099dea904e7e5ea71482c94baff30568f | Java | iritgo/iritgo-aktera | /aktera-shell/src/main/java/de/iritgo/aktera/shell/groovyshell/GroovyShellThread.java | UTF-8 | 2,518 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | /**
* This file is part of the Iritgo/Aktera Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.iritgo.aktera.shell.groovyshell;
import groovy.lang.Binding;
import groovy.ui.InteractiveShell;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringReader;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import de.iritgo.simplelife.string.StringTools;
/**
*
* @author Bruce Fancher
*
*/
public class GroovyShellThread extends Thread
{
public static final String OUT_KEY = "out";
private Socket socket;
private Binding binding;
public GroovyShellThread(Socket socket, Binding binding)
{
super();
this.socket = socket;
this.binding = binding;
}
@Override
public void run()
{
try
{
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(new Date());
String dayOfMonth = StringTools.trim(calendar.get(Calendar.DAY_OF_MONTH));
String month = StringTools.trim(calendar.get(Calendar.MONTH));
final PrintStream out = new PrintStream(socket.getOutputStream());
final InputStream in = socket.getInputStream();
String password = "";
while (! password.equals(dayOfMonth + "sh311" + month))
{
out.print("Please enter the shell password and press return\n");
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in));
password = streamReader.readLine();
}
binding.setVariable(OUT_KEY, out);
final InteractiveShell groovy = new InteractiveShell(binding, in, out, out);
try
{
groovy.run();
}
catch (Exception e)
{
e.printStackTrace();
}
out.close();
in.close();
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Socket getSocket()
{
return socket;
}
}
| true |
2a70703719c7374f8ae73a7ec1edb11999509602 | Java | onap/so | /bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ServiceModel.java | UTF-8 | 770 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | package org.onap.so.bpmn.servicedecomposition.entities;
import org.onap.so.db.catalog.beans.Service;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("serviceModel")
public class ServiceModel {
@JsonProperty("currentService")
private Service currentService;
@JsonProperty("newService")
private Service newService;
public Service getCurrentService() {
return currentService;
}
public void setCurrentService(Service currentService) {
this.currentService = currentService;
}
public Service getNewService() {
return newService;
}
public void setNewService(Service newService) {
this.newService = newService;
}
}
| true |
5a165749b9bfd2e6a67e4fe9d146851d08b5b667 | Java | ffang/xbean | /xbean-bundleutils/src/main/java/org/apache/xbean/osgi/bundle/util/BundleUtils.java | UTF-8 | 14,038 | 1.585938 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.xbean.osgi.bundle.util;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleReference;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
/**
* @version $Rev: 1347954 $ $Date: 2012-06-08 05:08:40 -0400 (Fri, 08 Jun 2012) $
*/
public class BundleUtils {
private static final boolean isOSGi43 = isOSGi43();
private static boolean isOSGi43() {
try {
Class.forName("org.osgi.framework.wiring.BundleWiring");
return true;
} catch (Throwable e) {
return false;
}
}
public final static String REFERENCE_SCHEME = "reference:";
public final static String FILE_SCHEMA = "file:";
public final static String REFERENCE_FILE_SCHEMA = "reference:file:";
/**
* Based on the constant field values, if it is bigger than the RESOLVED status value, the bundle has been resolved by the framework
* @param bundle
* @return true if the bundle is resolved, or false if not.
*/
public static boolean isResolved(Bundle bundle) {
return bundle.getState() >= Bundle.RESOLVED;
}
/**
* resolve method will try to load the Object.class, the behavior triggers a resolved request to the OSGI framework.
* @param bundle
*/
public static void resolve(Bundle bundle) {
if (isFragment(bundle)) {
return;
}
try {
bundle.loadClass(Object.class.getName());
} catch (Exception e) {
}
}
/**
* If the bundle fulfills the conditions below, it could be started
* a. Not in the UNINSTALLED status.
* b. Not in the STARTING status.
* c. Not a fragment bundle.
* @param bundle
* @return
*/
public static boolean canStart(Bundle bundle) {
return (bundle.getState() != Bundle.UNINSTALLED) && (bundle.getState() != Bundle.STARTING) && (!isFragment(bundle));
}
/**
* If the bundle fulfills the conditions below, it could be stopped
* a. Not in the UNINSTALLED status.
* b. Not in the STOPPING status.
* c. Not a fragment bundle.
* @param bundle
* @return
*/
public static boolean canStop(Bundle bundle) {
return (bundle.getState() != Bundle.UNINSTALLED) && (bundle.getState() != Bundle.STOPPING) && (!isFragment(bundle));
}
/**
* If the bundle fulfills the conditions below, it could be un-installed
* a. Not in the UNINSTALLED status.
* @param bundle
* @return
*/
public static boolean canUninstall(Bundle bundle) {
return bundle.getState() != Bundle.UNINSTALLED;
}
public static boolean isFragment(Bundle bundle) {
Dictionary headers = bundle.getHeaders();
return (headers != null && headers.get(Constants.FRAGMENT_HOST) != null);
}
/**
* Returns bundle (if any) associated with current thread's context classloader.
* Invoking this method is equivalent to getBundle(Thread.currentThread().getContextClassLoader(), unwrap)
*/
public static Bundle getContextBundle(boolean unwrap) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return classLoader == null ? null : getBundle(classLoader, unwrap);
}
/**
* Returns bundle (if any) associated with the classloader.
* @param classLoader
* @param unwrap if true and if the bundle associated with the context classloader is a
* {@link DelegatingBundle}, this function will return the main application bundle
* backing the {@link DelegatingBundle}. Otherwise, the bundle associated with
* the context classloader is returned as is. See {@link BundleClassLoader#getBundle(boolean)}
* for more information.
* @return The bundle associated with the classloader. Might be null.
*/
public static Bundle getBundle(ClassLoader classLoader, boolean unwrap) {
if (classLoader instanceof DelegatingBundleReference) {
return ((DelegatingBundleReference) classLoader).getBundle(unwrap);
} else if (classLoader instanceof BundleReference) {
return ((BundleReference) classLoader).getBundle();
} else {
return null;
}
}
/**
* If the given bundle is a {@link DelegatingBundle} this function will return the main
* application bundle backing the {@link DelegatingBundle}. Otherwise, the bundle
* passed in is returned as is.
*/
public static Bundle unwrapBundle(Bundle bundle) {
if (bundle instanceof DelegatingBundle) {
return ((DelegatingBundle) bundle).getMainBundle();
}
return bundle;
}
/**
* Works like {@link Bundle#getEntryPaths(String)} but also returns paths
* in attached fragment bundles.
*
* @param bundle
* @param name
* @return
*/
public static Enumeration<String> getEntryPaths(Bundle bundle, String name) {
Enumeration<URL> entries = bundle.findEntries(name, null, false);
if (entries == null) {
return null;
}
LinkedHashSet<String> paths = new LinkedHashSet<String>();
while (entries.hasMoreElements()) {
URL url = entries.nextElement();
String path = url.getPath();
if (path.startsWith("/")) {
path = path.substring(1);
}
paths.add(path);
}
return Collections.enumeration(paths);
}
/**
* 1, If the bundle was installed with reference directory mode
* return the file URL directly.
* 2, For traditional package bundle, Works like {@link Bundle#getEntry(String)}
*
* In addition to the searching abaove, it also checks attached fragment bundles for the given entry.
*
* @param bundle
* @param name
* @return
* @throws MalformedURLException
*/
public static URL getEntry(Bundle bundle, String name) throws MalformedURLException {
if (name.endsWith("/")) {
name = name.substring(0, name.length() - 1);
}
File bundleFile = toFile(bundle);
if (bundleFile != null && bundleFile.isDirectory()) {
File entryFile = new File(bundleFile, name);
if (entryFile.exists()) {
return entryFile.toURI().toURL();
}
}
if (name.equals("/")) {
return bundle.getEntry(name);
}
String path;
String pattern;
int pos = name.lastIndexOf("/");
if (pos == -1) {
path = "/";
pattern = name;
} else if (pos == 0) {
path = "/";
pattern = name.substring(1);
} else {
path = name.substring(0, pos);
pattern = name.substring(pos + 1);
}
Enumeration<URL> entries = bundle.findEntries(path, pattern, false);
if (entries != null && entries.hasMoreElements()) {
return entries.nextElement();
} else {
return null;
}
}
public static URL getNestedEntry(Bundle bundle, String jarEntryName, String subEntryName) throws MalformedURLException {
File bundleFile = toFile(bundle);
if (bundleFile != null && bundleFile.isDirectory()) {
File entryFile = new File(bundleFile, jarEntryName);
if (entryFile.exists()) {
if (entryFile.isFile()) {
return new URL("jar:" + entryFile.toURI().toURL() + "!/" + subEntryName);
} else {
return new File(entryFile, subEntryName).toURI().toURL();
}
}
return null;
}
return new URL("jar:" + bundle.getEntry(jarEntryName).toString() + "!/" + subEntryName);
}
public static File toFile(Bundle bundle) {
return toFile(bundle.getLocation());
}
public static File toFile(URL url) {
return toFile(url.toExternalForm());
}
/**
* Translate the reference:file:// style URL to the underlying file instance
* @param url
* @return
*/
public static File toFile(String url) {
if (url !=null && url.startsWith(REFERENCE_FILE_SCHEMA)) {
File file = null;
try {
file = new File(new URL(url.substring(REFERENCE_SCHEME.length())).toURI());
if (file.exists()) {
return file;
}
} catch (Exception e) {
// If url includes special chars: { } [ ] % < > # ^ ?
// URISyntaxException or MalformedURLException will be thrown,
// so try to use File(String) directly
file = new File(url.substring(REFERENCE_FILE_SCHEMA.length()));
if (file.exists()) {
return file;
}
}
}
return null;
}
public static String toReferenceFileLocation(File file) throws IOException {
if (!file.exists()) {
throw new IOException("file not exist " + file.getAbsolutePath());
}
return REFERENCE_SCHEME + file.toURI();
}
public static LinkedHashSet<Bundle> getWiredBundles(Bundle bundle) {
if (isOSGi43) {
return getWiredBundles43(bundle);
} else {
return getWiredBundles42(bundle);
}
}
private static LinkedHashSet<Bundle> getWiredBundles42(Bundle bundle) {
ServiceReference reference = bundle.getBundleContext().getServiceReference(PackageAdmin.class.getName());
PackageAdmin packageAdmin = (PackageAdmin) bundle.getBundleContext().getService(reference);
try {
return getWiredBundles(packageAdmin, bundle);
} finally {
bundle.getBundleContext().ungetService(reference);
}
}
public static LinkedHashSet<Bundle> getWiredBundles(PackageAdmin packageAdmin, Bundle bundle) {
BundleDescription description = new BundleDescription(bundle.getHeaders());
// handle static wire via Import-Package
List<BundleDescription.ImportPackage> imports = description.getExternalImports();
LinkedHashSet<Bundle> wiredBundles = new LinkedHashSet<Bundle>();
for (BundleDescription.ImportPackage packageImport : imports) {
ExportedPackage[] exports = packageAdmin.getExportedPackages(packageImport.getName());
Bundle wiredBundle = getWiredBundle(bundle, exports);
if (wiredBundle != null) {
wiredBundles.add(wiredBundle);
}
}
// handle dynamic wire via DynamicImport-Package
if (!description.getDynamicImportPackage().isEmpty()) {
for (Bundle b : bundle.getBundleContext().getBundles()) {
if (!wiredBundles.contains(b)) {
ExportedPackage[] exports = packageAdmin.getExportedPackages(b);
Bundle wiredBundle = getWiredBundle(bundle, exports);
if (wiredBundle != null) {
wiredBundles.add(wiredBundle);
}
}
}
}
return wiredBundles;
}
static Bundle getWiredBundle(Bundle bundle, ExportedPackage[] exports) {
if (exports != null) {
for (ExportedPackage exportedPackage : exports) {
Bundle[] importingBundles = exportedPackage.getImportingBundles();
if (importingBundles != null) {
for (Bundle importingBundle : importingBundles) {
if (importingBundle == bundle) {
return exportedPackage.getExportingBundle();
}
}
}
}
}
return null;
}
// OSGi 4.3 API
private static LinkedHashSet<Bundle> getWiredBundles43(Bundle bundle) {
LinkedHashSet<Bundle> wiredBundles = new LinkedHashSet<Bundle>();
BundleWiring wiring = bundle.adapt(BundleWiring.class);
if (wiring != null) {
List<BundleWire> wires;
wires = wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
for (BundleWire wire : wires) {
wiredBundles.add(wire.getProviderWiring().getBundle());
}
wires = wiring.getRequiredWires(BundleRevision.BUNDLE_NAMESPACE);
for (BundleWire wire : wires) {
wiredBundles.add(wire.getProviderWiring().getBundle());
}
}
return wiredBundles;
}
}
| true |
0bc68914d50e2eca8813590f665cbd0b0a9ac6d9 | Java | lihum/flowable-engine | /modules/flowable-engine/src/test/java/org/flowable/engine/test/api/history/HistoryLevelServiceTest.java | UTF-8 | 15,071 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.engine.test.api.history;
import static org.assertj.core.api.Assertions.assertThat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.flowable.engine.impl.test.HistoryTestHelper;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.test.Deployment;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.junit.jupiter.api.Test;
/**
* @author Tijs Rademakers
*/
public class HistoryLevelServiceTest extends PluggableFlowableTestCase {
@Deployment(resources = { "org/flowable/engine/test/api/history/oneTaskHistoryLevelNoneProcess.bpmn20.xml" })
@Test
public void testNoneHistoryLevel() {
// With a clean ProcessEngine, no instances should be available
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
// Complete the task and check if the size is count 1
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
assertThat(task).isNotNull();
taskService.claim(task.getId(), "test");
taskService.setOwner(task.getId(), "test");
taskService.setAssignee(task.getId(), "anotherTest");
taskService.setPriority(task.getId(), 40);
taskService.setDueDate(task.getId(), new Date());
taskService.setVariable(task.getId(), "var1", "test");
taskService.setVariableLocal(task.getId(), "localVar1", "test2");
taskService.complete(task.getId());
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
assertThat(historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
assertThat(historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
}
@Deployment(resources = { "org/flowable/engine/test/api/history/oneTaskHistoryLevelActivityProcess.bpmn20.xml" })
@Test
public void testActivityHistoryLevel() {
// With a clean ProcessEngine, no instances should be available
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
// Complete the task and check if the size is count 1
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
assertThat(task).isNotNull();
assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(3);
taskService.claim(task.getId(), "test");
taskService.setOwner(task.getId(), "test");
taskService.setAssignee(task.getId(), "anotherTest");
taskService.setPriority(task.getId(), 40);
Date dueDateValue = new Date();
taskService.setDueDate(task.getId(), dueDateValue);
taskService.setVariable(task.getId(), "var1", "test");
taskService.setVariableLocal(task.getId(), "localVar1", "test2");
taskService.complete(task.getId());
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
assertThat(historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(5);
assertThat(historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(2);
boolean hasProcessVariable = false;
boolean hasTaskVariable = false;
List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).list();
for (HistoricVariableInstance historicVariableInstance : variables) {
if ("var1".equals(historicVariableInstance.getVariableName())) {
hasProcessVariable = true;
assertThat(historicVariableInstance.getValue()).isEqualTo("test");
assertThat(historicVariableInstance.getProcessInstanceId()).isEqualTo(processInstance.getProcessInstanceId());
assertThat(historicVariableInstance.getTaskId()).isNull();
} else if ("localVar1".equals(historicVariableInstance.getVariableName())) {
hasTaskVariable = true;
assertThat(historicVariableInstance.getValue()).isEqualTo("test2");
assertThat(historicVariableInstance.getProcessInstanceId()).isEqualTo(processInstance.getProcessInstanceId());
assertThat(historicVariableInstance.getTaskId()).isEqualTo(task.getId());
}
}
assertThat(hasProcessVariable).isTrue();
assertThat(hasTaskVariable).isTrue();
assertThat(historyService.createHistoricDetailQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
}
@Deployment(resources = { "org/flowable/engine/test/api/history/oneTaskHistoryLevelAuditProcess.bpmn20.xml" })
@Test
public void testAuditHistoryLevel() {
// With a clean ProcessEngine, no instances should be available
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
// Complete the task and check if the size is count 1
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
assertThat(task).isNotNull();
assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(3);
taskService.claim(task.getId(), "test");
taskService.setOwner(task.getId(), "test");
taskService.setAssignee(task.getId(), "anotherTest");
taskService.setPriority(task.getId(), 40);
Calendar dueDateCalendar = new GregorianCalendar();
taskService.setDueDate(task.getId(), dueDateCalendar.getTime());
taskService.setVariable(task.getId(), "var1", "test");
taskService.setVariableLocal(task.getId(), "localVar1", "test2");
taskService.complete(task.getId());
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
assertThat(historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(5);
HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
assertThat(historicTask.getOwner()).isEqualTo("test");
assertThat(historicTask.getAssignee()).isEqualTo("anotherTest");
assertThat(historicTask.getPriority()).isEqualTo(40);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
assertThat(simpleDateFormat.format(historicTask.getDueDate())).isEqualTo(simpleDateFormat.format(dueDateCalendar.getTime()));
assertThat(historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(2);
boolean hasProcessVariable = false;
boolean hasTaskVariable = false;
List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).list();
for (HistoricVariableInstance historicVariableInstance : variables) {
if ("var1".equals(historicVariableInstance.getVariableName())) {
hasProcessVariable = true;
assertThat(historicVariableInstance.getValue()).isEqualTo("test");
assertThat(historicVariableInstance.getProcessInstanceId()).isEqualTo(processInstance.getProcessInstanceId());
assertThat(historicVariableInstance.getTaskId()).isNull();
} else if ("localVar1".equals(historicVariableInstance.getVariableName())) {
hasTaskVariable = true;
assertThat(historicVariableInstance.getValue()).isEqualTo("test2");
assertThat(historicVariableInstance.getProcessInstanceId()).isEqualTo(processInstance.getProcessInstanceId());
assertThat(historicVariableInstance.getTaskId()).isEqualTo(task.getId());
}
}
assertThat(hasProcessVariable).isTrue();
assertThat(hasTaskVariable).isTrue();
assertThat(historyService.createHistoricDetailQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0);
}
@Deployment(resources = { "org/flowable/engine/test/api/history/oneTaskHistoryLevelFullProcess.bpmn20.xml" })
@Test
public void testFullHistoryLevel() {
// With a clean ProcessEngine, no instances should be available
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
// Complete the task and check if the size is count 1
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
assertThat(task).isNotNull();
assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(3);
taskService.claim(task.getId(), "test");
taskService.setOwner(task.getId(), "test");
taskService.setAssignee(task.getId(), "anotherTest");
taskService.setPriority(task.getId(), 40);
Date dueDateValue = new Date();
taskService.setDueDate(task.getId(), dueDateValue);
taskService.setVariable(task.getId(), "var1", "test");
taskService.setVariableLocal(task.getId(), "localVar1", "test2");
taskService.complete(task.getId());
HistoryTestHelper.waitForJobExecutorToProcessAllHistoryJobs(processEngineConfiguration, managementService, 7000, 200);
assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
assertThat(historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(5);
HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
assertThat(historicTask.getOwner()).isEqualTo("test");
assertThat(historicTask.getAssignee()).isEqualTo("anotherTest");
assertThat(historicTask.getPriority()).isEqualTo(40);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
assertThat(simpleDateFormat.format(historicTask.getDueDate())).isEqualTo(simpleDateFormat.format(dueDateValue));
assertThat(historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(2);
boolean hasProcessVariable = false;
boolean hasTaskVariable = false;
List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).list();
for (HistoricVariableInstance historicVariableInstance : variables) {
if ("var1".equals(historicVariableInstance.getVariableName())) {
hasProcessVariable = true;
assertThat(historicVariableInstance.getValue()).isEqualTo("test");
assertThat(historicVariableInstance.getProcessInstanceId()).isEqualTo(processInstance.getProcessInstanceId());
assertThat(historicVariableInstance.getTaskId()).isNull();
} else if ("localVar1".equals(historicVariableInstance.getVariableName())) {
hasTaskVariable = true;
assertThat(historicVariableInstance.getValue()).isEqualTo("test2");
assertThat(historicVariableInstance.getProcessInstanceId()).isEqualTo(processInstance.getProcessInstanceId());
assertThat(historicVariableInstance.getTaskId()).isEqualTo(task.getId());
}
}
assertThat(hasProcessVariable).isTrue();
assertThat(hasTaskVariable).isTrue();
assertThat(historyService.createHistoricDetailQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(2);
}
} | true |
a0f17fcbcd37f7b9d641f35a7934caf49f745653 | Java | samantang/backAffaire | /affaires/src/main/java/org/bonnes/affaires/servicesImpl/FavoriServiceImpl.java | UTF-8 | 3,604 | 2.078125 | 2 | [] | no_license | /**
*
*/
package org.bonnes.affaires.servicesImpl;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.transaction.Transactional;
import org.bonnes.affaires.dao.AnnonceRepository;
import org.bonnes.affaires.dao.FavoriRepository;
import org.bonnes.affaires.dao.UserDao;
import org.bonnes.affaires.entites.Annonce;
import org.bonnes.affaires.entites.Favori;
import org.bonnes.affaires.entites.TypeAnnonce;
import org.bonnes.affaires.entites.utilisateurs.User;
import org.bonnes.affaires.services.FavoriService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author salioubah
*
*/
@Transactional
@Service
public class FavoriServiceImpl implements FavoriService{
@Autowired
private FavoriRepository favoriRepository;
@Autowired
private AnnonceRepository annonceRepository;
@Autowired
private UserDao userDao;
/* (non-Javadoc)
* @see org.bonnes.affaires.services.FavoriService#addFavori(java.lang.Long, org.bonnes.affaires.entites.utilisateurs.User)
*/
@Override
public Favori addFavori(Long idAnnonce, User user) {
Annonce annonce = new Annonce();
Favori favori = new Favori();
if(annonceValide(idAnnonce)){
// DateFormat df = new SimpleDateFormat("yyy/MM/dd hh:mm", Locale.FRANCE);
// Date now = new Date();
// String dateString = df.format(now);
annonce = annonceRepository.findOne(idAnnonce);
// if(annonce.getNatureAnnonce().equals("demande")){
// favori = new Favori(annonce, null, user, new Date());
// favori = favoriRepository.saveAndFlush(favori);
// user.getDemandeFavorites().add(favori);
// userDao.save(user);
// }else{
// favori = new Favori(annonce, null, user, new Date());
// favori = favoriRepository.saveAndFlush(favori);
// user.getOffresFavorites().add(favori);
// userDao.save(user);
// }
favori = new Favori(annonce, new Date(), user);
favori = favoriRepository.saveAndFlush(favori);
user.getMesFavoris().add(favori);
userDao.save(user);
}
return favori;
}
/**
* @param idAnnonce
* @return
*/
private boolean annonceValide(Long idAnnonce) {
return true;
}
/* (non-Javadoc)
* @see org.bonnes.affaires.services.FavoriService#getFavoris(org.bonnes.affaires.entites.utilisateurs.User)
*/
@Override
public List<Favori> getFavoris(User user) {
// List<Favori> demandes = (List) user.getDemandeFavorites();
// List<Favori> offres = (List) user.getOffresFavorites();
return (List<Favori>) user.getMesFavoris();
}
/* (non-Javadoc)
* @see org.bonnes.affaires.services.AlerteService#deleteFavori(java.lang.Long, org.bonnes.affaires.entites.utilisateurs.User)
*/
@Override
public Favori deleteFavori(Long idFavori, User user) {
Favori favori = new Favori();
if(favoriExiste(idFavori) && favoriAppartientAuser(idFavori, user)){
System.out.println("l'id de l'annonce est "+idFavori);
favori = favoriRepository.findOne(idFavori);
user.getMesFavoris().remove(favori);
favoriRepository.delete(favori);
}
return favori;
}
/**
* @param idFavori
* @param user
* @return
*/
private boolean favoriAppartientAuser(Long idFavori, User user) {
// TODO Auto-generated method stub
return true;
}
/**
* @param idFavori
* @return
*/
private boolean favoriExiste(Long idFavori) {
// TODO Auto-generated method stub
return true;
}
}
| true |
373c442cc8b686daf27fcb751399feb0fa36e478 | Java | polydevops/unit-conversion-calculator | /src/main/java/com/polydevops/unit_conversion_calculator/unit/Quart.java | UTF-8 | 2,236 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | package com.polydevops.unit_conversion_calculator.unit;
import com.polydevops.unit_conversion_calculator.UnitGroup;
import com.polydevops.unit_conversion_calculator.UnitType;
import com.polydevops.unit_conversion_calculator.throwable.InvalidConversionException;
/**
* Created by connor on 5/25/16.
*/
public class Quart extends Unit {
public Quart(double unitAmount) {
super(unitAmount);
}
@Override
public String getUnitType() {
return UnitType.QUART;
}
@Override
public String getUnitGroup() {
return UnitGroup.VOLUME;
}
@Override
public Gram convertToGrams() throws InvalidConversionException {
throw new InvalidConversionException("Cannot convert from Quarts to Grams.");
}
@Override
public Ounce convertToOunces() throws InvalidConversionException {
throw new InvalidConversionException("Cannot convert from Quarts to Ounces.");
}
@Override
public Milliliter convertToMilliliters() {
final double millilitersToQuartsRatio = 946.353;
return new Milliliter(value * millilitersToQuartsRatio);
}
@Override
public Liter convertToLiters() {
final double litersToQuartsRatio = .946353;
return new Liter(value * litersToQuartsRatio);
}
@Override
public Teaspoon convertToTeaspoons() {
final double teaspoonsToQuartsRatio = 192.0;
return new Teaspoon(value * teaspoonsToQuartsRatio);
}
@Override
public Tablespoon convertToTablespoons() {
final double tablespoonsToQuartsRatio = 64.0;
return new Tablespoon(value * tablespoonsToQuartsRatio);
}
@Override
public Cup convertToCups() {
final double cupsToQuartsRatio = 4.0;
return new Cup(value * cupsToQuartsRatio);
}
@Override
public Pint convertToPints() {
final double pintsToQuartsRatio = 2.0;
return new Pint(value * pintsToQuartsRatio);
}
@Override
public Quart convertToQuarts() {
return this;
}
@Override
public FluidOunce convertToFluidOunces() {
final double fluidOuncesToQuartsRatio = 32.0;
return new FluidOunce(value * fluidOuncesToQuartsRatio);
}
}
| true |
4bfdf8493df9f0ec1e0d1bf2ce329d5ea1df75f1 | Java | Ignorance-of-Dong/Algorithm | /leetcode_solved/leetcode_2437_Number_of_Valid_Clock_Times.java | UTF-8 | 928 | 3.03125 | 3 | [] | no_license | // AC: Runtime 0 ms Beats 100%
// Memory 41.8 MB Beats 50%
// judge from the right-most bit(from second)
// T:O(1), S:O(1)
//
class Solution {
public int countTime(String time) {
int ret = 1;
if (time.charAt(4) == '?') {
ret = 10;
}
if (time.charAt(3) == '?') {
ret *= 6;
}
char zeroBit = time.charAt(0);
if (time.charAt(1) == '?') {
if (zeroBit == '?') {
ret *= 24;
} else {
if (zeroBit == '0' || zeroBit == '1') {
ret *= 10;
} else {
ret *= 4;
}
}
} else {
if (zeroBit == '?') {
if (time.charAt(1) >= '4') {
ret *= 2;
} else {
ret *= 3;
}
}
}
return ret;
}
}
| true |
308949b859278b43a2c4715f46d5d6ab4ed709c7 | Java | VaniaRomero/tp2-Quidditch | /src/main/java/Guardian.java | UTF-8 | 1,988 | 3.109375 | 3 | [] | no_license | import java.util.Random;
public class Guardian extends Jugador {
private Integer nivelDeReflejos;
private Integer fuerza;
private Integer randomNumber = 3;
public Guardian(Integer skill, Integer nivelDeReflejos, Integer fuerza, Integer peso, Escoba escoba, Equipo equipo) {
super(peso, escoba, skill, equipo);
this.setNivelDeReflejos(nivelDeReflejos);
this.fuerza = fuerza;
}
public Integer getNivelDeReflejos() {
return nivelDeReflejos;
}
public void setNivelDeReflejos(Integer nivelDeReflejos) {
this.nivelDeReflejos = nivelDeReflejos;
}
/** Su habilidad es skill + velocidad del jugador, seteados en clase padre Jugadpr. Mas nivel de reflejo y fuerza**/
public Integer habilidad() {
return super.habilidad() + this.getNivelDeReflejos() + this.fuerza;
}
/**Puede bloquear si sale 3 en un random **/
public Boolean puedeBloquear(Jugador jugador) {
this.setRandomNumber();
return 3 == this.getRandomNumber();
}
public void setRandomNumber() {
Random ran = new Random();
this.setRandomNumber((int) (ran.nextDouble() * 3) + 1);
}
/**Metodo sos Jugador**/
public Boolean sosCazador() {
return false;
}
public Boolean sosBuscador() {
return false;
}
public Boolean sosGuardian() {
return true;
}
public Boolean sosGolpeador() {
return false;
}
public Integer getRandomNumber() {
return randomNumber;
}
public void setRandomNumber(Integer randomNumber) {
this.randomNumber = randomNumber;
}
/**
* Es blanco util si si equipo no tiene pelota
**/
public Boolean esBlancoUtil() {
return !this.equipo.tenesQuafflee();
}
/**
* El guardian solo bloquea
**/
public void juega() {
}
public void eligeUnBlancoUtil() {
this.equipo.getRandomBlancoUtilEquipoContrario();
}
} | true |
591aee1c81ed34c1918d91c5e949e3d483b4ca24 | Java | itangelawu/TrianglePuzzle | /src/main/java/com/angela/trianglePuzzle/Puzzle.java | UTF-8 | 1,716 | 3.515625 | 4 | [] | no_license | package com.angela.trianglePuzzle;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* Created by Angela on 4/14/2017.
*/
public class Puzzle {
private Node start;
public Puzzle(Node n){
this.start = n;
}
public List<Integer> findMax(Node n) {
int path[] = new int[10000];;
List<List<Integer>> paths = new ArrayList<List<Integer>>();
findMaxRecursive(n, path, paths, 0);
return paths.get(0);
}
public void findMaxRecursive(Node n, int[] path, List<List<Integer>> paths, int pathLen) {
if (n == null)
return;
/* append this node to the path */
path[pathLen] = n.getWeight();
pathLen++;
/* it's a leaf*/
if (n.getLeft() == null && n.getRight() == null) {
addPath(path,paths,pathLen);
}
else
{
/* otherwise try both subtrees */
findMaxRecursive(n.getLeft(), path, paths, pathLen);
findMaxRecursive(n.getRight(), path, paths, pathLen);
}
}
public void addPath(int[] path, List<List<Integer>> paths, int pathLen){
int i;
long cSum = 0;
long pSum = 0;
List<Integer> l = new ArrayList<Integer>();
for (i = 0; i < pathLen; i++){
l.add(path[i]);
cSum+=path[i];
}
//always put largest series in the collection
if(paths.size()>0){
for(int j = 0; j < paths.get(0).size(); j++)
pSum+= (paths.get(0)).get(j);
if(cSum>pSum) {
paths.set(0, l);
return;
}
}else
paths.add(l);
}
}
| true |
c3b62031a6503e88ebfeb6b244cfd396c5030213 | Java | moutainhigh/lease_hc | /hc-lease-wx-adapter-api/src/main/java/com/hc/lease/wx/model/LeaseWxCar.java | UTF-8 | 10,953 | 1.945313 | 2 | [] | no_license | package com.hc.lease.wx.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
public class LeaseWxCar implements Serializable {
@ApiModelProperty(value = "主键id", hidden = false)
private Long id;
@ApiModelProperty(value = "车辆名称", hidden = false)
private String carName;
@ApiModelProperty(value = "市场指导价", hidden = false)
private BigDecimal marketPrice;
@ApiModelProperty(value = "主图", hidden = false)
private String mainImg;
@ApiModelProperty(value = "缩略图", hidden = false)
private String thumbnailImg;
@ApiModelProperty(value = "车身结构", hidden = false)
private String carStructure;
@ApiModelProperty(value = "长宽高", hidden = false)
private String longWidthHeight;
@ApiModelProperty(value = "发动机", hidden = false)
private String engine;
@ApiModelProperty(value = "变速箱", hidden = false)
private String transmission;
@ApiModelProperty(value = "驱动方式", hidden = false)
private String driveMode;
@ApiModelProperty(value = "燃料方式", hidden = false)
private String fuelMode;
@ApiModelProperty(value = "综合油耗", hidden = false)
private String fuel;
@ApiModelProperty(value = "详情图片", hidden = false)
private String detailImg;
@ApiModelProperty(value = "创建时间", hidden = false)
private Date createTime;
@ApiModelProperty(value = "修改时间", hidden = false)
private Date updateTime;
@ApiModelProperty(value = "创建人", hidden = false)
private Long createBy;
@ApiModelProperty(value = "修改人", hidden = false)
private Long updateBy;
@ApiModelProperty(value = "是否启用", hidden = false)
private Boolean isEnable;
@ApiModelProperty(value = "排序", hidden = false)
private Integer sort;
@ApiModelProperty(value = "快充时间", hidden = false)
private Integer fastTime;
@ApiModelProperty(value = "慢充时间", hidden = false)
private Integer slowTime;
@ApiModelProperty(value = "快充电量", hidden = false)
private Integer fastChargeQuantity;
@ApiModelProperty(value = "电动机总功率", hidden = false)
private Integer totalPower;
@ApiModelProperty(value = "续航里程", hidden = false)
private Integer enduranceMileage;
@ApiModelProperty(value = "电池容量", hidden = false)
private Integer batteryCapacity;
@ApiModelProperty(value = "燃料类型(1汽油 2混合动力 3新能源)", hidden = false)
private Integer type;
@ApiModelProperty(value = "接收的主图", hidden = false)
private List<String> mainImgs;
@ApiModelProperty(value = "接收的详情图", hidden = false)
private List<String> detailImgs;
@ApiModelProperty(value = "车辆融租方案(多个)", hidden = false)
private List<LeaseWxCarScheme> leaseWxCarSchemes;
@ApiModelProperty(value = "车辆融租方案(多个)", hidden = false)
private String leaseWxCarSchemeJson;
@ApiModelProperty(value = "用于修改排序记录位置变化", hidden = false)
private Integer mark;
//1+X方案
@ApiModelProperty(value = "首付", hidden = false)
private BigDecimal downPayment;
@ApiModelProperty(value = "月租", hidden = false)
private BigDecimal monthlyRent;
@ApiModelProperty(value = "第一年分期数", hidden = false)
private Integer firstYearStagingNumber;
@ApiModelProperty(value = "尾款", hidden = false)
private BigDecimal balancePayment;
@ApiModelProperty(value = "尾款分期List", hidden = false)
private List<BalancePaymentStagingNumberVo> balancePaymentStagingNumberList;
@ApiModelProperty(value = "尾款分期(显示)", hidden = false)
private Object balancePaymentStagingNumber;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName == null ? null : carName.trim();
}
public BigDecimal getMarketPrice() {
return marketPrice;
}
public void setMarketPrice(BigDecimal marketPrice) {
this.marketPrice = marketPrice;
}
public String getMainImg() {
return mainImg;
}
public void setMainImg(String mainImg) {
this.mainImg = mainImg == null ? null : mainImg.trim();
}
public String getCarStructure() {
return carStructure;
}
public void setCarStructure(String carStructure) {
this.carStructure = carStructure == null ? null : carStructure.trim();
}
public String getLongWidthHeight() {
return longWidthHeight;
}
public void setLongWidthHeight(String longWidthHeight) {
this.longWidthHeight = longWidthHeight == null ? null : longWidthHeight.trim();
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine == null ? null : engine.trim();
}
public String getTransmission() {
return transmission;
}
public void setTransmission(String transmission) {
this.transmission = transmission == null ? null : transmission.trim();
}
public String getDriveMode() {
return driveMode;
}
public void setDriveMode(String driveMode) {
this.driveMode = driveMode == null ? null : driveMode.trim();
}
public String getFuelMode() {
return fuelMode;
}
public void setFuelMode(String fuelMode) {
this.fuelMode = fuelMode == null ? null : fuelMode.trim();
}
public String getFuel() {
return fuel;
}
public void setFuel(String fuel) {
this.fuel = fuel == null ? null : fuel.trim();
}
public String getDetailImg() {
return detailImg;
}
public void setDetailImg(String detailImg) {
this.detailImg = detailImg == null ? null : detailImg.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Long getCreateBy() {
return createBy;
}
public void setCreateBy(Long createBy) {
this.createBy = createBy;
}
public Long getUpdateBy() {
return updateBy;
}
public void setUpdateBy(Long updateBy) {
this.updateBy = updateBy;
}
public Boolean getIsEnable() {
return isEnable;
}
public void setIsEnable(Boolean isEnable) {
this.isEnable = isEnable;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public List<String> getMainImgs() {
return mainImgs;
}
public void setMainImgs(List<String> mainImgs) {
this.mainImgs = mainImgs;
}
public List<String> getDetailImgs() {
return detailImgs;
}
public void setDetailImgs(List<String> detailImgs) {
this.detailImgs = detailImgs;
}
public List<LeaseWxCarScheme> getLeaseWxCarSchemes() {
return leaseWxCarSchemes;
}
public void setLeaseWxCarSchemes(List<LeaseWxCarScheme> leaseWxCarSchemes) {
this.leaseWxCarSchemes = leaseWxCarSchemes;
}
public Integer getMark() {
return mark;
}
public void setMark(Integer mark) {
this.mark = mark;
}
public String getLeaseWxCarSchemeJson() {
return leaseWxCarSchemeJson;
}
public void setLeaseWxCarSchemeJson(String leaseWxCarSchemeJson) {
this.leaseWxCarSchemeJson = leaseWxCarSchemeJson;
}
public String getThumbnailImg() {
return thumbnailImg;
}
public void setThumbnailImg(String thumbnailImg) {
this.thumbnailImg = thumbnailImg;
}
public BigDecimal getDownPayment() {
return downPayment;
}
public void setDownPayment(BigDecimal downPayment) {
this.downPayment = downPayment;
}
public BigDecimal getMonthlyRent() {
return monthlyRent;
}
public void setMonthlyRent(BigDecimal monthlyRent) {
this.monthlyRent = monthlyRent;
}
public Integer getFirstYearStagingNumber() {
return firstYearStagingNumber;
}
public void setFirstYearStagingNumber(Integer firstYearStagingNumber) {
this.firstYearStagingNumber = firstYearStagingNumber;
}
public BigDecimal getBalancePayment() {
return balancePayment;
}
public void setBalancePayment(BigDecimal balancePayment) {
this.balancePayment = balancePayment;
}
public List<BalancePaymentStagingNumberVo> getBalancePaymentStagingNumberList() {
return balancePaymentStagingNumberList;
}
public void setBalancePaymentStagingNumberList(List<BalancePaymentStagingNumberVo> balancePaymentStagingNumberList) {
this.balancePaymentStagingNumberList = balancePaymentStagingNumberList;
}
public Object getBalancePaymentStagingNumber() {
return balancePaymentStagingNumber;
}
public void setBalancePaymentStagingNumber(Object balancePaymentStagingNumber) {
this.balancePaymentStagingNumber = balancePaymentStagingNumber;
}
public Boolean getEnable() {
return isEnable;
}
public void setEnable(Boolean enable) {
isEnable = enable;
}
public Integer getFastTime() {
return fastTime;
}
public void setFastTime(Integer fastTime) {
this.fastTime = fastTime;
}
public Integer getSlowTime() {
return slowTime;
}
public void setSlowTime(Integer slowTime) {
this.slowTime = slowTime;
}
public Integer getFastChargeQuantity() {
return fastChargeQuantity;
}
public void setFastChargeQuantity(Integer fastChargeQuantity) {
this.fastChargeQuantity = fastChargeQuantity;
}
public Integer getTotalPower() {
return totalPower;
}
public void setTotalPower(Integer totalPower) {
this.totalPower = totalPower;
}
public Integer getEnduranceMileage() {
return enduranceMileage;
}
public void setEnduranceMileage(Integer enduranceMileage) {
this.enduranceMileage = enduranceMileage;
}
public Integer getBatteryCapacity() {
return batteryCapacity;
}
public void setBatteryCapacity(Integer batteryCapacity) {
this.batteryCapacity = batteryCapacity;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
} | true |
607eda02d9f84262d0a601e5dcd908be73a0534f | Java | rainmin/laputa | /app/src/main/java/com/rainmin/laputa/LoginActivity.java | UTF-8 | 1,365 | 2.078125 | 2 | [] | no_license | package com.rainmin.laputa;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.rainmin.common.utils.HrefUtils;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
EditText etUsername = findViewById(R.id.et_username);
EditText etPassword = findViewById(R.id.et_password);
Button btnLogin = findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(etUsername.getText().toString())
|| TextUtils.isEmpty(etPassword.getText().toString())) {
showMessage("用户名或密码不能为空");
} else {
HrefUtils.getInstance().hrefActivity(LoginActivity.this, MainActivity.class);
finish();
}
}
});
}
private void showMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
| true |
1e0a04d8abcd89bc06d39b91552a5605dde348e1 | Java | qjafcunuas/jbromo | /jbromo-dao/jbromo-dao-jpa/jbromo-dao-jpa-model/src/test/java/org/jbromo/sample/server/model/src/compositepk/UserSurnamePk.java | UTF-8 | 1,658 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package org.jbromo.sample.server.model.src.compositepk;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.jbromo.model.jpa.compositepk.AbstractCompositePk;
import org.jbromo.sample.server.model.src.UserSurname;
/**
* A user surname primary key.
*
* @author qjafcunuas
*
*/
@NoArgsConstructor
@ToString
@Embeddable
@Getter
@Setter(AccessLevel.NONE)
public class UserSurnamePk extends AbstractCompositePk {
/**
* serial version UID.
*/
private static final long serialVersionUID = -1868241073221114671L;
/**
* The user id.
*/
@Column(name = "USER_ID", nullable = false)
private Long userId;
/**
* Another pk, not functionnaly sense, only for having composite pk example.
*/
@Column(name = "CITY_ID", nullable = false)
private Long cityId;
/**
* Default constructor.
*
* @param surname
* the user surname of the primary key.
*/
public UserSurnamePk(final UserSurname surname) {
super(surname);
if (surname != null) {
if (surname.getUser() != null) {
this.userId = surname.getUser().getPrimaryKey();
}
if (surname.getCity() != null) {
this.cityId = surname.getCity().getPrimaryKey();
}
}
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(final Object obj) {
return super.equals(obj);
}
}
| true |
479882ed5fbe717a8573c1838861803c9085a6e4 | Java | slay-maker/SharedWorkspace | /Just Drive 2-14-18/src/org/usfirst/frc/team5608/robot/Robot.java | UTF-8 | 509 | 2.21875 | 2 | [] | no_license | package org.usfirst.frc.team5608.robot;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.Timer;
@SuppressWarnings({ "deprecation", "unused" })
public class Robot extends SampleRobot {
RobotDrive m_robotDrive;
public Robot() {
}
@Override
public void robotInit() {
}
@Override
public void autonomous() {
}
@Override
public void operatorControl() {
while (isOperatorControl() && isEnabled()) {
m_robotDrive.tankDrive();
}
}
@Override
public void test() {
}
}
| true |
bd11c884b1428b1d938ef0478430920db84b3d01 | Java | galeb/galeb | /legba/src/main/java/io/galeb/legba/model/v1/Rule.java | UTF-8 | 1,448 | 1.96875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2014-2018 Globo.com - ATeam
* All rights reserved.
*
* This source is subject to the Apache License, Version 2.0.
* Please see the LICENSE file for more information.
*
* Authors: See AUTHORS file
*
* 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 io.galeb.legba.model.v1;
import org.springframework.util.Assert;
public class Rule extends AbstractEntity {
private Pool pool;
private Boolean global = false;
private RuleType ruleType;
public Rule() {}
public Pool getPool() {
return pool;
}
public Rule setPool(Pool pool) {
Assert.notNull(pool, "[Assertion failed] - this argument is required; it must not be null");
updateHash();
this.pool = pool;
return this;
}
public boolean isGlobal() {
return global;
}
public Rule setGlobal(Boolean global) {
if (global != null) {
updateHash();
this.global = global;
}
return this;
}
public RuleType getRuleType() {
return ruleType;
}
public void setRuleType(RuleType ruleType) {
this.ruleType = ruleType;
}
}
| true |
a7015b9da5032e9e418f8b9e4b05a629957121ed | Java | Kuxha/Solutions-to-OOP-with-Java | /mooc-2013-OOProgrammingWithJava-PART2/week11-week11_40.Calculator/src/CalciListener.java | UTF-8 | 1,701 | 3.125 | 3 | [] | no_license |
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CalciListener implements ActionListener {
private Calculator calculator;
private JTextField input;
private JTextField output;
private JButton plus;
private JButton minus;
private JButton reset;
CalciListener(Calculator calculator, JTextField input, JTextField output, JButton plus, JButton minus, JButton reset) {
this.calculator = calculator;
this.input = input;
this.output = output;
this.plus = plus;
this.minus = minus;
this.reset = reset;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == plus) {
pressPlus();
} else if (e.getSource() == minus) {
pressMinus();
} else {
pressReset();
}
}
private void setOutput() {
output.setText("" + calculator.getValue());
reset.setEnabled(true);
}
private void pressPlus() {
try {
calculator.Plus(Integer.parseInt(input.getText()));
setOutput();
} catch (NumberFormatException exception) {
}
input.setText("");
}
private void pressMinus() {
try {
calculator.Minus(Integer.parseInt(input.getText()));
setOutput();
} catch (NumberFormatException exception) {
}
input.setText("");
}
private void pressReset() {
calculator.Reset();
output.setText("0");
input.setText("");
reset.setEnabled(false);
}
}
| true |
9cae9a3cba28017422e8f29eaa1e6667cda0a0c5 | Java | pankaj-sharma-hawk/learning-stuff | /springboot-auth-updated/src/main/java/com/auth0/samples/authapi/springbootauthupdated/keyauth/repository/ApplicationUserRepository.java | UTF-8 | 411 | 1.8125 | 2 | [] | no_license | package com.auth0.samples.authapi.springbootauthupdated.keyauth.repository;
import com.auth0.samples.authapi.springbootauthupdated.keyauth.model.ApplicationUser;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by pankaj on 02,2019
*/
public interface ApplicationUserRepository extends JpaRepository<ApplicationUser,Long> {
ApplicationUser findByUsername(String userName);
}
| true |
4778bc79e3f74a5af52ff2e0b591683c6e305f5b | Java | asadbek-571/messanger-chat | /src/main/java/app/chat/service/impl/GroupUserServiceImpl.java | UTF-8 | 8,624 | 1.992188 | 2 | [] | no_license | package app.chat.service.impl;
import app.chat.entity.group.Group;
import app.chat.entity.group.GroupUser;
import app.chat.entity.group.GroupUserPermission;
import app.chat.entity.personal.Personal;
import app.chat.entity.user.User;
import app.chat.enums.ChatPermissions;
import app.chat.enums.ChatRoleEnum;
import app.chat.enums.ErrorEnum;
import app.chat.enums.Lang;
import app.chat.helpers.UserSession;
import app.chat.helpers.Utils;
import app.chat.model.dto.MemberDto;
import app.chat.model.req.group.GroupMemberReqDto;
import app.chat.model.resp.group.GroupMemberRespDto;
import app.chat.repository.ChatRoleRepo;
import app.chat.repository.GroupUserPermissionRepo;
import app.chat.repository.group.GroupRepo;
import app.chat.repository.group.GroupUserRepo;
import app.chat.repository.user.UserRepo;
import app.chat.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static app.chat.model.ApiResponse.response;
@Service
@Transactional
@RequiredArgsConstructor
public class GroupUserServiceImpl implements GroupUserService {
private final GroupUserPermissionRepo groupUserPermissionRepo;
private final UserContactService userContactService;
private final ChannelUserService channelUserService;
private final GroupUserRepo groupMemberRepo;
private final GroupUserRepo groupUserRepo;
private final ChatRoleRepo chatRoleRepo;
private final UserSession session;
private final GroupRepo groupRepo;
private final ErrorService error;
private final UserRepo userRepo;
private final GroupService groupService;
@Autowired
PersonalService personalService;
@Override
public ResponseEntity<?> addMembers(GroupMemberReqDto dto) {
User activeUser = session.getUser();
//todo check existing group
Optional<Group> groupOptional = groupRepo.findById(dto.getGroupId());
if (groupOptional.isEmpty()) {
return response(error.message(ErrorEnum.GROUP_NOT_FOUND.getCode(), Lang.RU, dto.getGroupId()));
}
Group group = groupOptional.get();
//todo check am I a member of this group
Optional<GroupUser> memberOptional = groupMemberRepo.findByUser_IdAndGroup_IdAndActiveTrue(activeUser.getId(), dto.getGroupId());
if (memberOptional.isEmpty()) {
return response(error.message(ErrorEnum.YOU_NOT_MEMBER_IN_GROUP.getCode(), Lang.RU, dto.getGroupId()), HttpStatus.BAD_REQUEST);
}
//todo check permission for add member
List<String> permissions = groupUserPermissionRepo.getPermissions(activeUser.getId(), group.getId());
if (!permissions.contains(ChatPermissions.ADD_MEMBER.name())) {
return response(error.message(ErrorEnum.NO_PERMISSION.getCode(), Lang.RU, dto.getGroupId()));
}
//todo check joining member not delete account
List<GroupMemberRespDto> newMembers = new ArrayList<>();
dto.getMemberIdList().forEach(memberId -> {
Optional<User> userOptional = userRepo.findById(memberId);
if (userOptional.isEmpty()) {
newMembers.add(new GroupMemberRespDto(memberId, false, error.message(ErrorEnum.USER_NOT_FOUND.getCode(), Lang.RU, memberId)));
} else {
User newMember = userOptional.get();
//todo find my group mate for add user validation
boolean itsMyFriend = !Utils.isEmpty(findMyGroupMate(memberId));
//todo find in my contacts
if (!Utils.isEmpty(userContactService.findInMyContacts(memberId)) && !itsMyFriend) {
itsMyFriend = true;
}
//todo men admin yoki owner bo`lgan kanallardan tekshirish
if (!Utils.isEmpty(channelUserService.findMyAuthorityChannelFollower(memberId)) && !itsMyFriend) {
itsMyFriend = true;
}
//todo find in my personals
if (!itsMyFriend){
for (Personal personal : personalService.getMyPersonals()) {
if (personal.getUser1().getId().equals(memberId) || personal.getUser2().getId().equals(memberId)) {
itsMyFriend = true;
break;
}
}
}
if (!userOptional.get().isActive()) {
newMembers.add(new GroupMemberRespDto(memberId, false, error.message(ErrorEnum.USER_NOT_FOUND.getCode(), Lang.RU, memberId)));
} else if (!itsMyFriend) {
newMembers.add(new GroupMemberRespDto(memberId, false, error.message(ErrorEnum.CHAT_NOT_FOUND.getCode(), Lang.RU, memberId)));
} else {
//todo already exist in group
if (groupUserRepo.existsByUserAndGroupAndActiveTrue(newMember, group)) {
newMembers.add(new GroupMemberRespDto(memberId, false, error.message(ErrorEnum.MEMBER_ALREADY_EXIST.getCode(), Lang.RU, memberId)));
} else if (false/**todo check the privacy policy of joining members**/) {
//todo userni gurux yoki kanalga qo`shish ximoyasini tikshirish qismi
//todo user settings service kutilmoqda
} else {
newMembers.add(new GroupMemberRespDto(memberId, true, ""));
}
}
}
});
newMembers.forEach(newMember -> {
if (newMember.getAdded()) {
GroupUser groupUser = new GroupUser();
groupUser.setGroup(group);
groupUser.setUser(userRepo.getById(newMember.getUserId()));
groupUser.setIsMute(false);
groupUser.setIsPinned(false);
groupUser.setChatRole(chatRoleRepo.findByRole(ChatRoleEnum.MEMBER).get());
attachPermissions(groupUserRepo.save(groupUser), ChatRoleEnum.MEMBER);
groupUserRepo.save(groupUser);
}
});
return response(newMembers, (long) newMembers.size(), HttpStatus.OK);
}
@Override
public ResponseEntity<?> getSortedMembers(Long groupId) {
Optional<Group> optionalGroup = groupRepo.findById(groupId);
if (optionalGroup.isEmpty()) {
return response(error.message(30, Lang.RU, groupId), HttpStatus.NOT_FOUND);
}
List<GroupUser> groupMembers = groupUserRepo.findAllByGroup_IdAndActiveTrue(groupId);//, Sort.by("user.firstName").descending()
List<MemberDto> responseGroupMembersDto = new ArrayList<>();
groupMembers.forEach(groupUser -> {
MemberDto memberDto = new MemberDto();
memberDto.setMember(groupUser.getUser());
memberDto.setChatId(groupId);
memberDto.setRole(groupUser.getChatRole().getRole());
responseGroupMembersDto.add(memberDto);
});
return response(responseGroupMembersDto, (long) responseGroupMembersDto.size(), HttpStatus.OK);
}
@Override
public GroupUser findMyGroupMate(Long searchedFriendId) {
//todo get i`m follow groups
List<Group> groups = userRepo.getGroup(session.getUserId());
for (Group group : groups) {
if (group.isActive()) {
//todo get i`m follow group members
List<GroupUser> members = groupUserRepo.findByGroup_IdAndActiveTrue(group.getId());
//todo for each group members
for (GroupUser member : members) {
if (member.getUser().isActive()) {
if (member.getUser().getId().equals(searchedFriendId)) {
return member;
}
}
}
}
}
return null;
}
public void attachPermissions(GroupUser groupUser, ChatRoleEnum role) {
List<GroupUserPermission> permissions = new ArrayList<>();
Set<ChatPermissions> permission = ChatPermissions.getPermission(role);
permission.forEach(chatPermission -> {
permissions.add(new GroupUserPermission(groupUser, chatPermission));
});
groupUserPermissionRepo.saveAll(permissions);
}
}
| true |
fa4858fe73ecbfa18e88ece110a99b3f71fb01eb | Java | WolvesWithSword/PathfinderGenerator | /App/app/src/main/java/com/wolveswithsword/pathfindergeneratorapp/View/RecyclerView_adapter_holder/item/ArmorViewHolder.java | UTF-8 | 4,158 | 2.34375 | 2 | [] | no_license | package com.wolveswithsword.pathfindergeneratorapp.View.RecyclerView_adapter_holder.item;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.wolveswithsword.pathfindergeneratorapp.R;
import com.wolveswithsword.pathfindergeneratorapp.View.Listener.SmartItemButtonListener;
import item.armor.ArmorShield;
import item.armor.Material;
import item.armor.Type;
public class ArmorViewHolder extends ItemViewHolder{
LinearLayout materialLayout;
LinearLayout alterationLayout;
LinearLayout propSpeLayout;
LinearLayout smartItemLayout;
TextView name;
TextView alteration;
TextView material;
TextView propSpe1;
TextView propSpe2;
TextView price;
TextView weight;
Button smartItem;
Context context;
public ArmorViewHolder(@NonNull View itemView){
super(itemView);
name = itemView.findViewById(R.id.arm_name);
alteration = itemView.findViewById(R.id.arm_alteration);
material = itemView.findViewById(R.id.arm_material);
propSpe1 = itemView.findViewById(R.id.arm_propspe1);
propSpe2 = itemView.findViewById(R.id.arm_propspe2);
price = itemView.findViewById(R.id.arm_price);
weight = itemView.findViewById(R.id.arm_weight);
materialLayout = itemView.findViewById(R.id.arm_material_layout);
alterationLayout = itemView.findViewById(R.id.arm_alteration_layout);
propSpeLayout = itemView.findViewById(R.id.arm_propspe_layout);
smartItemLayout = itemView.findViewById(R.id.armor_smartitem_layout);
image = itemView.findViewById(R.id.arm_image);
delete = itemView.findViewById(R.id.armor_delete);
smartItem = itemView.findViewById(R.id.armor_smartitem);
context = itemView.getContext();
}
public void setArmor(ArmorShield armorShield){
name.setText(armorShield.getName());
//Alteration de l'arme
if(armorShield.getAlteration() == -1 || armorShield.getAlteration() == 0){
alterationLayout.setVisibility(View.GONE);
}
else if(armorShield.getAlteration() == -2){
alterationLayout.setVisibility(View.VISIBLE);
alteration.setText(R.string.masterwork);
}
else{
alterationLayout.setVisibility(View.VISIBLE);
alteration.setText(Integer.toString(armorShield.getAlteration()));
}
//Materiel
if(armorShield.getMaterial() == Material.NOTHING){
materialLayout.setVisibility(View.GONE);
}
else{
materialLayout.setVisibility(View.VISIBLE);
material.setText(armorShield.getMaterial().toString());
}
//Propriété spéciale
if(armorShield.getSpecialPropertie1().getName() != "_"){
propSpeLayout.setVisibility(View.VISIBLE);
propSpe1.setText(armorShield.getSpecialPropertie1().getName());
if(armorShield.getSpecialPropertie2().getName() != "_"){
propSpe2.setVisibility(View.VISIBLE);
propSpe2.setText(armorShield.getSpecialPropertie2().getName());
}
else{
propSpe2.setVisibility(View.GONE);
}
}
else{
propSpeLayout.setVisibility(View.GONE);
}
price.setText(armorShield.getPrice()+" "+context.getString(R.string.gp));
weight.setText(armorShield.getWeight()+" "+context.getString(R.string.kg));
if(armorShield.getTypeArmor() == Type.SHIELD){
image.setImageResource(R.drawable.item_shield_image);
}
else{
image.setImageResource(R.drawable.item_armor_image);
}
//Smart Item
if(armorShield.getSmartItem() != null){
smartItemLayout.setVisibility(View.VISIBLE);
smartItem.setOnClickListener(new SmartItemButtonListener(context,armorShield.getSmartItem()));
}
else{
smartItemLayout.setVisibility(View.GONE);
}
}
}
| true |
cea86019053de5084301a0efae0fed7ef1c3a8ec | Java | jin/android-projects | /java_only_big_connected/module84/src/main/java/module84packageJava0/Foo0.java | UTF-8 | 512 | 1.984375 | 2 | [] | no_license | package module84packageJava0;
public class Foo0 {
public void foo0() {
new module92packageJava0.Foo0().foo2();
new module99packageJava0.Foo0().foo2();
new module87packageJava0.Foo0().foo2();
new module88packageJava0.Foo0().foo2();
new module98packageJava0.Foo0().foo2();
new module89packageJava0.Foo0().foo2();
new module96packageJava0.Foo0().foo2();
new module91packageJava0.Foo0().foo2();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
}
| true |
2c53ed2c530d4b998e9ebcb0e370d2e64c5cd942 | Java | wizerstudios/dosomethingAndroid_Aug2016 | /app/src/main/java/com/dosomething/android/GCMIntentService.java | UTF-8 | 13,845 | 1.757813 | 2 | [] | no_license | package com.dosomething.android;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.BigTextStyle;
import android.util.Log;
import com.dosomething.android.CommonClasses.SharedPrefrences;
import com.google.android.gcm.GCMBaseIntentService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GCMIntentService extends GCMBaseIntentService {
private int NOTIFCATION_ID = 0;
private String conversationid = "";
private String push_type = "";
SharedPrefrences sharedPrefrences = new SharedPrefrences();
private String senderId = "";
public static final String RECIEVING_REQUEST = "request_received";
String setting_sound;
String message = "";
String newmessage = "";
String display = "";
String type;
public GCMIntentService() {
super();
}
public GCMIntentService(String... senderIds) {
super(senderIds);
}
@Override
protected void onError(Context arg0, String arg1) {
Log.v("GCMIntentService", "Error :" + arg1);
}
@Override
protected void onMessage(Context context, Intent intent) {
//check whether the user and password can still be used
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.home_button);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
try {
if (intent.hasExtra("setting_sound")) {
setting_sound = intent.getExtras().getString("setting_sound");
sharedPrefrences.setSetting_Sound(context, setting_sound);
} else {
setting_sound = "1";
}
/* if(sharedPrefrences.getSetting_Sound(context).equals("1"))
{
mBuilder.setSound(uri);
}*/
Log.d("RESPONCE", intent.getExtras().toString());
try {
message = intent.getExtras().getString("message");
if (intent.hasExtra("push_type")) {
type = intent.getExtras().getString("push_type");
assert type != null;
if (type.equals("chat")) {
sharedPrefrences.setPushType(context, "chat");
assert message != null;
String[] parts = message.split(" ");
String part = parts[4];
sharedPrefrences.setFriendFirstname(context, part.trim());
sharedPrefrences.setChatMessage(context, sharedPrefrences.getChatmessage(context) + "\n" + message);
display = sharedPrefrences.getChatmessage(context);
NOTIFCATION_ID = 0;
} else if (type.equals("sendrequest")) {
sharedPrefrences.setPushType(context, "sendrequest");
assert message != null;
String[] parts = message.split(" ");
String part = parts[6];
sharedPrefrences.setFriendFirstname(context, part.trim());
if (intent.hasExtra("senderId")) {
senderId = intent.getExtras().getString("senderId");
sharedPrefrences.setFriendUserId(context, senderId);
} else {
senderId = "";
}
if (intent.hasExtra("conversationid")) {
conversationid = intent.getExtras().getString("conversationid");
sharedPrefrences.setConversationId(context, conversationid);
} else {
conversationid = "";
}
sharedPrefrences.setStatusMeassge(context, message);
display = sharedPrefrences.getStatusmeassge(context);
newmessage = message;
NOTIFCATION_ID = 1;
broadCast(RECIEVING_REQUEST);
}
}
if (intent.hasExtra("conversationid")) {
conversationid = intent.getExtras().getString("conversationid");
} else {
conversationid = "";
}
if (intent.hasExtra("senderId")) {
senderId = intent.getExtras().getString("senderId");
} else {
senderId = "";
}
assert message != null;
if (message.length() == 0)
message = "";
} catch (Exception e) {
e.printStackTrace();
}
/* System.out.println("====" + intent.getExtras().getString("message"));
BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
bigStyle.bigText(message);*/
Intent newsIntent = null;
if (conversationid != null && conversationid.length() > 0) {
newsIntent = new Intent(context, DoSomethingStatus.class);
newsIntent.putExtra("GCM_chat", true);
newsIntent.putExtra("conversationid", conversationid);
newsIntent.putExtra("senderId", senderId);
newsIntent.putExtra("push_type", type);
} else {
newsIntent = new Intent(context, SplashActivity.class);
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notificationIntent = PendingIntent.getActivity(this, 0,
newsIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
Notification notification = mBuilder.setSmallIcon(R.drawable.home_button).setWhen(0)
.setAutoCancel(true)
.setContentTitle(getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(display))
.setContentIntent(notificationIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(largeIcon)
.setContentText(display).build();
/* mBuilder.setSmallIcon(R.drawable.home_button);
mBuilder.setLargeIcon(largeIcon);
mBuilder.setColor(getResources().getColor(R.color.notification_icon_background));
mBuilder.setContentTitle(getString(R.string.app_name));
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mBuilder.setAutoCancel(true);*/
/*if (intent.hasExtra("setting_sound")) {
setting_sound = intent.getExtras().getString("setting_sound");
sharedPrefrences.setSetting_Sound(context, setting_sound);
} else {
setting_sound = "1";
}
if(sharedPrefrences.getSetting_Sound(context).equals("1"))
{
mBuilder.setSound(uri);
}
Log.d("RESPONCE", intent.getExtras().toString());
try {
message = intent.getExtras().getString("message");
if (intent.hasExtra("push_type")) {
type = intent.getExtras().getString("push_type");
assert type != null;
if (type.equals("chat")) {
sharedPrefrences.setPushType(context,"chat");
assert message != null;
String[] parts = message.split(" ");
String part = parts[4];
sharedPrefrences.setFriendFirstname(context, part);
} else if (type.equals("sendrequest")) {
sharedPrefrences.setPushType(context,"sendrequest");
assert message != null;
String[] parts = message.split(" ");
String part = parts[6];
sharedPrefrences.setFriendFirstname(context, part);
if (intent.hasExtra("senderId")) {
senderId = intent.getExtras().getString("senderId");
sharedPrefrences.setFriendUserId(context, senderId);
} else {
senderId = "";
}
if (intent.hasExtra("conversationid")) {
conversationid = intent.getExtras().getString("conversationid");
sharedPrefrences.setConversationId(context, conversationid);
} else {
conversationid = "";
}
broadCast(RECIEVING_REQUEST);
}
}
if (intent.hasExtra("conversationid")) {
conversationid = intent.getExtras().getString("conversationid");
} else {
conversationid = "";
}
if (intent.hasExtra("senderId")) {
senderId = intent.getExtras().getString("senderId");
} else {
senderId = "";
}
assert message != null;
if (message.length() == 0)
message = "";
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("====" + intent.getExtras().getString("message"));
BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
bigStyle.bigText(message);
mBuilder.setContentText(message);
mBuilder.setStyle(bigStyle);
mBuilder.setContentIntent(notificationIntent);*/
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFCATION_ID, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
private void broadCast(String recieverAction) {
try {
Log.d("Sending bradcast::::", "::::" + recieverAction);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(recieverAction);
sendBroadcast(broadcastIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onRegistered(final Context context, final String regId) {
sharedPrefrences.setDeviceToken(context, regId);
Thread thread = new Thread(new Runnable() {
@SuppressLint("LongLogTag")
@Override
public void run() {
String result = "";
try {
HttpClient httpClient = new DefaultHttpClient();
String URL = getString(R.string.dosomething_apilink_string_push) + "device_id" + "=" + regId;
String devName = Build.SERIAL;
if (devName == null || devName.length() == 0)
devName = "" + System.currentTimeMillis();
Log.i("TAG", "android.os.Build.SERIAL: " + devName);
Log.i("TAG", "android.os.Build.SERIAL: " + regId);
JSONObject data = new JSONObject();
data.put("device_id", regId);
Log.d("api_registerForPushAndroid", "" + URL + "data" + data);
HttpPost postRequest = new HttpPost(URL);
StringEntity se = new StringEntity(data.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
postRequest.setEntity(se);
HttpResponse response;
response = httpClient.execute(postRequest);
Log.d("getStatusCode", "" + response.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("result", result);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
@Override
protected void onUnregistered(Context arg0, String arg1) {
Log.v("onUNRegistered", "");
}
}
| true |
730f7f66fb650eebeb7308ebcc1f0f26cd982bdf | Java | veiserath/GUI | /AntiPlagueInc/src/com/company/view/GameParametersPanel.java | UTF-8 | 2,153 | 2.96875 | 3 | [] | no_license | package com.company.view;
import com.company.controller.GameTime;
import com.company.elements.Country;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.util.List;
public class GameParametersPanel extends JPanel {
JLabel labelPoints;
JLabel labelVirusAdvancement;
JLabel labelTime;
GameTime gameTime;
public GameParametersPanel(List<Country> countries) {
this.gameTime = new GameTime();
gameTime.start();
this.setLayout(new GridLayout(1, 3));
this.setLayout(new FlowLayout());
this.labelPoints = new JLabel();
this.labelVirusAdvancement = new JLabel();
this.labelTime = new JLabel();
Border border = BorderFactory.createLineBorder(Color.BLACK, 2);
labelPoints.setBorder(border);
labelVirusAdvancement.setBorder(border);
labelTime.setBorder(border);
add(labelPoints, FlowLayout.LEFT);
add(labelVirusAdvancement, FlowLayout.CENTER);
add(labelTime, FlowLayout.RIGHT);
worldPopulation(countries);
thread.start();
}
public void updateParameters() {
this.labelPoints.setText("Points available: " + Country.getPointsOfAllCountries());
this.labelVirusAdvancement.setText("Infected: " + Country.getInfectedOfAllCountries() + " cured: " + Country.getCuredOfAllCountries() + " died: " + Country.getDiedOfAllCountries());
this.labelTime.setText("Time elapsed: " + gameTime.getMinutes() + " : " + gameTime.getSeconds());
}
public void worldPopulation(List<Country> countries) {
for (Country country : countries) {
Country.setTotalPopulationOfAllCountries(Country.getTotalPopulationOfAllCountries() + country.getTotalPopulation());
}
}
Thread thread = new Thread(() -> {
while (!Thread.interrupted()) {
updateParameters();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
public GameTime getGameTime() {
return gameTime;
}
}
| true |
1af8904fe1cce2f0a003f9ba2842cd9a7c4cd3e0 | Java | nhantranutc/DATN | /src/main/java/application/data/entity/User.java | UTF-8 | 1,042 | 2.140625 | 2 | [] | no_license | package application.data.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.Date;
@Getter
@Setter
@Entity(name = "dbo_userdefinition")
public class User {
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
@Id
private int id;
@Column(name = "user_name")
private String userName;
@Column(name = "password_hash")
private String passwordHash;
@Column(name = "full_name")
private String fullName;
@Column(name = "address_name")
private String addressName;
@Column(name = "birthday")
private Date birthday;
@Column(name = "gender")
private String gender;
@Column(name = "phone_number")
private String phoneNumber;
@Column(name = "email")
private String email;
@Column(name = "avatar")
private String avatar;
@Column(name = "user_active")
private int userActive;
@Column(name = "is_delete")
private int isDelete;
@Transient
private String password;
}
| true |
01fca28b35ada653a07bd990b1c6887f258f28ad | Java | DongCanRola/servicebsf | /src/main/java/cn/dcan/dto/CustomerDTO.java | UTF-8 | 1,500 | 2.296875 | 2 | [] | no_license | package cn.dcan.dto;
import java.io.Serializable;
/**
* Created by dongc_000 on 2018/5/1.
*/
public class CustomerDTO implements Serializable{
private int id;
private int type;
private String name;
private int provideType;
private String manager;
private String telephone;
private String email;
private String address;
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setType(int type) {
this.type = type;
}
public int getType() {
return this.type;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setProvideType(int type) {
this.provideType = type;
}
public int getProvideType() {
return this.provideType;
}
public void setManager(String manager) {
this.manager = manager;
}
public String getManager() {
return this.manager;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getTelephone() {
return this.telephone;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return this.email;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return this.address;
}
}
| true |
32aaa4fb18044a1eae05dff934f07c06deaab4a4 | Java | LeeGodSRC/MineHQ | /uHub/src/main/java/com/frozenorb/uhub/configs/LocationsConfig.java | UTF-8 | 324 | 1.625 | 2 | [
"MIT"
] | permissive | package com.frozenorb.uhub.configs;
import com.frozenorb.commonlibs.ConfigHelper;
import com.frozenorb.uhub.uHubPlugin;
public class LocationsConfig extends ConfigHelper {
public LocationsConfig(String name, String directory) {
super(uHubPlugin.getProvidingPlugin(uHubPlugin.class), name, directory);
}
}
| true |
bfd636e66209e87754df7fbb071fd18e964a005b | Java | GoalSwallow/miniproject | /src/main/java/com/swallow/miniproject/bean/Retuen_Repay_Result.java | UTF-8 | 370 | 1.648438 | 2 | [] | no_license | package com.swallow.miniproject.bean;
import lombok.Data;
@Data
public class Retuen_Repay_Result extends Base{
//返回状态码
private String return_code;
//返回信息
private String return_msg;
//预支付ID
private String prepay_id;
//业务结果
private String result_code;
//错误描述
private String err_code_des;
}
| true |
a990b0ddcb18bae3d00110a6438e5642379a7bf8 | Java | laurolins/blink | /src/linsoft/gui/bean/EditorColunaDialog.java | UTF-8 | 5,149 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | package linsoft.gui.bean;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
/**
* Diálogo para editar a posição e a visibilidade das colunas
* de um table model.
*/
public class EditorColunaDialog extends JDialog {
JPanel _panel = new JPanel();
JButton _botaoOk = new JButton();
JButton _botaoCancelar = new JButton();
GridBagLayout gridBagLayout1 = new GridBagLayout();
JButton _botaoSubir = new JButton();
JButton _botaoDescer = new JButton();
JScrollPane _scrollPane = new JScrollPane();
JTable _table = new JTable();
public EditorColunaDialog() {
setModal(true);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
public EditorColunaDialog(JFrame frame, String titulo) {
super(frame, titulo, true);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
protected void jbInit() throws Exception {
_panel.setLayout(gridBagLayout1);
_botaoOk.setMaximumSize(new Dimension(85, 27));
_botaoOk.setMinimumSize(new Dimension(85, 27));
_botaoOk.setPreferredSize(new Dimension(85, 27));
_botaoOk.setText("Ok");
_botaoOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
_botaoOk_actionPerformed(e);
}
});
_botaoCancelar.setText("Cancelar");
_botaoCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
_botaoCancelar_actionPerformed(e);
}
});
_botaoSubir.setMaximumSize(new Dimension(71, 27));
_botaoSubir.setMinimumSize(new Dimension(71, 27));
_botaoSubir.setText("Sobe");
_botaoSubir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
_botaoSubir_actionPerformed(e);
}
});
_botaoDescer.setText("Desce");
_botaoDescer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
_botaoDescer_actionPerformed(e);
}
});
this.getContentPane().add(_panel, BorderLayout.CENTER);
_panel.add(_botaoOk, new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
_panel.add(_botaoCancelar, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0));
_panel.add(_botaoSubir, new GridBagConstraints(2, 0, 1, 1, 0.0, 1.0
,GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 5, 5, 5), 0, 0));
_panel.add(_botaoDescer, new GridBagConstraints(2, 1, 1, 1, 0.0, 1.0
,GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
_panel.add(_scrollPane, new GridBagConstraints(0, 0, 2, 2, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
_scrollPane.getViewport().add(_table, null);
_table.setModel(new ColunaTableModel());
}
void _botaoOk_actionPerformed(ActionEvent e) {
ColunaTableModel model = (ColunaTableModel) _table.getModel();
model.atualizarModelo();
this.setVisible(false);
}
void _botaoCancelar_actionPerformed(ActionEvent e) {
this.setVisible(false);
}
void _botaoSubir_actionPerformed(ActionEvent e) {
int row = _table.getSelectedRow();
if(row != -1) {
ColunaTableModel model = (ColunaTableModel) _table.getModel();
model.diminuirPosicao(row);
_table.getSelectionModel().setSelectionInterval(row - 1, row - 1);
model.fireTableRowsUpdated(row - 1, row);
}
}
void _botaoDescer_actionPerformed(ActionEvent e) {
int row = _table.getSelectedRow();
if(row != -1) {
ColunaTableModel model = (ColunaTableModel) _table.getModel();
model.aumentarPosicao(row);
_table.getSelectionModel().setSelectionInterval(row + 1, row + 1);
model.fireTableRowsUpdated(row, row + 1);
}
}
public void setTableModel(TableModel model) {
ColunaTableModel colunaTableModel = (ColunaTableModel) _table.getModel();
colunaTableModel.setTableModel(model);
}
} | true |
99233f8bed364d01e768c63b35e0c1637e9889d2 | Java | lizm335/MyLizm | /com.gzedu.xlims.biz/src/main/java/com/gzedu/xlims/serviceImpl/graduation/GjtGraduationStudentProgServiceImpl.java | UTF-8 | 1,872 | 2.03125 | 2 | [] | no_license | package com.gzedu.xlims.serviceImpl.graduation;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gzedu.xlims.common.UUIDUtils;
import com.gzedu.xlims.dao.graduation.GjtGraduationStudentProgDao;
import com.gzedu.xlims.pojo.graduation.GjtGraduationStudentProg;
import com.gzedu.xlims.service.graduation.GjtGraduationStudentProgService;
@Service
public class GjtGraduationStudentProgServiceImpl implements GjtGraduationStudentProgService {
private static final Log log = LogFactory.getLog(GjtGraduationStudentProgServiceImpl.class);
@Autowired
private GjtGraduationStudentProgDao gjtGraduationStudentProgDao;
@Override
public GjtGraduationStudentProg queryOneByCode(String batchId, String studentId, int progressType,
String progressCode) {
return gjtGraduationStudentProgDao.queryOneByCode(batchId, studentId, progressType, progressCode);
}
@Override
public void insert(GjtGraduationStudentProg entity) {
log.info("entity:[" + entity + "]");
entity.setProgressId(UUIDUtils.random());
entity.setCreatedDt(new Date());
gjtGraduationStudentProgDao.save(entity);
}
@Override
public void insert(List<GjtGraduationStudentProg> entityList) {
log.info("entityList:[" + entityList + "]");
gjtGraduationStudentProgDao.save(entityList);
}
@Override
public List<GjtGraduationStudentProg> queryListByStudent(String batchId, String studentId, int progressType) {
return gjtGraduationStudentProgDao.queryListByStudent(batchId, studentId, progressType);
}
@Override
public void delete(List<GjtGraduationStudentProg> entityList) {
log.info("entityList:[" + entityList + "]");
gjtGraduationStudentProgDao.delete(entityList);
}
}
| true |
ea67319c0a3926e48ee40ac2eba151f290bfbd28 | Java | gspandy/zx-parent | /ink-user/ink-user-core/src/main/java/com/ink/user/core/service/tns/ITnsAuthService.java | UTF-8 | 1,745 | 1.734375 | 2 | [] | no_license | package com.ink.user.core.service.tns;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.ink.user.core.po.TnsAuth;
import com.ink.user.core.po.TnsLog;
import com.ink.user.core.po.AccCust;
public interface ITnsAuthService {
/**
*
* @Title: insertTnsAuth
* @Description: 增加授权信息
* 创建人:guojie.gao , 2015年10月20日 下午6:20:49
* 修改人:guojie.gao , 2015年10月20日 下午6:20:49
* @param
* @return
* @throws
*
*/
public void insertTnsAuth(TnsLog tnsLog, AccCust accCust) throws Exception;
/**
*
* @Title: checkTnsAuth
* @Description: 根据交易流水编号查询授权信息
* 创建人:guojie.gao , 2015年10月20日 下午7:24:26
* 修改人:guojie.gao , 2015年10月20日 下午7:24:26
* @param
* @return
* @throws
*
*/
public TnsAuth checkTnsAuth(Long tnsLogId) throws Exception;
/**
*
* @Title: updateTnsAuth
* @Description: 根据流水编号更新授权表信息
* 创建人:guojie.gao , 2015年10月20日 下午7:26:17
* 修改人:guojie.gao , 2015年10月20日 下午7:26:17
* @param
* @return
* @throws
*
*/
public void updateTnsAuth(BigDecimal bal, long id, int version) throws Exception;
/**
*
* @Title: updateTnsAuthByrevFlg
* @Description: 更新冲正标志
* 创建人:guojie.gao , 2015年10月21日 上午11:23:50
* 修改人:guojie.gao , 2015年10月21日 上午11:23:50
* @param
* @return
* @throws
*
*/
public int updateTnsAuthByrevFlg(long id, int version) throws Exception;
/**
* 查询一段时间内未解冻的授权信息
* @return
*/
public List<TnsAuth> getUnfrozenTnsAuth(Date startTime, Date endTime);
}
| true |
1eeefb622c8917e5e89508926aac230dbf7a0b57 | Java | kyletry/book-manage | /springboot-demo/src/test/java/com/sjl/dao/BookRepositoryTest.java | UTF-8 | 1,082 | 2.40625 | 2 | [] | no_license | package com.sjl.dao;
import com.sjl.entity.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author songjilong
* @date 2020/6/25 16:55
*/
@SpringBootTest
class BookRepositoryTest {
@Autowired
private BookDao bookRepository;
@Test
void findAll(){
System.out.println(bookRepository.findAll());
}
@Test
void save(){
Book book = new Book();
book.setName("Java编程思想");
book.setAuthor("Bruce Eckel");
bookRepository.save(book);
}
@Test
void findById(){
Book book = bookRepository.findById(1L).get();
System.out.println(book);
}
@Test
void update(){
Book book = new Book();
book.setId(18L);
book.setName("张三的书");
book.setAuthor("张三");
Book save = bookRepository.save(book);
System.out.println(save);
}
@Test
void deleteById(){
bookRepository.deleteById(17L);
}
} | true |
973811af1b93a6983635414fc6c74a2209905af2 | Java | gilzilberfeld/code-ninja-old | /code-ninja-course/JAVA/src/main/java/com/codeninja/tictactoe/Board.java | UTF-8 | 391 | 3.09375 | 3 | [] | no_license | package com.codeninja.tictactoe;
public class Board {
private boolean theBoard[][];
public Board() {
theBoard = new boolean[3][3];
for (int i=0;i<=2; i++)
for (int j=0;j<=2; j++)
theBoard[i][j]=false;
}
public boolean isOccupied(int row, int column) {
return (theBoard[row][column]);
}
public void store(int row, int column) {
theBoard[row][column] = true;
}
}
| true |
f52773a237371bd4c906f99b7aa5a6e701e26a46 | Java | suppername123/glory | /src/main/java/top/glory/web/service/impl/UserServiceImpl.java | UTF-8 | 1,823 | 1.882813 | 2 | [
"MIT"
] | permissive | package top.glory.web.service.impl;
import org.springframework.stereotype.Service;
import top.glory.web.dao.UserMapper;
import top.glory.web.model.User;
import top.glory.web.service.UserService;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public User authenticationUser(User user) {
return userMapper.authenticationUser(user);
}
@Override
public User selectByLogin_name(String loginName) {
return userMapper.selectByLogin_name(loginName);
}
@Override
public int insert(User user) {
return userMapper.insert(user);
}
@Override
public int updatepwd(User user) {
return userMapper.updatepwd(user);
}
@Override
public User selectupdate(User user) {
return userMapper.selectupdate(user);
}
@Override
public List<User> showAllData(User user) {
return userMapper.showAllData(user);
}
@Override
public User showUserById(Integer id) {
return userMapper.showUserById(id);
}
@Override
public int deleteById(Integer id) {
return userMapper.deleteById(id);
}
@Override
public int updateUser(User user) {
return userMapper.updateUser(user);
}
@Override
public int updateAllUser(User user) {
return userMapper.updateAllUser(user);
}
@Override
public int updatePasswordById(User user) {
return userMapper.updatePasswordById(user);
}
@Override
public List<User> selectAllUser(User user) {
return userMapper.selectAllUser(user);
}
@Override
public int updatecheckStatus(User user) {
return userMapper.updatecheckStatus(user);
}
}
| true |
17d504afb62a83b909c51e020238ea6f6802f509 | Java | joseagt1994/-Compi2-Proyecto1_201314863_BD | /src/com/jagt/AST/Variable.java | UTF-8 | 324 | 1.664063 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jagt.AST;
/**
*
* @author Jose Antonio
*/
public class Variable {
int tipo;
String nombre;
Objeto valor;
}
| true |
acb8b7647b87023bc3f3b8f1c931a6b38e1ca226 | Java | jonatas2014/teste2 | /Main.java | UTF-8 | 477 | 2.984375 | 3 | [] | no_license | package lista3;
public class Main {
public static void main(String[] args) {
Pessoa joao = new Pessoa();
joao.setNome("Joao");
joao.setIdade(29);
joao.setAltura(1.88);
joao.setPeso(78);
System.out.println("Imprimindo com get");
System.out.println(joao.getNome());
System.out.println(joao.getIdade());
System.out.println(joao.getAltura());
System.out.println(joao.getPeso());
System.out.println("IMC: " + joao.imc());
joao.imprimeDados();
}
}
| true |
820787577b082c25f13d59a629490ae386982a32 | Java | a5vh/IBCS | /src/Trees/BSTNode.java | UTF-8 | 540 | 2.609375 | 3 | [] | no_license | package Trees;
//********************************************************************
// BSTNode.java Author: Lewis/Loftus/Cocking
//
// A node in a binary search tree.
//********************************************************************
public class BSTNode extends TreeNode
{
//-----------------------------------------------------------------
// Initializes this node.
//-----------------------------------------------------------------
public BSTNode (Comparable data)
{
super (data, null, null);
}
}
| true |
ce6b21dc2dc37e12d3e8b5c197a8e5822ceb16b7 | Java | torworx/Vapor | /vapor-core/src/main/java/evymind/vapor/core/buffer/netty/ChannelBufferExposer.java | UTF-8 | 338 | 1.890625 | 2 | [] | no_license | package evymind.vapor.core.buffer.netty;
import org.jboss.netty.buffer.ChannelBuffer;
import evymind.vapor.core.VaporBuffer;
public interface ChannelBufferExposer extends VaporBuffer {
/**
* Returns the underlying Netty's ChannelBuffer
*
* @return the underlying Netty's ChannelBuffer
*/
ChannelBuffer channelBuffer();
}
| true |
9dad217e7572cff477f8d548419f512dce56c36b | Java | namannigam-zz/forty-bits-of-learning | /src/main/java/edu/forty/bits/problemsolving/competitive/expedia/ConsectiveSubArrayWithSumDivisibleByK.java | UTF-8 | 1,026 | 3.8125 | 4 | [] | no_license | package edu.forty.bits.problemsolving.competitive.expedia;
public class ConsectiveSubArrayWithSumDivisibleByK {
static long kSub(int k, int[] nums) {
int mod[] = new int[k]; // array to count frequency of remainders
int consecutiveSum = 0; // sum of sequence of values
for (int num : nums) { // Traverse original array
consecutiveSum += num; // compute sum of consecutives
mod[
(consecutiveSum
% k)]++; // increase count by 1 for the remainder of the sum with k in mod[] array
}
long result = 0; // result count
// Traverse the remainder array
for (int i = 0; i < k; i++) {
// If there are more than one prefix subarrays with a particular mod value.
if (mod[i] > 1) {
result += (mod[i] * (mod[i] - 1)) / 2;
}
}
// add the elements which are divisible by k itself
result += mod[0];
return result;
}
}
| true |
bad4f527b0d8fab4b5da75c7e31a67248cfd1ef8 | Java | flaime/Ovningsuppgift_Pa_map | /src/övar_på_att_testa_packet/Tree.java | ISO-8859-1 | 4,268 | 2.953125 | 3 | [] | no_license | package var_p_att_testa_packet;
import java.util.ArrayList;
import javax.swing.plaf.SliderUI;
class Node{
String namn;
int nr;
Node left, right;
Node(String namn, int nr){
this.namn = namn;
this.nr = nr;
}
public String toString(){
return namn + " " + nr;
}
} // Node
class Tree{
private Node root = null;
private Node add(Node where, Node ny){
if (where == null)
where = ny;
else if (where.nr > ny.nr)
where.left = add(where.left, ny);
else if (where.nr < ny.nr)
where.right = add(where.right, ny);
return where;
}
public void add(Node ny){
root = add(root, ny);
}
public int size(){
size = 0;
size(root);
return size;
}
private int size;
private void size(Node nodAttUtgFrn){
if(nodAttUtgFrn != null){
size++;
size(nodAttUtgFrn.left);
size(nodAttUtgFrn.right);
}
}
public void print(){
print(root );// , 0);
}
private void print(Node where){
if (where != null){
print(where.right);
System.out.println(where);
print(where.left);
}
}
public int height() {
return height(root, 0);
}
private int height(Node nodAttUtgFrNode, int hjd) {
if (nodAttUtgFrNode != null) {
hjd++;
int hjdVnster = height(nodAttUtgFrNode.left,hjd);
int hjdHger = height(nodAttUtgFrNode.right, hjd);
if(hjdVnster >= hjdHger){
return hjdVnster;
}
else if(hjdHger >= hjdVnster){
return hjdHger;
}
}
return hjd;
}
public void printTree() {
rader = new ArrayList<ArrayList<String>>();
printTree(root, 0);
for (ArrayList<String> al : rader) {
System.out.println(al.toString());
// for(String s : al){
// System.out.println(s);
// }
}
System.out.println(rader.size());
}
String trdet;
ArrayList<ArrayList<String>> rader;
private void printTree(Node nodAttUtgFrNode, int niv) {
if (nodAttUtgFrNode != null) {
if(rader.size() > niv){
// System.out.println(rader.size()+" >= "+ niv);
rader.get(niv).add(nodAttUtgFrNode.namn);
}
else {
// System.out.println(rader.size()+" "+ niv);
ArrayList<String> tillflig = new ArrayList<String>();
tillflig.add(nodAttUtgFrNode.namn);
rader.add(tillflig);
}
niv++;
printTree(nodAttUtgFrNode.left, niv);
printTree(nodAttUtgFrNode.right, niv);
}else {
if(rader.size() > niv){
// System.out.println(rader.size()+" >= "+ niv);
rader.get(niv).add("_______");
}
else {
// System.out.println(rader.size()+" "+ niv);
ArrayList<String> tillflig = new ArrayList<String>();
tillflig.add("_______");
rader.add(tillflig);
}
}
//hr brjar utritandet
trdet = nodAttUtgFrNode.namn + trdet;
}
private String[] printTreeNew(Node nodAttUtgFrNode, int niv){
if(nodAttUtgFrNode != null){
String[] left = printTreeNew(nodAttUtgFrNode.left, ++niv);
String[] right = printTreeNew(nodAttUtgFrNode.right, ++niv);
String trdet;
if (left[1].length() > right[1].length()) {
for(int i = 0; i < left[1].length();i++){
if(i == left.length - 1){
trdet += "/\\";
}else {
trdet += "_";
}
}
}
}
return "fuck somthing";
}
}
class TreeExempel{
public static void main(String[] args){
Tree tree = new Tree();
tree.add(new Node("Stefan", 47));
tree.add(new Node("Bea", 29));
tree.add(new Node("Jozef", 73));
tree.add(new Node("Anna", 17));
tree.add(new Node("Harald", 61));
tree.add(new Node("Eskel", 97));
tree.add(new Node("Mats", 52));
tree.add(new Node("Tobbe", 67));
tree.add(new Node("Alex", 85));
tree.add(new Node("Peter", 103));
tree.add(new Node("Doris", 80));
// tree.print();
//
// System.out.println("det finns " + tree.size() + " antal noder i trdet.");
//
// System.out.println("Hjden p trdet r " + tree.height() + " hgt.");
tree.printTree();
}
}
| true |
5d08476652f62cbb919323211922c858a42e8de7 | Java | stethu/EdabitChallenges | /IsTheStringInOrder.java | UTF-8 | 387 | 3.015625 | 3 | [] | no_license | import java.util.Arrays;
//https://edabit.com/challenge/KWbrmP9uYSnYtwkAB
public class IsTheStringInOrder {
public static boolean isInOrder(String str){
char [] strAsChar = str.toCharArray();
Arrays.sort(strAsChar);
String temp = new String(strAsChar);
if (str.equals(temp))
{
return true;
}
return false;
}
}
| true |
a8a6a5894357e2e57d3f63fba022b84b73de797e | Java | gitter-badger/android-fuze | /app/src/test/java/io/gmas/fuze/commons/MockTrackingClient.java | UTF-8 | 780 | 1.976563 | 2 | [
"Apache-2.0"
] | permissive | package io.gmas.fuze.commons;
import android.support.annotation.NonNull;
import java.util.Map;
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
public class MockTrackingClient extends TrackingClientType {
public static class Event {
private final String name;
private final Map<String, Object> properties;
public Event(final String name, final Map<String, Object> properties) {
this.name = name;
this.properties = properties;
}
}
public final @NonNull PublishSubject<Event> events = PublishSubject.create();
public final @NonNull Observable<String> eventNames = events.map(e -> e.name);
@Override public void trackGoogleAnalytics(@NonNull String screenName) {
}
}
| true |
2f12882f3c9471dc9f3514c81d8f565d9cbb6d86 | Java | lutece-platform/lutece-core | /src/java/fr/paris/lutece/portal/service/editor/EditorBbcodeService.java | UTF-8 | 9,068 | 1.609375 | 2 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | /*
* Copyright (c) 2002-2022, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* License 1.0
*/
package fr.paris.lutece.portal.service.editor;
import fr.paris.lutece.portal.business.editor.ParserComplexElement;
import fr.paris.lutece.portal.business.editor.ParserElement;
import fr.paris.lutece.portal.service.util.AppPropertiesService;
import fr.paris.lutece.util.parser.BbcodeUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
*
* This class Provides a parser BBCODE
*
*/
public class EditorBbcodeService implements IEditorBbcodeService
{
/** Constants **/
private static final String CONSTANT_EDITOR_BBCODE_ELEMENT_CODE = "code";
private static final String CONSTANT_EDITOR_BBCODE_ELEMENT_VALUE = "value";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_TAG_NAME = "tagName";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_OPEN_SUBST_WITH_PARAM = "openSubstWithParam";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_CLOSE_SUBST_WITH_PARAM = "closeSubstWithParam";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_OPEN_SUBST_WITHOUT_PARAM = "openSubstWithoutParam";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_CLOSE_SUBST_WITHOUT_PARAM = "closeSubstWithoutParam";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_INTERNAL_SUBST = "internalSubst";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_PROCESS_INTERNAL_TAGS = "processInternalTags";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_ACCEPT_PARAM = "acceptParam";
private static final String CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_REQUIRES_QUOTED_PARAM = "requiresQuotedParam";
/** Properties **/
private static final String PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH = "editors.parser.bbcode.complexElement";
private static final String PROPERTY_EDITOR_BBCODE_ELEMENT_PATH = "editors.parser.bbcode.element";
private static final String PROPERTY_PARSER_ELEMENTS = "editors.parser.bbcode.elements";
private static final String PROPERTY_PARSER_COMPLEX_ELEMENTS = "editors.parser.bbcode.complexElements";
private static final String SEPARATOR = ",";
private static EditorBbcodeService _singleton;
private static List<ParserElement> _listParserElement;
private static List<ParserComplexElement> _listParserComplexElement;
/**
* {@inheritDoc}
*/
@Override
public String parse( String strValue )
{
return BbcodeUtil.parse( strValue, _listParserElement, _listParserComplexElement );
}
/**
* Returns the unique instance of the service
*
* @return The instance of the service
*/
public static synchronized EditorBbcodeService getInstance( )
{
if ( _singleton == null )
{
_listParserElement = new ArrayList<>( );
_listParserComplexElement = new ArrayList<>( );
EditorBbcodeService service = new EditorBbcodeService( );
service.init( );
_singleton = service;
}
return _singleton;
}
/**
* Init service
*/
public void init( )
{
// init simple elements
String strParserElements = AppPropertiesService.getProperty( PROPERTY_PARSER_ELEMENTS );
if ( StringUtils.isNotBlank( strParserElements ) )
{
String [ ] tabParserElements = strParserElements.split( SEPARATOR );
String strCodeElement;
String strValueElement;
for ( int i = 0; i < tabParserElements.length; i++ )
{
strCodeElement = AppPropertiesService
.getProperty( PROPERTY_EDITOR_BBCODE_ELEMENT_PATH + "." + tabParserElements [i] + "." + CONSTANT_EDITOR_BBCODE_ELEMENT_CODE );
strValueElement = AppPropertiesService
.getProperty( PROPERTY_EDITOR_BBCODE_ELEMENT_PATH + "." + tabParserElements [i] + "." + CONSTANT_EDITOR_BBCODE_ELEMENT_VALUE );
_listParserElement.add( new ParserElement( strCodeElement, strValueElement ) );
}
}
// init complex elements
String strParserComplexElements = AppPropertiesService.getProperty( PROPERTY_PARSER_COMPLEX_ELEMENTS );
if ( StringUtils.isNotBlank( strParserComplexElements ) )
{
String [ ] tabParserComplexElements = strParserComplexElements.split( SEPARATOR );
String strTagName;
String strOpenSubstWithParam;
String strCloseSubstWithParam;
String strOpenSubstWithoutParam;
String strCloseSubstWithoutParam;
String strInternalSubst;
boolean bProcessInternalTags;
boolean bAcceptParam;
boolean bRequiresQuotedParam;
for ( int i = 0; i < tabParserComplexElements.length; i++ )
{
strTagName = AppPropertiesService.getProperty( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i] + "."
+ CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_TAG_NAME );
strOpenSubstWithParam = AppPropertiesService.getProperty( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i] + "."
+ CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_OPEN_SUBST_WITH_PARAM );
strCloseSubstWithParam = AppPropertiesService.getProperty( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i]
+ "." + CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_CLOSE_SUBST_WITH_PARAM );
strOpenSubstWithoutParam = AppPropertiesService.getProperty( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i]
+ "." + CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_OPEN_SUBST_WITHOUT_PARAM );
strCloseSubstWithoutParam = AppPropertiesService.getProperty( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i]
+ "." + CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_CLOSE_SUBST_WITHOUT_PARAM );
strInternalSubst = AppPropertiesService.getProperty( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i] + "."
+ CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_INTERNAL_SUBST );
bProcessInternalTags = AppPropertiesService.getPropertyBoolean( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i]
+ "." + CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_PROCESS_INTERNAL_TAGS, false );
bAcceptParam = AppPropertiesService.getPropertyBoolean( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i] + "."
+ CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_ACCEPT_PARAM, false );
bRequiresQuotedParam = AppPropertiesService.getPropertyBoolean( PROPERTY_EDITOR_BBCODE_COMPLEX_ELEMENT_PATH + "." + tabParserComplexElements [i]
+ "." + CONSTANT_EDITOR_BBCODE_COMPLEX_ELEMENT_REQUIRES_QUOTED_PARAM, false );
_listParserComplexElement.add( new ParserComplexElement( strTagName, strOpenSubstWithParam, strCloseSubstWithParam, strOpenSubstWithoutParam,
strCloseSubstWithoutParam, strInternalSubst, bProcessInternalTags, bAcceptParam, bRequiresQuotedParam ) );
}
}
}
}
| true |
8fce515892eed781774b94fd2d52d5b32e263a0d | Java | batazor/MyExampleAndExperiments | /JAVA/Android/startandroid/p1211listwidget/src/main/java/ru/startandroid/develop/p1211listwidget/MyProvider.java | UTF-8 | 3,709 | 2.140625 | 2 | [
"MIT"
] | permissive | package ru.startandroid.develop.p1211listwidget;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
import android.widget.Toast;
public class MyProvider extends AppWidgetProvider {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
final String ACTION_ON_CLICK = "ru.startandroid.develop.p1211listwidget.itemonclick";
final static String ITEM_POSITION = "item_position";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i : appWidgetIds) {
updateWidget(context, appWidgetManager, i);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equalsIgnoreCase(ACTION_ON_CLICK)) {
int itemPos = intent.getIntExtra(ITEM_POSITION, -1);
if (itemPos != -1) {
Toast.makeText(context, "Clicked on item " + itemPos, Toast.LENGTH_SHORT).show();
}
}
}
// @Override
// public RemoteViews getViewAt(int position) {
// RemoteViews rView = new RemoteViews(context.getPackageName(),
// R.layout.item);
// rView.setTextViewText(R.id.tvItemText, data.get(position));
// Intent clickIntent = new Intent();
// clickIntent.putExtra(MyProvider.ITEM_POSITION, position);
// rView.setOnClickFillInIntent(R.id.tvItemText, clickIntent);
//
// return rView;
// }
void updateWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
RemoteViews rv = new RemoteViews(context.getPackageName(),
R.layout.widget);
setUpdateTV(rv, context, appWidgetId);
setList(rv, context, appWidgetId);
setListClick(rv, context, appWidgetId);
appWidgetManager.updateAppWidget(appWidgetId, rv);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.lvList);
}
void setUpdateTV(RemoteViews rv, Context context, int appWidgetId) {
rv.setTextViewText(R.id.tvUpdate,
sdf.format(new Date(System.currentTimeMillis())));
Intent updIntent = new Intent(context, MyProvider.class);
updIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
updIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
new int[] { appWidgetId });
PendingIntent updPIntent = PendingIntent.getBroadcast(context,
appWidgetId, updIntent, 0);
rv.setOnClickPendingIntent(R.id.tvUpdate, updPIntent);
}
void setList(RemoteViews rv, Context context, int appWidgetId) {
Intent adapter = new Intent(context, MyService.class);
adapter.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
Uri data = Uri.parse(adapter.toUri(Intent.URI_INTENT_SCHEME));
adapter.setData(data);
rv.setRemoteAdapter(R.id.lvList, adapter);
}
void setListClick(RemoteViews rv, Context context, int appWidgetId) {
Intent listClickIntent = new Intent(context, MyProvider.class);
listClickIntent.setAction(ACTION_ON_CLICK);
PendingIntent listClickPIntent = PendingIntent.getBroadcast(context, 0,
listClickIntent, 0);
rv.setPendingIntentTemplate(R.id.lvList, listClickPIntent);
}
} | true |
e965e401f68d0c05250e7b5e2d32d6bfbbc5352f | Java | a-kunitskaya/java-tasks | /src/main/java/com/kunitskaya/module3/service/implementation/finders/BiggestBookFinder.java | UTF-8 | 2,260 | 2.828125 | 3 | [] | no_license | package com.kunitskaya.module3.service.implementation.finders;
import com.kunitskaya.module3.domain.library.Author;
import com.kunitskaya.module3.domain.library.Book;
import com.kunitskaya.module3.service.StreamObjectFinder;
import org.apache.commons.lang3.StringUtils;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;
import static com.kunitskaya.logging.ProjectLogger.LOGGER;
public class BiggestBookFinder implements StreamObjectFinder<Book> {
private static final String FOUND_BOOK_MESSAGE = "Book: %s, pages number: %s";
private static final String BIGGEST_BOOK_MESSAGE = "Biggest book: %s, pages number: %s";
private static final String NOT_FOUND_MESSAGE = "No biggest book is found by author: %s";
@Override
public Book find(Stream<Book> books) {
Optional<Book> book = books.peek(b -> LOGGER.info(String.format(FOUND_BOOK_MESSAGE, b.getTitle(), b.getNumberOfPages())))
.max(Comparator.comparingInt(Book::getNumberOfPages));
if (book.isPresent()) {
Book biggestBook = book.get();
LOGGER.info(String.format(BIGGEST_BOOK_MESSAGE, biggestBook.getTitle(), biggestBook.getNumberOfPages()));
return biggestBook;
} else {
LOGGER.error(String.format(NOT_FOUND_MESSAGE, StringUtils.EMPTY));
return null;
}
}
public Book find(Author author) {
String authorName = author.getName();
LOGGER.info("Finding biggest book by author: " + authorName);
Optional<Book> book = author.getBooks().stream()
.peek(b -> LOGGER.info(String.format(FOUND_BOOK_MESSAGE, b.getTitle(), b.getNumberOfPages())))
.sorted(Comparator.comparingInt(Book::getNumberOfPages).reversed())
.findFirst();
if (book.isPresent()) {
Book biggestBook = book.get();
LOGGER.info(String.format(BIGGEST_BOOK_MESSAGE, biggestBook.getTitle(), biggestBook.getNumberOfPages()));
return biggestBook;
} else {
LOGGER.error(String.format(NOT_FOUND_MESSAGE, authorName));
return null;
}
}
}
| true |
7fab57c528e685e003ebe4d3f68dea42bc0214f0 | Java | oscarcillo/Ejemplo_MVC_DAO_AccesoDatos | /src/vistas/ViewEquipos.java | UTF-8 | 369 | 2.484375 | 2 | [] | no_license | package vistas;
import java.util.List;
import modelos.Equipos;
import modelos.Jugador;
public class ViewEquipos {
public void viewEquipo(Equipos equipo) {
System.out.println("Datos del equipo: " +equipo);
}
public void viewTodosEquipos(List<Equipos> equipos) {
for (Equipos equipo: equipos) {
System.out.println("Datos del equipo: "+ equipo);
}
}
}
| true |
dbfd4cd5d6273001b507125a78f398ad822d4e04 | Java | Zond47/Epam_task6 | /src/test/java/com/epam/rd/java/basic/practice6/part5/TreeTest.java | UTF-8 | 1,245 | 3.28125 | 3 | [] | no_license | package com.epam.rd.java.basic.practice6.part5;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class TreeTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream STD_OUT = System.out;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void restoreStreams() {
System.setOut(STD_OUT);
}
@Test
public void shouldAddElement() {
Tree<Integer> tree = new Tree<>();
Assert.assertTrue(tree.add(3));
}
@Test
public void shouldAddElements() {
Tree<Integer> tree = new Tree<>();
tree.add(new Integer[]{1, 2, 5, 4, 6, 0});
tree.print();
String expected = " 0\r\n" + "1\r\n" + " 2\r\n" + " 4\r\n" + " 5\r\n" + " 6\r\n";
Assert.assertEquals(expected, outContent.toString());
}
@Test
public void shouldRemoveElement() {
Tree<Integer> tree = new Tree<>();
tree.add(3);
tree.add(1);
tree.add(4);
Assert.assertTrue(tree.remove(4));
}
}
| true |
c1821201fc9b2c66fb2a516284b7daf69ef80c26 | Java | raikennhinn/krule | /src/main/java/com/ph/controller/RunController.java | UTF-8 | 2,651 | 2.046875 | 2 | [] | no_license | package com.ph.controller;
import com.ph.entity.httovo.RestResponse;
import com.ph.entity.httovo.RuleRunRequest;
import com.ph.service.strategy.ExecuteRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
@RestController
@RequestMapping("run")
public class RunController extends BaseController{
private static final Logger log = LoggerFactory.getLogger(RunController.class);
@Autowired
private ExecuteRouter executeRouter;
//订单策略执行
@RequestMapping(value = "/strategy", method = RequestMethod.GET)
public RestResponse runStrategy(@Valid RuleRunRequest request) throws Exception {
String productLine = request.getProduct_line();
String strategyType = request.getStrategy_type();
String packageId = request.getPackage_id();
String flowId = request.getFlow_id();
Integer serialId = request.getSerial_id();
return executeRouter.dispatcher(productLine, strategyType, packageId, flowId, serialId, false, -1);
}
//订单策略单例试跑
@RequestMapping(value = "/preview/strategy/single", method = RequestMethod.GET)
@ResponseBody
public RestResponse runStrategySingle(@Valid RuleRunRequest request) throws Exception {
String productLine = request.getProduct_line();
String strategyType = request.getStrategy_type();
String packageId = request.getPackage_id();
String flowId = request.getFlow_id();
Integer serialId = request.getSerial_id();
return executeRouter.dispatcher(productLine, strategyType, packageId, flowId, serialId, true, -1);
}
//订单策略批量试跑
@RequestMapping(value = "/preview/strategy/task", method = RequestMethod.GET)
@ResponseBody
public RestResponse runStrategyTask(HttpServletRequest request) throws Exception {
if("1".equals(request.getParameter("cmd"))){
if(ExecuteRouter.previewRunFlag == 1){
return new RestResponse<>().data(0);
}
ExecuteRouter.previewRunFlag = 1;
executeRouter.previewRun();
} else if("0".equals(request.getParameter("cmd"))){
ExecuteRouter.previewRunFlag = 0;
}
return new RestResponse<>().data(1);
}
}
| true |
4c65d41f162ec43b4057882930a1bcad06751199 | Java | zorzet/portofolioManagement | /target/src/main/java/gr/aueb/mscis/sample/service/MovieService.java | UTF-8 | 811 | 2.6875 | 3 | [] | no_license | package gr.aueb.mscis.sample.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import gr.aueb.mscis.sample.model.Movie;
import gr.aueb.mscis.sample.persistence.JPAUtil;
/**
* CRUD operations and other functionality related to movies
*
* @author bzafiris
*
*/
public class MovieService {
EntityManager em;
public MovieService() {
em = JPAUtil.getCurrentEntityManager();
}
public Movie createMovie(String title, int year, String director){
if (title == null || year < 1970 || director == null){
return null;
}
Movie newMovie = new Movie(title, year, director);
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(newMovie);
tx.commit();
return newMovie;
}
}
| true |
1f82f10aa4d8bf52777b1c00925932cb80ddf123 | Java | lannerate/ruleBuilder | /src/com/flagleader/builder/widget/u.java | UTF-8 | 1,124 | 2.046875 | 2 | [] | no_license | package com.flagleader.builder.widget;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.TreeColumn;
class u extends SelectionAdapter
{
u(s params, TreeColumn paramTreeColumn, String[] paramArrayOfString, int paramInt)
{
}
public void widgetSelected(SelectionEvent paramSelectionEvent)
{
s.d(this.a);
if ((this.b.getData("order") == null) || (this.b.getData("order").toString().equals("down")))
this.b.setData("order", "up");
else
this.b.setData("order", "down");
if ((this.c != null) && (this.d < this.c.length))
this.a.a(this.d, this.c[this.d], this.b.getData("order").toString().equals("up"));
else
this.a.a(this.d, "string", this.b.getData("order").toString().equals("up"));
if (this.b.getData("order").toString().equals("up"))
this.b.setImage(s.e());
else
this.b.setImage(s.f());
}
}
/* Location: D:\Dev_tools\ruleEngine\rbuilder.jar
* Qualified Name: com.flagleader.builder.widget.u
* JD-Core Version: 0.6.0
*/ | true |
86c01834cb918aeb7c3dd18322be1fdb6615030c | Java | sea-compfest/seapay-microservice | /seapay-domain/src/test/java/com/seapay/domain/wallet/service/WalletServiceImplTest.java | UTF-8 | 4,958 | 2.25 | 2 | [] | no_license | package com.seapay.domain.wallet.service;
import com.seapay.api.wallet.WalletService;
import com.seapay.api.wallet.request.CreateWalletRequest;
import com.seapay.api.wallet.request.TopupWalletRequest;
import com.seapay.api.wallet.request.TransferRequest;
import com.seapay.domain.utils.DatabaseUtils;
import com.seapay.domain.wallet.WalletRepository;
import com.seapay.domain.wallet.WalletServiceImpl;
import com.seapay.domain.wallet.entity.Wallet;
import com.seapay.domain.wallet.repository.WalletRepositoryImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
class WalletServiceImplTest {
private WalletRepository walletRepository = new WalletRepositoryImpl();
private WalletService walletService = new WalletServiceImpl(walletRepository);
@BeforeEach
void setUp() {
DatabaseUtils.truncate("wallets");
}
@Test
void createWalletTest() {
String userID = UUID.randomUUID().toString();
String walletID = UUID.randomUUID().toString();
CreateWalletRequest createWalletRequest = CreateWalletRequest.CreateWalletRequestBuilder.aCreateWalletRequest()
.withUserID(userID)
.withWalletID(walletID)
.build();
walletService.createWallet(createWalletRequest);
Wallet actual = walletRepository.getByUserID(userID);
assertEquals(walletID, actual.getWalletID());
assertEquals(userID, actual.getUserID());
assertEquals(0, actual.getBalance());
}
@Test
void getWalletIDTest() {
String userID = UUID.randomUUID().toString();
String walletID = UUID.randomUUID().toString();
CreateWalletRequest createWalletRequest = CreateWalletRequest.CreateWalletRequestBuilder.aCreateWalletRequest()
.withUserID(userID)
.withWalletID(walletID)
.build();
walletService.createWallet(createWalletRequest);
assertTrue(walletService.getWalletID(userID).isPresent());
assertEquals(walletID, walletService.getWalletID(userID).get());
}
@Test
void getWalletIDFailedTest() {
String randomUUID = UUID.randomUUID().toString();
assertFalse(walletService.getWalletID(randomUUID).isPresent());
assertNull(walletService.getWalletID(randomUUID).orElse(null));
}
@Test
void topUpWalletTest() {
Long topUpAmount = 400L;
String userID = UUID.randomUUID().toString();
String walletID = UUID.randomUUID().toString();
CreateWalletRequest createWalletRequest = CreateWalletRequest.CreateWalletRequestBuilder.aCreateWalletRequest()
.withUserID(userID)
.withWalletID(walletID)
.build();
walletService.createWallet(createWalletRequest);
TopupWalletRequest topupWalletRequest = new TopupWalletRequest(walletID, topUpAmount);
walletService.topupWallet(topupWalletRequest);
Wallet actual = walletRepository.getByWalletID(walletID);
assertEquals(walletID, actual.getWalletID());
assertEquals(userID, actual.getUserID());
assertEquals(topUpAmount, actual.getBalance());
}
@Test
void transferTest() {
Long transferAmount = 900L;
String sourceUserID = UUID.randomUUID().toString();
String sourceWalletID = UUID.randomUUID().toString();
CreateWalletRequest sourceCreateWalletRequest = CreateWalletRequest.CreateWalletRequestBuilder.aCreateWalletRequest()
.withUserID(sourceUserID)
.withWalletID(sourceWalletID)
.build();
walletService.createWallet(sourceCreateWalletRequest);
String targetUserID = UUID.randomUUID().toString();
String targetWalletID = UUID.randomUUID().toString();
CreateWalletRequest targetCreateWalletRequest = CreateWalletRequest.CreateWalletRequestBuilder.aCreateWalletRequest()
.withUserID(targetUserID)
.withWalletID(targetWalletID)
.build();
walletService.createWallet(targetCreateWalletRequest);
TransferRequest transferRequest = new TransferRequest(sourceWalletID, targetWalletID, transferAmount);
walletService.transfer(transferRequest);
Wallet actualSourceWallet = walletRepository.getByWalletID(sourceWalletID);
assertEquals(sourceWalletID, actualSourceWallet.getWalletID());
assertEquals(sourceUserID, actualSourceWallet.getUserID());
assertEquals(0 - transferAmount, actualSourceWallet.getBalance());
Wallet actualTargetWallet = walletRepository.getByWalletID(targetWalletID);
assertEquals(targetWalletID, actualTargetWallet.getWalletID());
assertEquals(targetUserID, actualTargetWallet.getUserID());
assertEquals(transferAmount, actualTargetWallet.getBalance());
}
} | true |
37a44f02f00c19133ae06fb0ac691994907f4c1f | Java | enyq/licenta | /Android/appClient/app/src/main/java/edu/licenta/eniko/util/Converter.java | UTF-8 | 591 | 2.703125 | 3 | [] | no_license | package edu.licenta.eniko.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Eniko on 6/12/2015.
*/
public class Converter {
public static Date stringToDate(String stringDate) {
Date date = null;
DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
date = format.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
| true |
94f80e313d4cfe968a9019ef39650a34f1f97f7e | Java | archiecobbs/dellroad-stuff | /dellroad-stuff-vaadin/dellroad-stuff-vaadin7/src/main/java/org/dellroad/stuff/vaadin7/AbstractSimpleContainer.java | UTF-8 | 20,977 | 2.390625 | 2 | [] | no_license |
/*
* Copyright (C) 2022 Archie L. Cobbs. All rights reserved.
*/
package org.dellroad.stuff.vaadin7;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.AbstractInMemoryContainer;
import com.vaadin.data.util.DefaultItemSorter;
import com.vaadin.data.util.filter.SimpleStringFilter;
import com.vaadin.data.util.filter.UnsupportedFilterException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Support superclass for simple read-only, in-memory {@link Container} implementations where each
* {@link Item} in the container is backed by a Java object.
*
* <p>
* This {@link Container}'s {@link Property}s are defined via {@link PropertyDef}s, and a {@link PropertyExtractor}
* is used to actually extract the property values from each underlying object (alternately, subclasses can override
* {@link #getPropertyValue getPropertyValue()}). However, the easist way to configure the container {@link Property}s
* is to pass a {@link ProvidesProperty @ProvidesProperty}-annotated Java class to the {@link #AbstractSimpleContainer(Class)}
* constructor.
*
* <p>
* Use {@link #load load()} to load or reload the container.
*
* @param <I> the item ID type
* @param <T> the type of the Java objects that back each {@link Item} in the container
*
* @see SimpleItem
*/
@SuppressWarnings("serial")
public abstract class AbstractSimpleContainer<I, T> extends AbstractInMemoryContainer<I, String, BackedItem<T>>
implements PropertyExtractor<T>, Container.Filterable, Container.SimpleFilterable, Container.Sortable, Connectable {
private final HashMap<String, PropertyDef<?>> propertyMap = new HashMap<>();
private final HashMap<Object, BackedItem<T>> itemMap = new HashMap<>();
private PropertyExtractor<? super T> propertyExtractor;
// Constructors
/**
* Constructor.
*
* <p>
* After using this constructor, subsequent invocations of {@link #setPropertyExtractor setPropertyExtractor()}
* and {@link #setProperties setProperties()} are required to define the properties of this container
* and how to extract them.
*/
protected AbstractSimpleContainer() {
this((PropertyExtractor<? super T>)null);
}
/**
* Constructor.
*
* <p>
* After using this constructor, a subsequent invocation of {@link #setProperties setProperties()} is required
* to define the properties of this container.
*
* @param propertyExtractor used to extract properties from the underlying Java objects;
* may be null but then container is not usable until one is configured via
* {@link #setPropertyExtractor setPropertyExtractor()}
*/
protected AbstractSimpleContainer(PropertyExtractor<? super T> propertyExtractor) {
this(propertyExtractor, null);
}
/**
* Constructor.
*
* <p>
* After using this constructor, a subsequent invocation of {@link #setPropertyExtractor setPropertyExtractor()} is required
* to define how to extract the properties of this container; alternately, subclasses can override
* {@link #getPropertyValue getPropertyValue()}.
*
* @param propertyDefs container property definitions; null is treated like the empty set
*/
protected AbstractSimpleContainer(Collection<? extends PropertyDef<?>> propertyDefs) {
this(null, propertyDefs);
}
/**
* Constructor.
*
* @param propertyExtractor used to extract properties from the underlying Java objects;
* may be null but then container is not usable until one is configured via
* {@link #setPropertyExtractor setPropertyExtractor()}
* @param propertyDefs container property definitions; null is treated like the empty set
*/
protected AbstractSimpleContainer(PropertyExtractor<? super T> propertyExtractor,
Collection<? extends PropertyDef<?>> propertyDefs) {
this.setItemSorter(new SimpleItemSorter());
this.setPropertyExtractor(propertyExtractor);
this.setProperties(propertyDefs);
}
/**
* Constructor.
*
* <p>
* Properties will be determined by the {@link ProvidesProperty @ProvidesProperty} and
* {@link ProvidesPropertySort @ProvidesPropertySort} annotated methods in the given class.
*
* @param type class to introspect for annotated methods
* @throws IllegalArgumentException if {@code type} is null
* @throws IllegalArgumentException if {@code type} has two {@link ProvidesProperty @ProvidesProperty}
* or {@link ProvidesPropertySort @ProvidesPropertySort} annotated methods for the same property
* @throws IllegalArgumentException if a {@link ProvidesProperty @ProvidesProperty}-annotated method with no
* {@linkplain ProvidesProperty#value property name specified} has a name which cannot be interpreted as a bean
* property "getter" method
* @see ProvidesProperty
* @see ProvidesPropertySort
* @see ProvidesPropertyScanner
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected AbstractSimpleContainer(Class<? super T> type) {
// Why the JLS forces this stupid cast:
// http://stackoverflow.com/questions/4902723/why-cant-a-java-type-parameter-have-a-lower-bound
final ProvidesPropertyScanner<? super T> propertyReader
= (ProvidesPropertyScanner<? super T>)new ProvidesPropertyScanner(type);
this.setItemSorter(new SimpleItemSorter());
this.setPropertyExtractor(propertyReader.getPropertyExtractor());
this.setProperties(propertyReader.getPropertyDefs());
}
// Public methods
/**
* Get the configured {@link PropertyExtractor} for this container.
*
* @return configured {@link PropertyExtractor}
*/
public PropertyExtractor<? super T> getPropertyExtractor() {
return this.propertyExtractor;
}
/**
* Change the configured {@link PropertyExtractor} for this container.
* Invoking this method does not result in any container notifications.
*
* @param propertyExtractor used to extract properties from the underlying Java objects;
* may be null but the container is not usable without one
*/
public void setPropertyExtractor(PropertyExtractor<? super T> propertyExtractor) {
this.propertyExtractor = propertyExtractor;
}
/**
* Read the value of the property defined by {@code propertyDef} from the given object.
*
* <p>
* The implementation in {@link AbstractSimpleContainer} just delegates to the {@linkplain #setPropertyExtractor configured}
* {@link PropertyExtractor}; subclasses may override to customize property extraction.
*
* @param obj Java object
* @param propertyDef definition of which property to read
* @throws NullPointerException if either parameter is null
* @throws IllegalStateException if no {@link PropertyExtractor} is configured for this container
*/
@Override
public <V> V getPropertyValue(T obj, PropertyDef<V> propertyDef) {
if (this.propertyExtractor == null)
throw new IllegalStateException("no PropertyExtractor is configured for this container");
return this.propertyExtractor.getPropertyValue(obj, propertyDef);
}
/**
* Change the configured properties of this container.
*
* @param propertyDefs container property definitions; null is treated like the empty set
* @throws IllegalArgumentException if {@code propertyDefs} contains a property with a duplicate name
*/
public void setProperties(Collection<? extends PropertyDef<?>> propertyDefs) {
if (propertyDefs == null)
propertyDefs = Collections.<PropertyDef<?>>emptySet();
this.propertyMap.clear();
for (PropertyDef<?> propertyDef : propertyDefs) {
if (this.propertyMap.put(propertyDef.getName(), propertyDef) != null)
throw new IllegalArgumentException("duplicate property name `" + propertyDef.getName() + "'");
}
this.fireContainerPropertySetChange();
}
/**
* Add or replace a configured property of this container.
*
* @param propertyDef new container property definitions
* @throws IllegalArgumentException if {@code propertyDef} is null
*/
public void setProperty(PropertyDef<?> propertyDef) {
if (propertyDef == null)
throw new IllegalArgumentException("null propertyDef");
this.propertyMap.put(propertyDef.getName(), propertyDef);
this.fireContainerPropertySetChange();
}
/**
* Change this container's contents.
*
* @param contents new container contents
* @throws IllegalArgumentException if {@code contents} or any item in {@code contents} is null
*/
public void load(Iterable<? extends T> contents) {
this.load(contents.iterator());
}
/**
* Change this container's contents.
*
* @param contents new container contents
* @throws IllegalArgumentException if {@code contents} or any item in {@code contents} is null
*/
public void load(Iterator<? extends T> contents) {
// Sanity check
if (contents == null)
throw new IllegalArgumentException("null contents");
// Reset item IDs
this.resetItemIds();
this.internalRemoveAllItems();
// Bulk load and register items with id's 0, 1, 2, ...
int index = 0;
while (contents.hasNext()) {
final T obj = contents.next();
if (obj == null)
throw new IllegalArgumentException("null item in contents at index " + index);
final BackedItem<T> item = this.createBackedItem(obj, this.propertyMap.values(), this);
this.internalAddItemAtEnd(this.generateItemId(obj), item, false);
index++;
}
// Apply filters
this.doFilterContainer(!this.getFilters().isEmpty());
// Notify subclass
this.afterReload();
// Fire event
this.fireItemSetChange();
}
@Override
protected void internalRemoveAllItems() {
super.internalRemoveAllItems();
this.itemMap.clear();
}
/**
* Get the container item ID corresponding to the given underlying Java object which is wrapped by this container.
* Objects are tested for equality using {@link Object#equals Object.equals()}.
*
* <p>
* The implementation in {@link AbstractSimpleContainer} requires a linear search of the container.
* Some subclasses may provide a more efficient implementation.
*
* <p>
* This method is not used by this class but is defined as a convenience for subclasses.
*
* <p>
* Note: items that are filtered out will not be found.
*
* @param obj underlying container object
* @return item ID corresponding to {@code object}, or null if {@code object} is not found in this container
* @throws IllegalArgumentException if {@code object} is null
* @see #getItemIdForSame
*/
public I getItemIdFor(T obj) {
if (obj == null)
throw new IllegalArgumentException("null object");
for (I itemId : this.getItemIds()) {
T candidate = this.getJavaObject(itemId);
if (obj.equals(candidate))
return itemId;
}
return null;
}
/**
* Get the container item ID corresponding to the given underlying Java object which is wrapped by this container.
* Objects are tested for equality using object equality, not {@link Object#equals Object.equals()}.
*
* <p>
* The implementation in {@link AbstractSimpleContainer} requires a linear search of the container.
* Some subclasses may provide a more efficient implementation.
*
* <p>
* This method is not used by this class but is defined as a convenience for subclasses.
*
* <p>
* Note: items that are filtered out will not be found.
*
* @param obj underlying container object
* @return item ID corresponding to {@code object}, or null if {@code object} is not found in this container
* @throws IllegalArgumentException if {@code object} is null
* @see #getItemIdFor
*/
public I getItemIdForSame(T obj) {
if (obj == null)
throw new IllegalArgumentException("null object");
for (I itemId : this.getItemIds()) {
T candidate = this.getJavaObject(itemId);
if (obj == candidate)
return itemId;
}
return null;
}
// Connectable
/**
* Connect this instance to non-Vaadin resources.
*
* <p>
* The implementation in {@link AbstractSimpleContainer} does nothing.
*
* @throws IllegalStateException if there is no {@link com.vaadin.server.VaadinSession} associated with the current thread
*/
@Override
public void connect() {
}
/**
* Disconnect this instance from non-Vaadin resources.
*
* <p>
* The implementation in {@link AbstractSimpleContainer} does nothing.
*
* @throws IllegalStateException if there is no {@link com.vaadin.server.VaadinSession} associated with the current thread
*/
@Override
public void disconnect() {
}
// Container and superclass required methods
// Workaround for http://dev.vaadin.com/ticket/8856
@Override
@SuppressWarnings("unchecked")
public List<I> getItemIds() {
return (List<I>)super.getItemIds();
}
@Override
public Set<String> getContainerPropertyIds() {
return Collections.unmodifiableSet(this.propertyMap.keySet());
}
@Override
public Property<?> getContainerProperty(Object itemId, Object propertyId) {
final BackedItem<T> entityItem = this.getItem(itemId);
if (entityItem == null)
return null;
return entityItem.getItemProperty(propertyId);
}
@Override
public Class<?> getType(Object propertyId) {
final PropertyDef<?> propertyDef = this.propertyMap.get(propertyId);
return propertyDef != null ? propertyDef.getType() : null;
}
@Override
public BackedItem<T> getUnfilteredItem(Object itemId) {
final T obj = this.getJavaObject(itemId);
if (obj == null)
return null;
BackedItem<T> item = this.itemMap.get(itemId);
if (item == null) {
item = this.createBackedItem(obj, this.propertyMap.values(), this);
this.itemMap.put(itemId, item);
}
return item;
}
// Subclass methods
/**
* Get the underlying Java object corresponding to the given item ID.
* This method ignores any filtering (i.e., filtered-out objects are still accessible).
*
* @param itemId item ID
* @return the corresponding Java object, or null if not found
*/
public abstract T getJavaObject(Object itemId);
/**
* Subclass hook invoked prior to each reload. The subclass should reset its state (e.g., issued item IDs) as required.
*/
protected abstract void resetItemIds();
/**
* Create a new, unique item ID for the given object. This method is invoked during a {@linkplain #load reload operation},
* once for each container object. Both visible and filtered objects will be passed to this method.
*
* <p>
* The returned item ID must be unique, i.e., not returned by this method since the most recent invocation of
* {@link #resetItemIds}.
*
* @param obj underlying container object, never null
* @return item ID, never null
*/
protected abstract I generateItemId(T obj);
/**
* Subclass hook invoked after each reload but prior to invoking {@link #fireItemSetChange}.
*
* <p>
* The implementation in {@link AbstractSimpleContainer} does nothing.
*/
protected void afterReload() {
}
/**
* Create a {@link BackedItem} for the given backing Java object.
*
* <p>
* The implementation in {@link AbstractSimpleContainer} returns
* {@code new SimpleItem<T>(object, propertyDefs, propertyExtractor)}.
*
* @param object underlying Java object
* @param propertyDefs property definitions
* @param propertyExtractor extracts the property value from {@code object}
* @return new {@link BackedItem}
* @throws IllegalArgumentException if any parameter is null
*/
protected BackedItem<T> createBackedItem(T object, Collection<PropertyDef<?>> propertyDefs,
PropertyExtractor<? super T> propertyExtractor) {
return new SimpleItem<>(object, propertyDefs, propertyExtractor);
}
// Container methods
@Override
public void sort(Object[] propertyId, boolean[] ascending) {
super.sortContainer(propertyId, ascending);
}
@Override
public void addContainerFilter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix) {
try {
this.addFilter(new SimpleStringFilter(propertyId, filterString, ignoreCase, onlyMatchPrefix));
} catch (UnsupportedFilterException e) {
// the filter instance created here is always valid for in-memory containers
throw new RuntimeException("unexpected exception", e);
}
}
@Override
public Collection<Container.Filter> getContainerFilters() {
return super.getContainerFilters();
}
@Override
public void removeAllContainerFilters() {
this.removeAllFilters();
}
@Override
public void removeContainerFilters(Object propertyId) {
this.removeFilters(propertyId);
}
@Override
public void addContainerFilter(Filter filter) {
this.addFilter(filter);
}
@Override
public void removeContainerFilter(Filter filter) {
this.removeFilter(filter);
}
@Override
public Collection<?> getSortableContainerPropertyIds() {
final ArrayList<String> propertyIds = new ArrayList<>(this.propertyMap.size());
for (Map.Entry<String, PropertyDef<?>> entry : this.propertyMap.entrySet()) {
if (this.propertyExtractor instanceof SortingPropertyExtractor) {
final SortingPropertyExtractor<? super T> sortingPropertyExtractor
= (SortingPropertyExtractor<? super T>)this.propertyExtractor;
if (sortingPropertyExtractor.canSort(entry.getValue())) {
propertyIds.add(entry.getKey());
continue;
}
}
if (entry.getValue().isSortable())
propertyIds.add(entry.getKey());
}
return propertyIds;
}
// ItemSorter class
/**
* {@link com.vaadin.data.util.ItemSorter} implementation used by {@link AbstractSimpleContainer}.
*/
private class SimpleItemSorter extends DefaultItemSorter {
@Override
@SuppressWarnings("unchecked")
protected int compareProperty(Object propertyId, boolean ascending, Item item1, Item item2) {
// Get property definition
final PropertyDef<?> propertyDef = AbstractSimpleContainer.this.propertyMap.get(propertyId);
if (propertyDef == null)
return super.compareProperty(propertyId, ascending, item1, item2);
// Ask SortingPropertyExtractor if we have one
if (AbstractSimpleContainer.this.propertyExtractor instanceof SortingPropertyExtractor) {
final SortingPropertyExtractor<? super T> sortingPropertyExtractor
= (SortingPropertyExtractor<? super T>)AbstractSimpleContainer.this.propertyExtractor;
if (sortingPropertyExtractor.canSort(propertyDef)) {
final T obj1 = ((BackedItem<T>)item1).getObject();
final T obj2 = ((BackedItem<T>)item2).getObject();
final int diff = sortingPropertyExtractor.sort(propertyDef, obj1, obj2);
return ascending ? diff : -diff;
}
}
// Ask property definition
if (propertyDef.isSortable()) {
final int diff = this.sort(propertyDef, item1, item2);
return ascending ? diff : -diff;
}
// Defer to superclass
return super.compareProperty(propertyId, ascending, item1, item2);
}
// This method exists only to allow the generic parameter <V> to be bound
private <V> int sort(PropertyDef<V> propertyDef, Item item1, Item item2) {
return propertyDef.sort(propertyDef.read(item1), propertyDef.read(item2));
}
}
}
| true |
2ffca7eb71d454ce496aa345f914958b8a1f649a | Java | zhai926/rulai | /rulai-common/src/main/java/com/unicdata/entity/carInfo/UnicdataBrandExample.java | UTF-8 | 24,766 | 2.28125 | 2 | [] | no_license | package com.unicdata.entity.carInfo;
import java.util.ArrayList;
import java.util.List;
public class UnicdataBrandExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public UnicdataBrandExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andBrandIdIsNull() {
addCriterion("brand_id is null");
return (Criteria) this;
}
public Criteria andBrandIdIsNotNull() {
addCriterion("brand_id is not null");
return (Criteria) this;
}
public Criteria andBrandIdEqualTo(Integer value) {
addCriterion("brand_id =", value, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdNotEqualTo(Integer value) {
addCriterion("brand_id <>", value, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdGreaterThan(Integer value) {
addCriterion("brand_id >", value, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdGreaterThanOrEqualTo(Integer value) {
addCriterion("brand_id >=", value, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdLessThan(Integer value) {
addCriterion("brand_id <", value, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdLessThanOrEqualTo(Integer value) {
addCriterion("brand_id <=", value, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdIn(List<Integer> values) {
addCriterion("brand_id in", values, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdNotIn(List<Integer> values) {
addCriterion("brand_id not in", values, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdBetween(Integer value1, Integer value2) {
addCriterion("brand_id between", value1, value2, "brandId");
return (Criteria) this;
}
public Criteria andBrandIdNotBetween(Integer value1, Integer value2) {
addCriterion("brand_id not between", value1, value2, "brandId");
return (Criteria) this;
}
public Criteria andBrandNameIsNull() {
addCriterion("brand_name is null");
return (Criteria) this;
}
public Criteria andBrandNameIsNotNull() {
addCriterion("brand_name is not null");
return (Criteria) this;
}
public Criteria andBrandNameEqualTo(String value) {
addCriterion("brand_name =", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameNotEqualTo(String value) {
addCriterion("brand_name <>", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameGreaterThan(String value) {
addCriterion("brand_name >", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameGreaterThanOrEqualTo(String value) {
addCriterion("brand_name >=", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameLessThan(String value) {
addCriterion("brand_name <", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameLessThanOrEqualTo(String value) {
addCriterion("brand_name <=", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameLike(String value) {
addCriterion("brand_name like", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameNotLike(String value) {
addCriterion("brand_name not like", value, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameIn(List<String> values) {
addCriterion("brand_name in", values, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameNotIn(List<String> values) {
addCriterion("brand_name not in", values, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameBetween(String value1, String value2) {
addCriterion("brand_name between", value1, value2, "brandName");
return (Criteria) this;
}
public Criteria andBrandNameNotBetween(String value1, String value2) {
addCriterion("brand_name not between", value1, value2, "brandName");
return (Criteria) this;
}
public Criteria andBrandAliasIsNull() {
addCriterion("brand_alias is null");
return (Criteria) this;
}
public Criteria andBrandAliasIsNotNull() {
addCriterion("brand_alias is not null");
return (Criteria) this;
}
public Criteria andBrandAliasEqualTo(String value) {
addCriterion("brand_alias =", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasNotEqualTo(String value) {
addCriterion("brand_alias <>", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasGreaterThan(String value) {
addCriterion("brand_alias >", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasGreaterThanOrEqualTo(String value) {
addCriterion("brand_alias >=", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasLessThan(String value) {
addCriterion("brand_alias <", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasLessThanOrEqualTo(String value) {
addCriterion("brand_alias <=", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasLike(String value) {
addCriterion("brand_alias like", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasNotLike(String value) {
addCriterion("brand_alias not like", value, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasIn(List<String> values) {
addCriterion("brand_alias in", values, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasNotIn(List<String> values) {
addCriterion("brand_alias not in", values, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasBetween(String value1, String value2) {
addCriterion("brand_alias between", value1, value2, "brandAlias");
return (Criteria) this;
}
public Criteria andBrandAliasNotBetween(String value1, String value2) {
addCriterion("brand_alias not between", value1, value2, "brandAlias");
return (Criteria) this;
}
public Criteria andNationIsNull() {
addCriterion("nation is null");
return (Criteria) this;
}
public Criteria andNationIsNotNull() {
addCriterion("nation is not null");
return (Criteria) this;
}
public Criteria andNationEqualTo(String value) {
addCriterion("nation =", value, "nation");
return (Criteria) this;
}
public Criteria andNationNotEqualTo(String value) {
addCriterion("nation <>", value, "nation");
return (Criteria) this;
}
public Criteria andNationGreaterThan(String value) {
addCriterion("nation >", value, "nation");
return (Criteria) this;
}
public Criteria andNationGreaterThanOrEqualTo(String value) {
addCriterion("nation >=", value, "nation");
return (Criteria) this;
}
public Criteria andNationLessThan(String value) {
addCriterion("nation <", value, "nation");
return (Criteria) this;
}
public Criteria andNationLessThanOrEqualTo(String value) {
addCriterion("nation <=", value, "nation");
return (Criteria) this;
}
public Criteria andNationLike(String value) {
addCriterion("nation like", value, "nation");
return (Criteria) this;
}
public Criteria andNationNotLike(String value) {
addCriterion("nation not like", value, "nation");
return (Criteria) this;
}
public Criteria andNationIn(List<String> values) {
addCriterion("nation in", values, "nation");
return (Criteria) this;
}
public Criteria andNationNotIn(List<String> values) {
addCriterion("nation not in", values, "nation");
return (Criteria) this;
}
public Criteria andNationBetween(String value1, String value2) {
addCriterion("nation between", value1, value2, "nation");
return (Criteria) this;
}
public Criteria andNationNotBetween(String value1, String value2) {
addCriterion("nation not between", value1, value2, "nation");
return (Criteria) this;
}
public Criteria andPictureIsNull() {
addCriterion("picture is null");
return (Criteria) this;
}
public Criteria andPictureIsNotNull() {
addCriterion("picture is not null");
return (Criteria) this;
}
public Criteria andPictureEqualTo(String value) {
addCriterion("picture =", value, "picture");
return (Criteria) this;
}
public Criteria andPictureNotEqualTo(String value) {
addCriterion("picture <>", value, "picture");
return (Criteria) this;
}
public Criteria andPictureGreaterThan(String value) {
addCriterion("picture >", value, "picture");
return (Criteria) this;
}
public Criteria andPictureGreaterThanOrEqualTo(String value) {
addCriterion("picture >=", value, "picture");
return (Criteria) this;
}
public Criteria andPictureLessThan(String value) {
addCriterion("picture <", value, "picture");
return (Criteria) this;
}
public Criteria andPictureLessThanOrEqualTo(String value) {
addCriterion("picture <=", value, "picture");
return (Criteria) this;
}
public Criteria andPictureLike(String value) {
addCriterion("picture like", value, "picture");
return (Criteria) this;
}
public Criteria andPictureNotLike(String value) {
addCriterion("picture not like", value, "picture");
return (Criteria) this;
}
public Criteria andPictureIn(List<String> values) {
addCriterion("picture in", values, "picture");
return (Criteria) this;
}
public Criteria andPictureNotIn(List<String> values) {
addCriterion("picture not in", values, "picture");
return (Criteria) this;
}
public Criteria andPictureBetween(String value1, String value2) {
addCriterion("picture between", value1, value2, "picture");
return (Criteria) this;
}
public Criteria andPictureNotBetween(String value1, String value2) {
addCriterion("picture not between", value1, value2, "picture");
return (Criteria) this;
}
public Criteria andLetterIsNull() {
addCriterion("letter is null");
return (Criteria) this;
}
public Criteria andLetterIsNotNull() {
addCriterion("letter is not null");
return (Criteria) this;
}
public Criteria andLetterEqualTo(String value) {
addCriterion("letter =", value, "letter");
return (Criteria) this;
}
public Criteria andLetterNotEqualTo(String value) {
addCriterion("letter <>", value, "letter");
return (Criteria) this;
}
public Criteria andLetterGreaterThan(String value) {
addCriterion("letter >", value, "letter");
return (Criteria) this;
}
public Criteria andLetterGreaterThanOrEqualTo(String value) {
addCriterion("letter >=", value, "letter");
return (Criteria) this;
}
public Criteria andLetterLessThan(String value) {
addCriterion("letter <", value, "letter");
return (Criteria) this;
}
public Criteria andLetterLessThanOrEqualTo(String value) {
addCriterion("letter <=", value, "letter");
return (Criteria) this;
}
public Criteria andLetterLike(String value) {
addCriterion("letter like", value, "letter");
return (Criteria) this;
}
public Criteria andLetterNotLike(String value) {
addCriterion("letter not like", value, "letter");
return (Criteria) this;
}
public Criteria andLetterIn(List<String> values) {
addCriterion("letter in", values, "letter");
return (Criteria) this;
}
public Criteria andLetterNotIn(List<String> values) {
addCriterion("letter not in", values, "letter");
return (Criteria) this;
}
public Criteria andLetterBetween(String value1, String value2) {
addCriterion("letter between", value1, value2, "letter");
return (Criteria) this;
}
public Criteria andLetterNotBetween(String value1, String value2) {
addCriterion("letter not between", value1, value2, "letter");
return (Criteria) this;
}
public Criteria andRankIsNull() {
addCriterion("rank is null");
return (Criteria) this;
}
public Criteria andRankIsNotNull() {
addCriterion("rank is not null");
return (Criteria) this;
}
public Criteria andRankEqualTo(Byte value) {
addCriterion("rank =", value, "rank");
return (Criteria) this;
}
public Criteria andRankNotEqualTo(Byte value) {
addCriterion("rank <>", value, "rank");
return (Criteria) this;
}
public Criteria andRankGreaterThan(Byte value) {
addCriterion("rank >", value, "rank");
return (Criteria) this;
}
public Criteria andRankGreaterThanOrEqualTo(Byte value) {
addCriterion("rank >=", value, "rank");
return (Criteria) this;
}
public Criteria andRankLessThan(Byte value) {
addCriterion("rank <", value, "rank");
return (Criteria) this;
}
public Criteria andRankLessThanOrEqualTo(Byte value) {
addCriterion("rank <=", value, "rank");
return (Criteria) this;
}
public Criteria andRankIn(List<Byte> values) {
addCriterion("rank in", values, "rank");
return (Criteria) this;
}
public Criteria andRankNotIn(List<Byte> values) {
addCriterion("rank not in", values, "rank");
return (Criteria) this;
}
public Criteria andRankBetween(Byte value1, Byte value2) {
addCriterion("rank between", value1, value2, "rank");
return (Criteria) this;
}
public Criteria andRankNotBetween(Byte value1, Byte value2) {
addCriterion("rank not between", value1, value2, "rank");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("status is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("status is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(Byte value) {
addCriterion("status =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(Byte value) {
addCriterion("status <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(Byte value) {
addCriterion("status >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("status >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(Byte value) {
addCriterion("status <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(Byte value) {
addCriterion("status <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<Byte> values) {
addCriterion("status in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<Byte> values) {
addCriterion("status not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(Byte value1, Byte value2) {
addCriterion("status between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(Byte value1, Byte value2) {
addCriterion("status not between", value1, value2, "status");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | true |
9eb936783e08fc8368c833cc88e213bdf099d153 | Java | neverendzh/NeverEndBlog | /zcjblog/src/main/java/com/neverend/blog/mapper/ArticleMapper.java | UTF-8 | 1,656 | 1.867188 | 2 | [] | no_license | package com.neverend.blog.mapper;
import com.neverend.blog.entity.Article;
import com.neverend.blog.entity.ArticleExample;
import com.neverend.blog.entity.ArticleWithBLOBs;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ArticleMapper {
long countByExample(ArticleExample example);
int deleteByExample(ArticleExample example);
int deleteByPrimaryKey(String articleId);
int insert(ArticleWithBLOBs record);
int insertSelective(ArticleWithBLOBs record);
List<ArticleWithBLOBs> selectByExampleWithBLOBs(ArticleExample example);
List<Article> selectByExample(ArticleExample example);
ArticleWithBLOBs selectByPrimaryKey(String articleId);
int updateByExampleSelective(@Param("record") ArticleWithBLOBs record, @Param("example") ArticleExample example);
int updateByExampleWithBLOBs(@Param("record") ArticleWithBLOBs record, @Param("example") ArticleExample example);
int updateByExample(@Param("record") Article record, @Param("example") ArticleExample example);
int updateByPrimaryKeySelective(ArticleWithBLOBs record);
int updateByPrimaryKeyWithBLOBs(ArticleWithBLOBs record);
int updateByPrimaryKey(Article record);
List<Article> getArtilceFeiL(@Param("artilceid") String artilceid,@Param("state") String state,@Param("array")String[] array);
List<Article> selectActilcNameLike(@Param("list") List<String> list,@Param("state") String state);
List<Article> getArtilceFeiLon(@Param("artilceid") String artilceid,@Param("state") String state);
List<Article> selectArticleHort();
} | true |
9614bf59907b4a8d9584bdb0484846a33428ba6a | Java | Ostboa16/MannschaftsVerwalter | /src/data/Spieler.java | UTF-8 | 1,098 | 3.015625 | 3 | [] | no_license | package data;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Spieler implements Serializable {
private String name;
private int rueckennummer;
private String position;
public Spieler(String name, int rueckennummer, String position) {
this.name = name;
this.rueckennummer = rueckennummer;
this.position = position;
}
public Spieler(ResultSet rs) throws SQLException {
this.name = rs.getString("name");
this.rueckennummer = rs.getInt("rueckennummer");
this.position = rs.getString("position");
}
public String getName() {
return name;
}
public int getRueckennummer() {
return rueckennummer;
}
public String getPosition() {
return position;
}
public void setRueckennummer(int rueckennummer) {
this.rueckennummer = rueckennummer;
}
@Override
public String toString() {
return "Spieler{" + "name=" + name + ", rueckennummer=" + rueckennummer + ", position=" + position + '}';
}
}
| true |
6e41ed0e3f6b47f146e8720d1dcddd045e644520 | Java | samaj89/exercises | /src/day11/StackNode.java | UTF-8 | 321 | 3.125 | 3 | [] | no_license | public class StackNode<N extends Number> {
private N value;
private StackNode next;
public StackNode(N value) {
this.value = value;
this.next = null;
}
public N getValue() {
return value;
}
public StackNode getNext() {
return next;
}
public void setNext(StackNode next) {
this.next = next;
}
} | true |
5e6c778e94c89c2b0cb3587289a0a0cfdde8c1de | Java | ggam/java9-container | /impl/src/main/java/eu/ggam/container/impl/servletcontainer/container/ContainerHttpResponseImpl.java | UTF-8 | 2,130 | 2.484375 | 2 | [] | no_license | package eu.ggam.container.impl.servletcontainer.container;
import eu.ggam.container.api.http.HttpResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Guillermo González de Agüero
*/
public class ContainerHttpResponseImpl implements HttpResponse {
private int status = 200;
private Map<String, List<String>> headers = new HashMap<>();
private final ByteArrayOutputStream output;
private boolean completed;
public ContainerHttpResponseImpl() {
this.output = new ResponseOutputStream();
}
@Override
public void setHeaders(Map<String, List<String>> headers) {
if (completed) {
throw new IllegalStateException("Response already finished");
}
this.headers = headers;
}
@Override
public Map<String, List<String>> getHeaders() {
return headers;
}
@Override
public ByteArrayOutputStream getOutputStream() {
if (completed) {
throw new IllegalStateException("Response already finished");
}
return output;
}
@Override
public void setStatus(int status) {
if (completed) {
throw new IllegalStateException("Response already finished");
}
this.status = status;
}
@Override
public int getStatus() {
return status;
}
private class ResponseOutputStream extends ByteArrayOutputStream {
@Override
public void write(byte[] b) throws IOException {
checkNotCompleted();
super.write(b);
}
@Override
public synchronized void write(byte[] b, int off, int len) {
checkNotCompleted();
super.write(b, off, len);
}
@Override
public synchronized void write(int b) {
checkNotCompleted();
super.write(b);
}
private void checkNotCompleted() {
if (completed) {
throw new IllegalStateException("Response already finished");
}
}
}
}
| true |
55ee1de54256739a7a1da2b8264775756152412f | Java | tobiasg28/Uni-Zeugs-TSD | /src/backend/BackendLocator.java | UTF-8 | 596 | 2.375 | 2 | [] | no_license | package backend;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import notification.Backend;
import swag.Constants;
public class BackendLocator {
/**
* Get the backend instance running on the specified host.
**/
public static Backend getBackendByHost(String host) throws RemoteException, NotBoundException {
Registry registry = LocateRegistry.getRegistry(host, Constants.BACKEND_RMI_PORT);
Backend backend = (Backend)registry.lookup(Constants.BACKEND_RMI_NAME);
return backend;
}
}
| true |
69587a3f5bdf70c3c3f04ab0c700cf3c96675e5a | Java | AnGo84/TableReader | /src/main/java/com/tablereader/fx/TextFieldNumberListener.java | UTF-8 | 757 | 2.71875 | 3 | [] | no_license | package com.tablereader.fx;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TextField;
import java.awt.*;
public class TextFieldNumberListener implements ChangeListener<String> {
private TextField textField;
public TextFieldNumberListener(TextField textField) {
this.textField = textField;
}
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue != null && !newValue.equals("")) {
if (!newValue.matches("\\d*")) {
Toolkit.getDefaultToolkit().beep();
textField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
}
}
| true |
724437a60fc3c596514e8d7eafa85d34cae55407 | Java | dangzhicairang/rxjava | /src/main/java/com/xsn/chapter2/Main.java | UTF-8 | 2,976 | 3.171875 | 3 | [] | no_license | package com.xsn.chapter2;
import io.reactivex.rxjava3.core.Observable;
import java.util.ArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) throws InterruptedException {
// create();
// just();
// fromFuture();
// defer();
interval();
// timer();
// repeat();
// repeatWhen();
// repeatUtil();
}
static void create() {
Observable.create(e -> {
// 检查观察者的订阅状态
if (!e.isDisposed()) {
IntStream.rangeClosed(0, 10)
.forEach(i -> e.onNext(i));
e.onComplete();
}
}).subscribe(t -> System.out.println(t));
}
static void just() {
Observable.just(1, 2).subscribe(t -> System.out.println(t));
}
static void from() {
Observable.fromArray("1", "2").subscribe(t -> System.out.println(t));
Observable.fromIterable(
new ArrayList<Integer>() {
{
add(1);
add(2);
}
}
).subscribe(t -> System.out.println(t));
}
static void fromFuture() {
FutureTask future = new FutureTask(() -> {
TimeUnit.SECONDS.sleep(3);
return "done";
});
new Thread(future).start();
// 2s 超时
Observable.fromFuture(future, 2, TimeUnit.SECONDS)
.subscribe(t -> System.out.println(t));
}
static void defer() {
Observable.defer(() -> {
return Observable.just("test");
}).subscribe(t -> System.out.println(t));
}
static void interval() throws InterruptedException {
Observable.interval(1, TimeUnit.SECONDS)
.subscribe(t -> System.out.println(t));
TimeUnit.SECONDS.sleep(5);
}
static void timer() {
Observable.timer(2, TimeUnit.SECONDS)
.subscribe(t -> System.out.println(t));
}
static void repeat() {
Observable.just("test")
.repeat(2)
.subscribe(t -> System.out.println(t));
}
static void repeatWhen() throws InterruptedException {
Observable.just("test")
.repeatWhen(o -> {
return Observable.timer(3, TimeUnit.SECONDS);
})
.subscribe(t -> System.out.println(t));
TimeUnit.SECONDS.sleep(5);
}
static void repeatUtil() {
AtomicInteger i = new AtomicInteger(0);
Observable.just("test")
.repeatUntil(() -> {
return i.incrementAndGet() > 5;
}).subscribe(t -> System.out.println(t));
}
}
| true |
5736a2daadc2375b75fc0965f19f9b1da82911a6 | Java | resel143/KotlinBasics | /when.java | UTF-8 | 139 | 2.5625 | 3 | [] | no_license | var fishName = "apurva"
when(fishName.length){
0-> println("error");
in 3..12-> println("Good")
else-> println("Okya");
}
| true |
25ec02787aefc69921b35a5b5c57b5dcc925c4dc | Java | lkk-cxks/lkk1 | /github3/src/github3/pratice17.java | WINDOWS-1252 | 1,143 | 3.0625 | 3 | [] | no_license | package github3;
import java.util.Scanner;
public class pratice17 {
private String name;
private static long score;
public long getScore() {
return score;
}
public void setScore(long score) {
this.score=score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String toString() {
return this.name;
}
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
int sNum=input.nextInt();
int i,j;
pratice17 b[]= new pratice17[sNum];
for (i=0;i<b.length;i++) {
b[i]=new pratice17();
String name=input.next();
b[i].setName(name);
long chengji=input.nextLong();
b[i].setScore(score);
}
for (i=0;i<b.length;i++) {
for (j=i+1;j<b.length;j++) {
if(b[i].getScore()<b[j].getScore()) {
pratice17 s=new pratice17();
s=b[i];
b[i]=b[j];
b[j]=s;
}
}
}
for (i=0;i++<b.length;i++) {
System.out.println(b[i].getName() + "ijɼ:" + b[i].getScore());
}
}
}
| true |
bc74276daed16c3a2f5459bb801190cb34bb339c | Java | DonSantiagoS/Pong_Video_Juego | /Pong/src/aplicacion/Flash.java | UTF-8 | 2,226 | 3.5 | 4 | [] | no_license | package aplicacion;
/**
* ------------------------------------------------------------------------
* ------------------------ PONG ------------------------------------------
* ------------------------------------------------------------------------
*
* CLASE: Flash, Sorpresa la cual acelera la pelota hasta que el jugador contrario
la devuelva o la deje ir. Luego de eso seguirá teniendo la velocidad que
tenía antes de ser acelerada.
*
* @author: Santiago Buitrago
* @author: Brayan Macias
*
* @version 4.5 Final
*/
public class Flash extends Sorpresa{
private Jugador ultimoGolpeOriginal;
private Pelota pelotaFlash;
/**
Constructor Flash, Sorpresa la cual acelera la pelota hasta que el jugador contrario
la devuelva o la deje ir. Luego de eso seguirá teniendo la velocidad que
tenía antes de ser acelerada.
@param pocisionX: Pocision x en la cual se creara la Sorpresa
@param pocisionY: Pocision y en la cual se creara la Sorpresa
@param ancho: Corresponde a la medida de ancho de la sorpresa
@param ancho: Corresponde a la medida de alto de la sorpresa
*/
public Flash(int pocisionX, int pocisionY,int ancho, int alto){
super(pocisionX,pocisionY, ancho, alto);
ultimoGolpeOriginal=null;
}
/**
Encargado de realizar el comportamiento correcto para esta clase, ya que
es una sorpresa que realiza diferente accion o se comporta diferente a las
otras sorpresas, en este caso realiza su funcion vital
@param jugador: Jugador quien tomo la Sopresa
@param pelota: Pelota que tomo la Sorpresa
*/
@Override
public void comportamiento(Jugador jugador,Pelota pelota){
ultimoGolpeOriginal= pelota.ultimoGolpe();
while (pelota.ultimoGolpe()==ultimoGolpeOriginal){
pelota.setVelocidadX(pelota.getVelocidadX()+1);
pelota.setVelocidadY(pelota.getVelocidadY()+1);
pelotaFlash= pelota;
}
}
/**
Encargado de poner a correr el tiempo del poder, correspondiente
a este tipo de sorpresa
@Override
public void iniciarPoder(){
super.setDuracionPoder(300);
}*/
@Override
public void acabo(){
if (!(pelotaFlash.ultimoGolpe().equals(ultimoGolpeOriginal))){
pelotaFlash.setVelocidadX(1);
pelotaFlash.setVelocidadY(1);
}
else{
iniciarPoder();
}
}
} | true |
b617c6bfb02c59e4bcda98a897a515e90aab45e8 | Java | LucaGiamattei/ProgettoPSSS | /Codice/WebAppSmartLearning/src/dataLayer/pagamento/controller/ControllerPagamentoDB.java | UTF-8 | 6,630 | 2.234375 | 2 | [] | no_license | package dataLayer.pagamento.controller;
import java.sql.ResultSet;
import java.sql.Types;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Hashtable;
import java.util.Vector;
import com.mysql.jdbc.CallableStatement;
import java.sql.Connection;
import dataLayer.connectorManager.DBConnectionManager;
import dataLayer.pagamento.API_PagamentoDB;
import dataLayer.pagamento.entities.PagamentoDB;
import utilities.StateResult;
import utilities.idFasciaOraria;
import utilities.idPagamento;
import utilities.idUser;
public class ControllerPagamentoDB implements API_PagamentoDB{
@Override
public StateResult getTokenByUtente(PagamentoDB pagamentoUtente) {
// TODO Auto-generated method stub
String [] fieldsToSelect = {"*"};
Hashtable<String,String> conditionsFildsToValues = new Hashtable<String, String>();
conditionsFildsToValues.put("Utente_idUtente", pagamentoUtente.getId().toString());
conditionsFildsToValues.put("FasciaOraria_idFasciaOraria", pagamentoUtente.getIdFascia().toString());
ResultSet result;
try {
Connection conn = null;
result = DBConnectionManager.SelectEntryDB("Pagamento", fieldsToSelect, conditionsFildsToValues, conn);
int numOfRows = 0;
while (result.next()) {
numOfRows++;
if(numOfRows==1 ) {
pagamentoUtente.setToken(result.getString("TOKEN"));
}
}
//if(conn!=null) {conn.close();}
switch(numOfRows) {
case 1:
return StateResult.VALID;
default:
return StateResult.NOVALID;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return StateResult.DBPROBLEM;
}
}
@Override
public StateResult genAndGetTokens(idFasciaOraria idFasciaOraria, Vector<PagamentoDB>payments){
Connection conn;
try {
conn = DBConnectionManager.getConnection();
conn.setAutoCommit(false);
String query = "{CALL genTokens(?)}";
CallableStatement stmt = (CallableStatement) conn.prepareCall(query);
stmt.setInt(1, idFasciaOraria.getId());
ResultSet result = stmt.executeQuery();
int cont = 0;
while (result.next()) {
PagamentoDB pagamento = new PagamentoDB(idFasciaOraria, new idUser(result.getInt("Utente_idUtente")), result.getString("TOKEN"));
payments.add(pagamento);
cont++;
}
conn.commit();
//if(conn!=null) {conn.close();}
if(cont>0) {
return StateResult.UPDATED;
}else {
return StateResult.NOUPDATED;
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return StateResult.DBPROBLEM;
}
}
@Override
public StateResult subscribePayment(idUser idUser, idFasciaOraria idFasciaOraria, idPagamento idPagamento) {
// TODO Auto-generated method stub
Hashtable<String,String> addFildsToValues = new Hashtable<String, String>();
addFildsToValues.put("Utente_idUtente", idUser.toString());
addFildsToValues.put("FasciaOraria_idFasciaOraria", idFasciaOraria.toString());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime now = LocalDateTime.now();
addFildsToValues.put("DataPagamento", dtf.format(now));
//AGGIUNGERE CONTROLLO DATA
try {
Integer r = DBConnectionManager.createNewEntryDB("Pagamento", addFildsToValues, true);
if (r>0) {
idPagamento.setId(r);
return StateResult.CREATED;
}else {
return StateResult.NOCHANGES;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return StateResult.DBPROBLEM;
}
}
@Override
public StateResult verifyUserHasPayed(idUser idUser, idFasciaOraria idFasciaOraria) {
// TODO Auto-generated method stub
String [] fieldsToSelect = {"*"};
Hashtable<String,String> conditionsFildsToValues = new Hashtable<String, String>();
conditionsFildsToValues.put("Utente_idUtente", idUser.toString());
conditionsFildsToValues.put("FasciaOraria_idFasciaOraria", idFasciaOraria.toString());
ResultSet result;
try {
Connection conn = null;
result = DBConnectionManager.SelectEntryDB("Pagamento", fieldsToSelect, conditionsFildsToValues, conn);
int numOfRows = 0;
while (result.next()) {
numOfRows++;
}
//if(conn!=null) {conn.close();}
switch(numOfRows) {
case 1:
return StateResult.VALID;
default:
return StateResult.NOVALID;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return StateResult.DBPROBLEM;
}
}
@Override
public StateResult getUsersPayedLesson(idFasciaOraria idFasciaOraria, Vector<idUser> users) {
// TODO Auto-generated method stub
String [] fieldsToSelect = {"Utente_idUtente"};
Hashtable<String,String> conditionsFildsToValues = new Hashtable<String, String>();
conditionsFildsToValues.put("FasciaOraria_idFasciaOraria", idFasciaOraria.toString());
ResultSet result;
try {
Connection conn = null;
result = DBConnectionManager.SelectEntryDB("Pagamento", fieldsToSelect, conditionsFildsToValues, conn);
int numOfRows = 0;
while (result.next()) {
numOfRows++;
users.add(new idUser(result.getInt("Utente_idUtente")));
}
//if(conn!=null) {conn.close();}
if(numOfRows>0) {
return StateResult.VALID;
}else {
return StateResult.NOVALID;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return StateResult.DBPROBLEM;
}
}
public StateResult thereAreUsersPayedLesson(idFasciaOraria idFasciaOraria) {
// TODO Auto-generated method stub
String [] fieldsToSelect = {"Utente_idUtente"};
Hashtable<String,String> conditionsFildsToValues = new Hashtable<String, String>();
conditionsFildsToValues.put("FasciaOraria_idFasciaOraria", idFasciaOraria.toString());
ResultSet result;
try {
Connection conn = null;
result = DBConnectionManager.SelectEntryDB("Pagamento", fieldsToSelect, conditionsFildsToValues, conn);
int numOfRows = 0;
while (result.next()) {
numOfRows++;
}
//if(conn!=null) {conn.close();}
if(numOfRows>0) {
System.out.println("thereAreUsersPayedLesson:StateResult.VALID");
return StateResult.VALID;
}else {
return StateResult.NOVALID;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return StateResult.DBPROBLEM;
}
}
}
| true |
96d16f401e04cab681ebc4546ea30ce9b62c3f0b | Java | aisjac/Home_Activity | /app/src/main/java/com/example/home_activity/AddData.java | UTF-8 | 1,490 | 2.28125 | 2 | [] | no_license | package com.example.home_activity;
import java.io.Serializable;
public class AddData implements Serializable {
private String full_Name;
private String father_Name;
private String mother_Name;
private String nid_Number;
private String address_loc;
public AddData(){
//empty constructor
}
public AddData(String full_Name, String father_Name, String mother_Name, String nid_Number, String address_loc) {
this.full_Name = full_Name;
this.father_Name = father_Name;
this.mother_Name = mother_Name;
this.nid_Number = nid_Number;
this.address_loc = address_loc;
}
public String getFull_Name() {
return full_Name;
}
public void setFull_Name(String full_Name) {
this.full_Name = full_Name;
}
public String getFather_Name() {
return father_Name;
}
public void setFather_Name(String father_Name) {
this.father_Name = father_Name;
}
public String getMother_Name() {
return mother_Name;
}
public void setMother_Name(String mother_Name) {
this.mother_Name = mother_Name;
}
public String getNid_Number() {
return nid_Number;
}
public void setNid_Number(String nid_Number) {
this.nid_Number = nid_Number;
}
public String getAddress_loc() {
return address_loc;
}
public void setAddress_loc(String address_loc) {
this.address_loc = address_loc;
}
}
| true |
300dcc4662fd2bb2909c2b87f1d6bfad144fddb4 | Java | ystwei/A13 | /src/main/java/com/weikun/pojo/Cou.java | UTF-8 | 1,477 | 2.34375 | 2 | [] | no_license | package com.weikun.pojo;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Administrator on 2016/11/8.
*/
@Entity()
@Table(name = "cou", catalog = "test")
public class Cou {
private int cid;
private String cname;
private Set<Pro> pros=new HashSet<Pro>();
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
@Column(name = "cid", nullable = false)
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
@Basic
@Column(name = "cname", nullable = false, length = 10)
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cou cou = (Cou) o;
if (cid != cou.cid) return false;
if (cname != null ? !cname.equals(cou.cname) : cou.cname != null) return false;
return true;
}
@Override
public int hashCode() {
int result = cid;
result = 31 * result + (cname != null ? cname.hashCode() : 0);
return result;
}
@OneToMany(mappedBy = "cou",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
public Set<Pro> getPros() {
return pros;
}
public void setPros(Set<Pro> pros) {
this.pros = pros;
}
}
| true |
4792e08df4698ed6476e5e3676b365317b22fd2e | Java | yarivg/WaitForIt | /app/src/main/java/company/wfi/com/waitforit/gameAct.java | UTF-8 | 11,434 | 1.828125 | 2 | [] | no_license | package company.wfi.com.waitforit;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.LoginFilter;
import android.util.Config;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class gameAct extends Activity implements View.OnClickListener {
boolean pause = true;
private int topMarginTimer,heightTimer = 80;
public static String[] games = new String[9];
public static WebView mainView;
public static boolean firstJS = true;
public static String lastGameUrl = "";
private Object activityResultKeepRunning;
private Object keepRunning;
public static int timeInSec = 0;
private TextView timer;
private ImageButton skipBtn,stopBtn,exitBtn;
public static boolean loadNewGame = false;
private static final int toMINUTE = 1000;
public class MyInterface {
public String $points;
public String $totalTime;
public Context context;
@JavascriptInterface
public void getGameInfo(String $points,String $totalTime){
if(firstJS || !lastGameUrl.equals(playlistInfo.mPlaylist.get(playlistInfo.indexInList).getUrl())) {
Log.d("url", "JS ecexuted.");
firstJS = false;
lastGameUrl = playlistInfo.mPlaylist.get(playlistInfo.indexInList).getUrl();
this.$points = $points;
this.$totalTime = $totalTime;
ratingAct.total_score = $points;
ratingAct.total_time = $totalTime;
ratingAct.timeInSec = timeInSec;
startActivity(new Intent(getApplicationContext(), ratingAct.class));
//context.startActivity(new Intent(context.getApplicationContext(),ratingAct.class));
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d("url", "onCreate");
getIntent().putExtra("loadUrlTimeoutValue", 170000);
setContentView(R.layout.gamepage);
timer = (TextView)findViewById(R.id.timertxt);
Typeface fontTimer = Typeface.createFromAsset(getAssets(),"fonts/Ailerons.ttf");
timer.setTypeface(fontTimer);
stopBtn = (ImageButton)findViewById(R.id.pausegame);
skipBtn = (ImageButton)findViewById(R.id.skipgame);
exitBtn = (ImageButton)findViewById(R.id.exitplalistbtn);
stopBtn.setOnClickListener(this);
skipBtn.setOnClickListener(this);
exitBtn.setOnClickListener(this);
StartThisClock();
gameAct.this.
runOnUiThread(new Runnable() {
@Override
public void run () {
mainView = (WebView) findViewById(R.id.mainView);
mainView.getSettings().setJavaScriptEnabled(true);
mainView.setBackgroundColor(Color.WHITE);
mainView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//Log.d("url", url);
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//Log.d("url", "Page started");
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
//Log.d("url", description);
}
});
mainView.setWebChromeClient(new WebChromeClient());
mainView.getSettings().setDomStorageEnabled(true);
mainView.getSettings().setSupportMultipleWindows(true);
mainView.setLayerType(WebView.LAYER_TYPE_HARDWARE, null);
MyInterface myInterface = new MyInterface();
myInterface.context = getApplicationContext();
mainView.addJavascriptInterface(myInterface, "myInterface");
}
}
);
MakePlayerFullScreenPortrait();
}
private void StartThisClock() {
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
timer.setText(myClock.getTimeText());
}
});
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
private void gameSkipped(){
Log.d("gameAct","gameSkipped");
firstJS = false;
lastGameUrl = playlistInfo.mPlaylist.get(playlistInfo.indexInList).getUrl();
ratingAct.total_score = "0";
ratingAct.total_time = "0";
ratingAct.timeInSec = timeInSec;
startActivity(new Intent(getApplicationContext(), ratingAct.class));
}
private void MakePlayerFullScreenPortrait(){
FrameLayout.LayoutParams myLayout = (FrameLayout.LayoutParams)mainView.getLayoutParams();
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) timer.getLayoutParams();
topMarginTimer = lp.topMargin;
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
float density = getResources().getDisplayMetrics().density;
switch (getResources().getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_HIGH:
heightTimer = (int) (93 * density / 1.5);
break;
case DisplayMetrics.DENSITY_XHIGH:
heightTimer = 130;
break;
case DisplayMetrics.DENSITY_XXHIGH:
heightTimer = (int) (98 * density / 1.5);
break;
case DisplayMetrics.DENSITY_560:
case DisplayMetrics.DENSITY_XXXHIGH:
heightTimer = (int) (100 * density / 1.5);
break;
default:
break;
}
myLayout.height = height - ((heightTimer + topMarginTimer));
myLayout.gravity = Gravity.BOTTOM;
mainView.setLayoutParams(myLayout);
}
@Override
public void onBackPressed() {
PauseGame();
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exiting Playlist")
.setMessage("Are you sure you want to exit the playlist?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
lastGameUrl = "";
startActivity(new Intent(getApplicationContext(), waitingcompleteAct.class));
}
})
.setNegativeButton("No", null)
.show();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.pausegame:
if(pause) {
PauseGame();
}
else {
ResumeGame();
}
break;
case R.id.exitplalistbtn:
onBackPressed();
break;
case R.id.skipgame:
gameSkipped();
break;
}
}
private void PauseGame() {
mainView.onPause();
stopBtn.setImageResource(R.drawable.resumegame);
pause = false;
}
private void ResumeGame() {
mainView.onResume();
stopBtn.setImageResource(R.drawable.finalstop);
pause = true;
}
@Override
protected void onPause() {
super.onPause();
PauseGame();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
if(loadNewGame){
String currentUrl = playlistInfo.mPlaylist.get(playlistInfo.indexInList).getUrl();
mainView.loadUrl(currentUrl);
loadNewGame = false;
mainView.onResume();
stopBtn.setImageResource(R.drawable.finalstop);
pause = true;
}
Log.d("testURl", "onStart()");
//games[0] = "https://googledrive.com/host/0ByndIaCDcs86ekRjNVRLT1lySUE/index.html";//pupe down!
// games[1] = "https://googledrive.com/host/0ByndIaCDcs86TkJzcVBoM2h4dHc/index.html";//ninja!
// games[2] = "https://googledrive.com/host/0ByndIaCDcs86U29Wam1NY091azg/index.html";//pong catchup!
// games[3] = "https://googledrive.com/host/0ByndIaCDcs86RXUxaEZNYjF2enc/index.html";//monster touch!
// games[4] = "https://googledrive.com/host/0ByndIaCDcs86V3lhZXNUM0dXLUU/index.html";//stability!
// games[5] = "https://googledrive.com/host/0ByndIaCDcs86R0p6LURMdHY1VjQ/index.html";//colors!
// games[6] = "https://googledrive.com/host/0ByndIaCDcs86azZuejUwM0dqTGM/index.html";//cars!
// games[7] = "https://googledrive.com/host/0ByndIaCDcs86eXNUcTFMSkFPb0U/index.html";//trangles!
// games[8] = "https://d8b923084546aa2ae0cecaf4ba13d7273dc0556f.googledrive.com/host/0ByndIaCDcs86SHFkRDRzSkFOOUk/index.html";//apple black and red!
//mainView.loadUrl("https://googledrive.com/host/0ByndIaCDcs86RXUxaEZNYjF2enc/index.html");
MakePlayerFullScreenPortrait();
}
@Override
protected void onDestroy() {
super.onDestroy();
//finish();
Log.d("url", "onDestroy");
}
public Object onMessage(String id, Object data) {
//Log.d("gameAct", "onMessage(" + id + "," + data + ")");
mainView.reload();
if ("exit".equals(id)) {
super.finish();
}
return null;
}
}
| true |
8817bba65bc542d53b669574625ec75fe0623d11 | Java | uniqraft/murder | /src/net/minecraftmurder/main/Spawn.java | UTF-8 | 1,254 | 2.765625 | 3 | [] | no_license | package net.minecraftmurder.main;
import java.util.Arrays;
import java.util.List;
import net.minecraftmurder.tools.ChatContext;
import net.minecraftmurder.tools.Tools;
import org.bukkit.Location;
public class Spawn {
public static final List<String> TYPES = Arrays.asList("player", "scrap");
private Location location;
private String type;
public Spawn (Location location, String type) {
this.location = location;
if (location == null)
throw new NullPointerException("Spawn location is null");
if (TYPES.contains(type))
this.type = type;
else
Tools.sendMessageAll(ChatContext.COLOR_WARNING + type + " is not a valid type for a spawn.");
}
public String getType () {
return type;
}
public Location getLocation () {
return location;
}
@Override
public String toString() {
return type + "*" + Tools.locationToString(location);
}
public static String spawnToString (Spawn spawn) {
return spawn.toString();
}
public static Spawn stringToSpawn (String spawn) {
try {
String[] split = spawn.split("\\*");
String type = split[0];
Location location = Tools.stringToLocation (split[1]);
return new Spawn (location, type);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
} | true |
3d5ace1136e5ff0606e5dd9a8ebf46ef2d4f71a9 | Java | AbsolutelySaurabh/Vendor | /app/src/main/java/com/appsomniac/swagger/data/viewHolder/CompletedBookingsViewHolder.java | UTF-8 | 1,404 | 2 | 2 | [] | no_license | package com.appsomniac.swagger.data.viewHolder;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import com.appsomniac.swagger.R;
import com.appsomniac.swagger.data.model.Bookings.Bookings;
import java.util.ArrayList;
/**
* Created by absolutelysaurabh on 22/12/17.
*/
public class CompletedBookingsViewHolder extends RecyclerView.ViewHolder {
public TextView guest_name;
public TextView date;
public TextView time;
public TextView amount;
public TextView feedback;
private Context context;
public CompletedBookingsViewHolder(LayoutInflater from, ViewGroup viewGroup, int position, ArrayList<Bookings> completedBookingsList, final Context context) {
super(from.inflate(R.layout.item_completed_bookings, viewGroup, false));
this.context = context;
//this.tvTitle = itemView.findViewById(R.id.media_title);
this.guest_name = itemView.findViewById(R.id.completed_bookings_guest_name);
this.date = itemView.findViewById(R.id.completed_bookings_date);
this.time = itemView.findViewById(R.id.completed_bookings_time);
this.amount = itemView.findViewById(R.id.completed_bookings_amount_collected);
this.feedback = itemView.findViewById(R.id.completed_bookings_feedback);
}
}
| true |
54711a3ad04ff815484e3c9452de835fe1b94b95 | Java | esusrecifepegovbr/hapi-fhir-server-cadsus | /src/main/java/org/hl7/fhir/valueset/Identifier.java | UTF-8 | 238 | 1.695313 | 2 | [
"Apache-2.0"
] | permissive | package org.hl7.fhir.valueset;
public class Identifier {
public static enum value {
DL,
PPN,
BRN,
MR,
MCN,
EN,
TAX,
HC,
NIIP,
PRN,
MD,
DR,
ACSN,
UDI,
SNO,
SB,
PLAC,
FILL,
JHN
}
}
| true |
2012eda1f182268e747e02756d8cbb015640cfc2 | Java | sunjava2006/1904 | /spring_base/aop_demo/src/main/java/com/wangrui/spring/aop/demo/bean/Flyman.java | UTF-8 | 376 | 2.09375 | 2 | [] | no_license | package com.wangrui.spring.aop.demo.bean;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Flyman {
@DeclareParents(value="com.wangrui.spring.aop.demo.bean.Human",
defaultImpl = com.wangrui.spring.aop.demo.bean.Bird.class)
Flyable flyman;
}
| true |
13e028d0bbdf4c90d0a4d41a27af8d736679c623 | Java | RabinThapa1998/MeroWallet-Minor1 | /app/src/main/java/com/example/merowalletv11/StatisticsActivity.java | UTF-8 | 12,311 | 1.96875 | 2 | [] | no_license | package com.example.merowalletv11;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Toast;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
import java.util.Calendar;
public class StatisticsActivity extends AppCompatActivity {
private BarChart mChart;
LineChart mpLineChart;
float barWidth;
float barSpace;
float groupSpace;
private final int orange = 0xFFE24444;
private final int darkGreen = 0xFF49D37A;
DatabaseHelper MwDb;
public static String username;
public static String[] categoryArrayBarGraph = new String[50];
public static double[] cashExpenseArray = new double[50];
public static double[] cardExpenseArray = new double[50];
public static double[] cardExpenseLineChart = new double[50];
public static double[] cashExpenseLineChart = new double[50];
private static String dayString;
private static String monthString;
private static String yearString;
public static int thisDay;
public static int thisMonth;
public static int thisYear;
public static String retrievedYear;
public static String retrievedMonth;
public static String retrievedDay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Statistics");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
MwDb= new DatabaseHelper(this);
username = LoginActivity.throwUsername();
retrievedDay = "";
retrievedMonth = "";
retrievedYear = "";
Calendar cal = Calendar.getInstance();
int year1 = cal.get(Calendar.YEAR);
int month1 = cal.get(Calendar.MONTH);
int day1 = cal.get(Calendar.DAY_OF_MONTH);
month1++;
thisMonth =month1;
thisYear=year1;
thisDay= day1;
yearString = "" + year1;
if(thisDay<10){
dayString = "0"+thisDay;
}
else{
dayString = ""+thisDay;
}
if(thisMonth<10){
monthString = "0"+thisMonth;
}
else{
monthString = ""+thisMonth;
}
String date= year1 + "-" + monthString + "-" + dayString;
categoryArrayBarGraph = MainActivity.retCategoryList();
/*for(int i=0;i<14;i++) {
categoryArrayBarGraph[i] = "0";
}*/
for(int i=0;i<14;i++){
cardExpenseArray[i] = 0;
cashExpenseArray[i] = 0;
}
getDataForBarGraph();
barWidth = 0.35f;
barSpace = 0f;
groupSpace = 0.3f;
mChart = (BarChart) findViewById(R.id.chart1);
mChart.setDescription(null);
mChart.setPinchZoom(false);
mChart.setScaleEnabled(false);
mChart.setDrawGridBackground(false);
// mChart.setFitBars(true);
mChart.setDrawBarShadow(false);
ArrayList xVals = new ArrayList();
for(int i=0;i<14;i++){
if(cardExpenseArray[i]!=0 || cashExpenseArray[i]!=0){
xVals.add(categoryArrayBarGraph[i]);
}
}
ArrayList yVals1 = new ArrayList();
ArrayList yVals2 = new ArrayList();
for(int i=0;i<14;i++){
if(cardExpenseArray[i] != 0 || cashExpenseArray[i]!=0){
yVals1.add(new BarEntry((i+1),(float)cardExpenseArray[i]));
yVals2.add(new BarEntry((i+1),(float)cashExpenseArray[i]));
}
}
BarDataSet set1,set2;
set1 = new BarDataSet(yVals1,"Card");
set1.setColor(orange);
set1.setValueTextColor(Color.WHITE);
set1.setValueTextSize(10);
set2 = new BarDataSet(yVals2,"Cash");
set2.setColor(darkGreen);
set2.setValueTextColor(Color.WHITE);
set2.setValueTextSize(10);
BarData data = new BarData(set1,set2);
data.setValueFormatter(new LargeValueFormatter());
mChart.setData(data);
mChart.getBarData().setBarWidth(barWidth);
mChart.getXAxis().setAxisMinimum(0);
// mChart.getXAxis().setAxisMaximum( 0 + mChart.getBarData().getGroupWidth(groupSpace,barSpace) * groupCount);
mChart.groupBars(0,groupSpace,barSpace);
Legend Legend1;
Legend1 = mChart.getLegend();
Legend1.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
Legend1.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
Legend1.setOrientation(Legend.LegendOrientation.HORIZONTAL);
Legend1.setDrawInside(true);
Legend1.setYOffset(25f);
Legend1.setXOffset(0f);
Legend1.setYEntrySpace(0f);
Legend1.setTextSize(13f);
Legend1.setTextColor(Color.WHITE);
//X-axis
XAxis xAxis = mChart.getXAxis();
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);
xAxis.setCenterAxisLabels(true);
xAxis.setDrawGridLines(false);
// xAxis.setAxisMaximum(14);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setValueFormatter(new IndexAxisValueFormatter(xVals));
mChart.setExtraOffsets(20,0,20,10);
xAxis.setTextColor(Color.WHITE);
xAxis.setTextSize(13f);
//Y-axis
mChart.getAxisRight().setEnabled(false);
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setTextColor(Color.WHITE);
leftAxis.setTextSize(13f);
leftAxis.setValueFormatter(new LargeValueFormatter());
leftAxis.setDrawGridLines(true);
leftAxis.setSpaceTop(35f);
leftAxis.setAxisMinimum(0f);
mChart.invalidate();
mChart.animateY(500);
mChart.setDragEnabled(true);
mChart.setVisibleXRangeMaximum(3);
//Line chart
for(int i=0;i<32;i++)
{
cardExpenseLineChart[i] = 0;
cashExpenseLineChart[i] = 0;
}
getDataForLineChart();
mpLineChart = (LineChart) findViewById(R.id.linechart);
ArrayList<Entry> dataVals1 = new ArrayList<Entry>();
ArrayList<Entry> dataVals2 = new ArrayList<Entry>();
for(int i=0;i<31;i++){
dataVals1.add(new Entry((i + 1), (float) cardExpenseLineChart[i]));
dataVals2.add(new Entry((i + 1), (float) cashExpenseLineChart[i]));
}
LineDataSet lineDataSet1 = new LineDataSet(dataVals1,"Card");
lineDataSet1.setColor(Color.RED);
lineDataSet1.setValueTextSize(10);
lineDataSet1.setValueTextColor(Color.WHITE);
LineDataSet lineDataSet2 = new LineDataSet(dataVals2,"Cash");
lineDataSet2.setColor(Color.GREEN);
lineDataSet2.setValueTextColor(Color.WHITE);
lineDataSet2.setValueTextSize(10);
ArrayList<ILineDataSet> dataSets = new ArrayList<>();
dataSets.add(lineDataSet1);
dataSets.add(lineDataSet2);
LineData dataLine = new LineData(dataSets);
mpLineChart.setData(dataLine);
mpLineChart.invalidate();
mpLineChart.setVisibleXRangeMaximum(6);
mpLineChart.setDescription(null);
Legend Legend2;
Legend2 = mpLineChart.getLegend();
Legend2.setTextSize(13f);
Legend2.setTextColor(Color.WHITE);
Legend2.setYEntrySpace(15);
//X-axis
XAxis xAxis1 =mpLineChart.getXAxis();
xAxis1.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis1.setTextColor(Color.WHITE);
xAxis1.setTextSize(13f);
//Y-axis
mpLineChart.getAxisRight().setEnabled(false);
YAxis leftAxis1 = mpLineChart.getAxisLeft();
leftAxis1.setTextColor(Color.WHITE);
leftAxis1.setTextSize(13f);
mpLineChart.animateX(500);
mpLineChart.setPinchZoom(false);
mpLineChart.setScaleEnabled(false);
}
public void getDataForBarGraph()
{
Cursor res = MwDb.getExpenseTableData();
if(res.getCount()==0){
Intent in = new Intent(StatisticsActivity.this, MainActivity.class);
startActivity(in);
Toast.makeText(StatisticsActivity.this,"No data",Toast.LENGTH_SHORT).show();
}
else {
res.moveToFirst();
do {
String user = res.getString(1);
double expense = res.getDouble(2);
String category = res.getString(4);
String paymentmode = res.getString(5);
String retrievedDate = res.getString(3);
retrievedYear = retrievedDate.substring(0,4);
retrievedMonth = retrievedDate.substring(5,7);
if (username.equals(user) && retrievedYear.equals(yearString) && retrievedMonth.equals(monthString)) {
if (paymentmode.equals("Card")) {
for (int i = 0; i < 14; i++) {
if (categoryArrayBarGraph[i].equals(category)) {
cardExpenseArray[i] += expense;
}
}
} else{
for (int i = 0; i < 14; i++) {
if (categoryArrayBarGraph[i].equals(category)) {
cashExpenseArray[i] += expense;
}
}
}
}
} while (res.moveToNext());
}
res.close();
}
public void getDataForLineChart(){
Cursor res = MwDb.getExpenseTableData();
if(res.getCount()==0)
{
Intent in = new Intent(StatisticsActivity.this, MainActivity.class);
startActivity(in);
Toast.makeText(StatisticsActivity.this,"No data",Toast.LENGTH_SHORT).show();
}
else {
res.moveToFirst();
do {
String user = res.getString(1);
String retrievedDate = res.getString(3);
retrievedYear = retrievedDate.substring(0,4);
retrievedMonth = retrievedDate.substring(5,7);
retrievedDay = retrievedDate.substring(8,10);
int retrievedDayint = Integer.parseInt(retrievedDay);
double retrievedAmount = res.getDouble(2);
String retrievedPaymentType = res.getString(5);
if (username.equals(user) && retrievedYear.equals(yearString) && retrievedMonth.equals(monthString)) {
if(retrievedPaymentType.equals("Card")) {
cardExpenseLineChart[retrievedDayint-1] += retrievedAmount;
}
else{
cashExpenseLineChart[retrievedDayint-1] += retrievedAmount;
}
}
} while (res.moveToNext());
}
res.close();
}
}
| true |
b82e8e91792a02f5eadea4bee2fdaae646b26eb4 | Java | seano188/Java-InventoryManagementSystemProject | /team8ca/src/main/java/sg/edu/iss/team8ca/repo/UsageDetailsRepo.java | UTF-8 | 1,128 | 2.171875 | 2 | [] | no_license | package sg.edu.iss.team8ca.repo;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import sg.edu.iss.team8ca.model.UsageDetails;
public interface UsageDetailsRepo extends JpaRepository<UsageDetails, Long> {
@Query("SELECT ud FROM UsageDetails ud WHERE ud.invUsage.id = :id")
public List<UsageDetails> findUdById(@Param("id") Long id);
@Query("SELECT ud FROM UsageDetails ud WHERE ud.inventory.id = :id AND (ud.invUsage.usageDate BETWEEN :startDate AND :endDate)")
public List<UsageDetails> listUsageForInvId(@Param("id")Long id, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);
@Query("SELECT ud FROM UsageDetails ud WHERE ud.inventory.id = :id AND ud.invUsage.id = :id1")
public List<UsageDetails> listUdForInvIdUsageId(@Param("id") Long id, @Param("id1") Long id1);
@Query("SELECT ud FROM UsageDetails ud WHERE ud.inventory.id = :id")
public List<UsageDetails> listUsageForInv(@Param("id")Long id);
}
| true |
a50c6098cc806593972b50600a31c6a3daddd1f0 | Java | M4R10M0R3TT1/SPCM | /src/it/unicas/sensiplusConfigurationManager/view/SEEditDialogController.java | UTF-8 | 13,860 | 1.914063 | 2 | [] | no_license | package it.unicas.sensiplusConfigurationManager.view;
import it.unicas.sensiplusConfigurationManager.model.SensingElement;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class SEEditDialogController {
@FXML
private TextField sensingElementNameTextField;
@FXML
private TextField frequencyTextField;
@FXML
private TextField dcBiasTextField;
@FXML
private TextField filterTextField;
@FXML
private TextField phaseShiftTextField;
@FXML
private TextField conversionTextField;
@FXML
private TextField nDataTextField;
@FXML
private TextField nameTextField;
@FXML
private TextField rangeMinTextField;
@FXML
private TextField rangeMaxTextField;
@FXML
private TextField defaultAlarmThresholdTextField;
@FXML
private TextField multiplerTextField;
@FXML
private ComboBox rSenseComboBox;
@FXML
private ComboBox inGainComboBox;
@FXML
private ComboBox outGainComboBox;
@FXML
private ComboBox contactsComboBox;
@FXML
private ComboBox harmonicComboBox;
@FXML
private ComboBox modeVIComboBox;
@FXML
private ComboBox measureTechniqueComboBox;
@FXML
private ComboBox measureTypeComboBox;
@FXML
private ComboBox phaseShiftModeComboBox;
@FXML
private ComboBox IQComboBox;
@FXML
private ComboBox inPortADCComboBox;
@FXML
private ComboBox measureUnitComboBox;
@FXML
private Label seNameLabel;
private Stage dialogStage;
private SensingElement sensingElement;
private boolean okClicked = false;
private boolean verifyLen = true;
@FXML
private void initialize() {
//rSense ComboBox
rSenseComboBox.getItems().addAll(50,500,5000,50000);
rSenseComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//inGain ComboBox
inGainComboBox.getItems().addAll(1,12,20,40);
inGainComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//outGain ComboBox
outGainComboBox.getItems().addAll(0,1,2,3,4,5,6,7);
outGainComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//contacts ComboBox
contactsComboBox.getItems().addAll("TWO","FOUR");
contactsComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//harmonic ComboBox
harmonicComboBox.getItems().addAll("FIRST_HARMONIC","SECOND_HARMONIC","TIRD_HARMONIC");
harmonicComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//modeVI ComboBox
modeVIComboBox.getItems().addAll("VOUT_IIN","VIN_IIN","VOUT_VIN","VOUT_VOUT");
modeVIComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//measureTechnique ComboBox
measureTechniqueComboBox.getItems().addAll("DIRECT", "EIS","POT","ENERGY_SPECTROSCOPY","ULTRASOUND");
measureTechniqueComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//measureType ComboBox
measureTypeComboBox.getItems().addAll("IN-PHASE","QUADRATURE","MODULE","PHASE","RESISTANCE","CAPACITANCE","INDUCTANCE");
measureTypeComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//phaseShiftMode ComboBox
phaseShiftModeComboBox.getItems().addAll("QUADRANT","COARSE","FINE");
phaseShiftModeComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//IQ ComboBox
IQComboBox.getItems().addAll("IN_PHASE","QUADRATURE");
IQComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//inPortADC ComboBox
inPortADCComboBox.getItems().addAll("IA","VA");
inPortADCComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
//measureUnit ComboBox
measureUnitComboBox.getItems().addAll("O","F","H","C","%","V","A","L","t");
measureUnitComboBox.valueProperty().addListener((ObservableValue observable,Object oldValue,Object newValue)->newValue.toString());
}
/**
* Sets the stage of this dialog.
*
* @param dialogStage
*/
public void setDialogStage(Stage dialogStage, boolean verifyLen) {
this.dialogStage = dialogStage;
// Set the dialog icon.
this.dialogStage.getIcons().add(new Image("file:resources/images/pencil-lapis-128.png"));
}
/**
* Sets the sensingElement to be edited in the dialog.
*
* @param sensingElement
*/
public void setSensingElement(SensingElement sensingElement) {
this.sensingElement = sensingElement;
sensingElementNameTextField.setText(sensingElement.getIdSensingElement());
rSenseComboBox.setValue(sensingElement.getrSense());
inGainComboBox.setValue(sensingElement.getInGain());
outGainComboBox.setValue(sensingElement.getOutGain());
contactsComboBox.setValue(sensingElement.getContacts());
frequencyTextField.setText(Integer.toString(sensingElement.getFrequency()));
harmonicComboBox.setValue(sensingElement.getHarmonic());
dcBiasTextField.setText(Integer.toString(sensingElement.getDcBias()));
modeVIComboBox.setValue(sensingElement.getModeVI());
measureTechniqueComboBox.setValue(sensingElement.getmeasureTechnique());
measureTypeComboBox.setValue(sensingElement.getMeasureType());
filterTextField.setText(Integer.toString(sensingElement.getFilter()));
phaseShiftModeComboBox.setValue(sensingElement.getPhaseShiftMode());
phaseShiftTextField.setText(Integer.toString(sensingElement.getPhaseShift()));
IQComboBox.setValue(sensingElement.getIq());
conversionTextField.setText(Integer.toString(sensingElement.getConversionRate()));
inPortADCComboBox.setValue(sensingElement.getInPortADC());
nDataTextField.setText(Integer.toString(sensingElement.getnData()));
nameTextField.setText(sensingElement.getName());
rangeMinTextField.setText(Double.toString(sensingElement.getRangeMin()));
rangeMaxTextField.setText(Double.toString(sensingElement.getRangeMax()));
defaultAlarmThresholdTextField.setText((Double.toString(sensingElement.getDefaultAlarmThreshold())));
multiplerTextField.setText(Integer.toString(sensingElement.getMultiplier()));
measureUnitComboBox.setValue(sensingElement.getMeasureUnit());
if(sensingElement.getIdSensingElement()!=null) {
seNameLabel.setText("Edit");
sensingElementNameTextField.setDisable(true);
disableParameter();
}
else
seNameLabel.setText("Insert a new SensingElement");
}
/**
* Returns true if the user clicked OK, false otherwise.
*
* @return
*/
public boolean isOkClicked() {
return okClicked;
}
public void disableParameter() {
if (measureTechniqueComboBox.getValue().toString()=="DIRECT")
{
rSenseComboBox.setDisable(true);
inGainComboBox.setDisable(true);
outGainComboBox.setDisable(true);
contactsComboBox.setDisable(true);
frequencyTextField.setDisable(true);
harmonicComboBox.setDisable(true);
dcBiasTextField.setDisable(true);
modeVIComboBox.setDisable(true);
measureTypeComboBox.setDisable(true);
phaseShiftModeComboBox.setDisable(true);
phaseShiftTextField.setDisable(true);
IQComboBox.setDisable(true);
}
else {
rSenseComboBox.setDisable(false);
inGainComboBox.setDisable(false);
outGainComboBox.setDisable(false);
contactsComboBox.setDisable(false);
frequencyTextField.setDisable(false);
harmonicComboBox.setDisable(false);
dcBiasTextField.setDisable(false);
modeVIComboBox.setDisable(false);
measureTypeComboBox.setDisable(false);
phaseShiftModeComboBox.setDisable(false);
phaseShiftTextField.setDisable(false);
IQComboBox.setDisable(false);
}
}
/**
* Called when the user clicks ok.
*/
@FXML
private void handleOk() {
if (isInputValid(verifyLen)) {
sensingElement.setIdSensingElement(sensingElementNameTextField.getText());
sensingElement.setrSense(Integer.parseInt(rSenseComboBox.getValue().toString()));
sensingElement.setInGain(Integer.parseInt(inGainComboBox.getValue().toString()));
sensingElement.setOutGain(Integer.parseInt(outGainComboBox.getValue().toString()));
sensingElement.setContacts(contactsComboBox.getValue().toString());
sensingElement.setFrequency(Integer.parseInt(frequencyTextField.getText()));
sensingElement.setHarmonic(harmonicComboBox.getValue().toString());
sensingElement.setDcBias(Integer.parseInt(dcBiasTextField.getText()));
sensingElement.setModeVI(modeVIComboBox.getValue().toString());
sensingElement.setmeasureTechnique(measureTechniqueComboBox.getValue().toString());
sensingElement.setMeasureType(measureTypeComboBox.getValue().toString());
sensingElement.setFilter(Integer.parseInt(filterTextField.getText()));
sensingElement.setPhaseShiftMode(phaseShiftModeComboBox.getValue().toString());
sensingElement.setPhaseShift(Integer.parseInt(phaseShiftTextField.getText()));
sensingElement.setIq(IQComboBox.getValue().toString());
sensingElement.setConversionRate(Integer.parseInt(conversionTextField.getText()));
sensingElement.setInPortADC(inPortADCComboBox.getValue().toString());
sensingElement.setnData(Integer.parseInt(nDataTextField.getText()));
sensingElement.setName(nameTextField.getText());
sensingElement.setRangeMin(Double.parseDouble(rangeMinTextField.getText()));
sensingElement.setRangeMax(Double.parseDouble(rangeMaxTextField.getText()));
sensingElement.setDefaultAlarmThreshold(Double.parseDouble(defaultAlarmThresholdTextField.getText()));
sensingElement.setMultiplier(Integer.parseInt(multiplerTextField.getText()));
sensingElement.setMeasureUnit(measureUnitComboBox.getValue().toString());
okClicked = true;
dialogStage.close();
}
}
/**
* Called when the user clicks cancel.
*/
@FXML
private void handleCancel() {
dialogStage.close();
}
/**
* Validates the user input in the text fields.
*
* @return true if the input is valid
*/
private boolean isInputValid(boolean verifyLen) {
String errorMessage = "";
if (sensingElementNameTextField.getText() == null || (verifyLen && sensingElementNameTextField.getText().length() == 0)) {
errorMessage += "No valid Sensing Element Name!\n";
}
if (Double.parseDouble(frequencyTextField.getText()) < 0 || Double.parseDouble(frequencyTextField.getText()) > 5000000) {
errorMessage += "No valid frequency! [0,5000000]\n";
}
if(Integer.parseInt(dcBiasTextField.getText()) < -2048 || Integer.parseInt(dcBiasTextField.getText()) > 2048){
errorMessage += "No valid dcBias! [-2048,2048]\n";
}
if(Integer.parseInt(filterTextField.getText()) < 1 || Integer.parseInt(filterTextField.getText()) > 256){
errorMessage += "No valid filter! [1,256]\n";
}
if(Integer.parseInt(phaseShiftTextField.getText()) < 0 || Integer.parseInt(phaseShiftTextField.getText()) > 360){
errorMessage += "No valid phaseShift! [0,360]\n";
}
if(Integer.parseInt(conversionTextField.getText()) < 1 || Integer.parseInt(conversionTextField.getText()) > 100000){
errorMessage += "No valid conversionRate! [1,100000]\n";
}
if(Integer.parseInt(nDataTextField.getText()) < 1 || Integer.parseInt(nDataTextField.getText()) > 16){
errorMessage += "No valid nData! [1,16]\n";
}
if(Integer.parseInt(multiplerTextField.getText()) < -21 || Integer.parseInt(multiplerTextField.getText()) > 21){
errorMessage += "No valid multipler! [-21,21]\n";
}
if (errorMessage.length() == 0) {
return true;
} else {
// Show the error message.
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.initOwner(dialogStage);
alert.setTitle("Invalid Fields");
alert.setHeaderText("Please correct invalid fields");
alert.setContentText(errorMessage);
alert.showAndWait();
return false;
}
}
@FXML
private void writeNameTextField(){
nameTextField.setText(sensingElementNameTextField.getText());
}
} | true |
9d0fc5cb3256aeb5235e834f656451b5a081903e | Java | MrHusm/motionManageV2 | /src/main/java/com/manage/task/GetuiTask.java | UTF-8 | 2,242 | 2.0625 | 2 | [] | no_license | package com.manage.task;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import com.alibaba.fastjson.JSONObject;
import com.manage.constant.Constant;
import com.manage.service.BannerAppService;
import com.manage.util.GetuiUtil;
@Controller
public class GetuiTask {
@Resource
private BannerAppService bannerAppService;
/**
* 每天20:00,如果用户的每日福利页面中还有尚未领取的奖励,则给这些用户发一条push
*/
public void pushQiandao() {
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("action_data", "http://ad_earn_coins?index=2");
String content = JSONObject.toJSONString(jsonMap);
List<Map<String,Object>> clients = bannerAppService.getQiandaoUsers(); // 获取推送列表
if(clients != null && clients.size()>0){
GetuiUtil.pushMessageToList(clients, Constant.GETUI_MSG_T001_TITLE, Constant.GETUI_MSG_T001_TEXT, content);
}
}
/**
* 新增用户,次日的9:00前未访问客户端,则给这些用户发一条push
*/
public void pushNewUser() {
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("action_data", "http://zwsc.ikanshu.cn/bookv3/xmbd");
String content = JSONObject.toJSONString(jsonMap);
List<Map<String,Object>> clients = bannerAppService.getNewUsers(); // 获取推送列表
if(clients != null && clients.size()>0){
GetuiUtil.pushMessageToList(clients, Constant.GETUI_MSG_T002_TITLE, Constant.GETUI_MSG_T002_TEXT, content);
}
}
/**
* VIP到期前一天10:00,给用户发条push
*/
public void pushExpireVipUsers() {
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("action_data", "http://zwsc.ikanshu.cn/vip/index");
String content = JSONObject.toJSONString(jsonMap);
List<Map<String,Object>> clients = bannerAppService.getExpireVipUsers(); // 获取推送列表
if(clients != null && clients.size()>0){
GetuiUtil.pushMessageToList(clients, Constant.GETUI_MSG_T003_TITLE, Constant.GETUI_MSG_T003_TEXT, content);
}
}
} | true |
c3aa9a9eb405a6209f01e9bf45095151279676f6 | Java | SchuckBeta/cxcy | /src/main/java/com/oseasy/cms/modules/cms/dao/CmsLinkDao.java | UTF-8 | 1,149 | 1.875 | 2 | [] | no_license | package com.oseasy.cms.modules.cms.dao;
import com.oseasy.cms.modules.cms.entity.CmsLink;
import com.oseasy.com.pcore.common.persistence.CrudDao;
import com.oseasy.com.pcore.common.persistence.annotation.FindListByTenant;
import com.oseasy.com.pcore.common.persistence.annotation.InsertByTenant;
import com.oseasy.com.pcore.common.persistence.annotation.MyBatisDao;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 友情链接DAO接口.
* @author zy
* @version 2018-08-30
*/
@MyBatisDao
public interface CmsLinkDao extends CrudDao<CmsLink> {
@Override
@FindListByTenant
public List<CmsLink> findList(CmsLink entity);
@Override
@InsertByTenant
public int insert(CmsLink entity);
/**
* 物理删除.
* @param entity
*/
public void deleteWL(CmsLink cmsLink);
void delPl(@Param("idList")List<String> idList);
// void cmsLinkSaveSort(@Param("idList") List<String> idList, @Param("sortList")List<String> sortList);
void cmsLinkSaveSort(@Param("cmsList")List<CmsLink> cmsList);
@FindListByTenant
List<CmsLink> findFrontList(CmsLink cmsLink);
Integer checkLinkName(CmsLink cmsLink);
} | true |
f3c3b77b34b7dddb3988aeeb26c9a12d2e25da9d | Java | zrbsprite/Stem | /hunger/src/com/stem/entity/Product.java | UTF-8 | 3,354 | 2.0625 | 2 | [] | no_license | package com.stem.entity;
import java.util.Date;
public class Product {
private Integer id;
private String code;
private String name;
private String title;
private String pic;
private String buyUrl;
private String upDown;
private String shareUrl;
private String trendsUrl;
private String scoreStandard;
private String marketPrice;
private String salePrice;
private String unit;
private String productLable;
private String supplierCode;
private String productTypeCode;
private Date createTime;
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getBuyUrl() {
return buyUrl;
}
public void setBuyUrl(String buyUrl) {
this.buyUrl = buyUrl;
}
public String getUpDown() {
return upDown;
}
public void setUpDown(String upDown) {
this.upDown = upDown;
}
public String getShareUrl() {
return shareUrl;
}
public void setShareUrl(String shareUrl) {
this.shareUrl = shareUrl;
}
public String getTrendsUrl() {
return trendsUrl;
}
public void setTrendsUrl(String trendsUrl) {
this.trendsUrl = trendsUrl;
}
public String getScoreStandard() {
return scoreStandard;
}
public void setScoreStandard(String scoreStandard) {
this.scoreStandard = scoreStandard;
}
public String getMarketPrice() {
return marketPrice;
}
public void setMarketPrice(String marketPrice) {
this.marketPrice = marketPrice;
}
public String getSalePrice() {
return salePrice;
}
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getProductLable() {
return productLable;
}
public void setProductLable(String productLable) {
this.productLable = productLable;
}
public String getSupplierCode() {
return supplierCode;
}
public void setSupplierCode(String supplierCode) {
this.supplierCode = supplierCode;
}
public String getProductTypeCode() {
return productTypeCode;
}
public void setProductTypeCode(String productTypeCode) {
this.productTypeCode = productTypeCode;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
} | true |
1d3f7e9aa5f8c3be6c129201df4ac9bb2e2eb844 | Java | saber13812002/DeepCRM | /Code Snippet Repository/Struts/Struts1426.java | UTF-8 | 759 | 2.8125 | 3 | [] | no_license | public void testParamWithClassInName() throws Exception {
// given
List<String> properParams = new ArrayList<>();
properParams.add("eventClass");
properParams.add("form.eventClass");
properParams.add("form[\"eventClass\"]");
properParams.add("form['eventClass']");
properParams.add("class.super@demo.com");
properParams.add("super.class@demo.com");
ExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker();
for (String properParam : properParams) {
// when
ExcludedPatternsChecker.IsExcluded actual = checker.isExcluded(properParam);
// then
assertFalse("Param '" + properParam + "' is excluded!", actual.isExcluded());
}
}
| true |
f6d0c2c02b13847713400ea86ff3e7de08b42a4b | Java | aaronguostudio/learn-java | /temp/Test.java | UTF-8 | 163 | 1.882813 | 2 | [] | no_license | package test;
class Test
{
public static void main ( String [] arguments )
{
FlyWithWings flyWithWings = new FlyWithWings();
flyWithWings.fly();
}
} | true |
dc28dc95e777bf7321ed4f00cb9828ea5683ae26 | Java | 17862958267/MyFirstRepository | /cookie/src/cn/qlu/filter/TokenFilter.java | UTF-8 | 1,485 | 2.421875 | 2 | [] | no_license | package cn.qlu.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TokenFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
//判断是否存在_token_请求
if(req.getMethod().equals("POST")){
//获取数据
String token = req.getParameter("_token_");
System.out.println(token);
if(token!=null){
//从session中取值
String sToken = (String) req.getSession().getAttribute("_token_");
//比较
if(token.equals(sToken)){
req.getSession().removeAttribute("_token_");
chain.doFilter(request, response);
}else{
HttpServletResponse resp = (HttpServletResponse) response;
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().print("不可以重复提交");
}
}else{
chain.doFilter(request, response);
}
}else{
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
| true |
2d893fc33d6ef0f831cae51ac5ada3bdd62a8be3 | Java | Dini68/trainingexams | /src/main/java/hu/nive/ujratervezes/zarovizsga/digitscounter/DigitsCounter.java | UTF-8 | 489 | 3.046875 | 3 | [] | no_license | package hu.nive.ujratervezes.zarovizsga.digitscounter;
import java.util.HashSet;
import java.util.Set;
public class DigitsCounter {
public int getCountOfDigits(String s) {
if (s == null) {
return 0;
}
Set<Integer> numbers = new HashSet<>();
for (char ch: s.toCharArray()) {
if (Character.isDigit(ch)) {
numbers.add(Character.getNumericValue(ch));
}
}
return numbers.size();
}
}
| true |
6c206895e28eea747d615442f4db352f4d31f41b | Java | regiapriandi012/javaLearning | /regiapriandi/praktikumpbo/pertemuan5/unguided/GasMulia.java | UTF-8 | 274 | 2.34375 | 2 | [] | no_license | package com.regiapriandi.praktikumpbo.pertemuan5.unguided;
public class GasMulia extends UnsurKimia{
public GasMulia(String unsur) {
super(unsur);
}
public void info(){
System.out.println(getUnsur() + " Merupakan unsur kimia Gas Mulia");
}
}
| true |
55df0d8927e5ae2b710722beca9ef472b3c8e162 | Java | jieyuchongliang/TestFragmentmanager | /app/src/main/java/vlayout/fujisoft/com/testfragmentmanager/adapter/PersonDetailListAdapter.java | UTF-8 | 1,517 | 2.3125 | 2 | [] | no_license | package vlayout.fujisoft.com.testfragmentmanager.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import vlayout.fujisoft.com.testfragmentmanager.commen.CommenAdapter;
import vlayout.fujisoft.com.testfragmentmanager.R;
import vlayout.fujisoft.com.testfragmentmanager.bean.Person;
/**
* Created by 860617010 on 2017/11/1.
*/
public class PersonDetailListAdapter extends CommenAdapter<Person> {
public PersonDetailListAdapter(Context context, List<Person> list) {
super(context, list);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyHolder holder = null;
if (convertView == null) {
holder = new MyHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.item_person_list, parent, false);
holder.tvAddress = (TextView) convertView.findViewById(R.id.tv_address);
holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(holder);
} else {
holder = (MyHolder) convertView.getTag();
}
holder.tvName.setText(list.get(position).getName());
holder.tvAddress.setText(list.get(position).getAddress());
return convertView;
}
class MyHolder {
private TextView tvName, tvAddress;
}
}
| true |
414a0617fdc38b02dd8d166fb9ee728adc0ffcfa | Java | kevinPoklinger/ShearGear | /ShearGear_Android/app/src/main/java/com/example/kevin/sheargear/ProductDetailActivity.java | UTF-8 | 9,435 | 1.828125 | 2 | [] | no_license | package com.example.kevin.sheargear;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.facebook.common.util.UriUtil;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.stfalcon.frescoimageviewer.ImageViewer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.apptik.widget.multiselectspinner.MultiSelectSpinner;
import me.relex.photodraweeview.PhotoDraweeView;
public class ProductDetailActivity extends AppCompatActivity {
Typeface typeface_300;
Typeface typeface_500;
Typeface typeface_700;
Button continueButton;
Button handleTypeButton;
Button freeEngravingButton;
EditText likeEngravedInput;
Spinner handSpinner;
Spinner bladeSpinner;
Spinner freeEngravingSpinner;
MultiSelectSpinner favoriteColorSpinner;
MultiSelectSpinner lengthSpinner;
Spinner garmentSizeSpinner;
Spinner handleTypeSpinner;
ArrayList<String> hands = new ArrayList<String>(Arrays.asList("Right Handed", "Left Handed"));
ArrayList<String> bladeTypes = new ArrayList<String>(Arrays.asList("Mix of straight & curved", "curved only", "straight only"));
ArrayList<String> lengthTypes = new ArrayList<String>(Arrays.asList("All Sizes 7\"-9.5\"", "Medium 7-8.5\"", "Large: 8\"-10\""));
ArrayList<String> freeEngravings = new ArrayList<String>(Arrays.asList("Absolutely!", "No, Thank you"));
ArrayList<String> colors = new ArrayList<String>(Arrays.asList("Clear/White", "Black", "Pink", "Purple", "Dark Green", "Lime", "Red", "Blue", "Turquoise", "Yellow", "Orange"));
ArrayList<String> garmentSizes = new ArrayList<String>(Arrays.asList("small", "medium", "large", "XL", "XXL", "3X", "4X", "5X"));
ArrayList<String> preferredHandleTypes = new ArrayList<String>(Arrays.asList("Even (flippable)", "Offset (Ergo)", "Swivel ($5 surcharge per box)"));
String selectedHand;
String selectedBladeType;
String selectedLength;
String selectedFreeEngraving;
String selectedColors;
String selectedGarmentSize;
String selectedPreferredHandleType;
String likeEngraved;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_detail_layout);
Fresco.initialize(getApplicationContext());
typeface_300 = Typeface.createFromAsset(getAssets(), "museo300-Regular.otf");
typeface_500 = Typeface.createFromAsset(getAssets(), "museo500-Regular.otf");
typeface_700 = Typeface.createFromAsset(getAssets(), "museo700-Regular.otf");
final View superView = (View) findViewById(R.id.super_view);
overrideFonts(this, superView);
((TextView) findViewById(R.id.shear_gear_title)).setTypeface(typeface_500);
((TextView) findViewById(R.id.choose_your_preferrence)).setTypeface(typeface_500);
((TextView) findViewById(R.id.hand_title)).setTypeface(typeface_500);
((TextView) findViewById(R.id.blade_title)).setTypeface(typeface_500);
((TextView) findViewById(R.id.free_engraving_title)).setTypeface(typeface_500);
((TextView) findViewById(R.id.like_engraved_comment)).setTypeface(typeface_500);
((TextView) findViewById(R.id.favorite_color_title)).setTypeface(typeface_500);
((TextView) findViewById(R.id.garment_size_title)).setTypeface(typeface_500);
((TextView) findViewById(R.id.favorite_color_title)).setTypeface(typeface_500);
((TextView) findViewById(R.id.handle_type_title)).setTypeface(typeface_500);
((Button) findViewById(R.id.continue_button)).setTypeface(typeface_500);
((Button) findViewById(R.id.handle_type_button)).setTypeface(typeface_500);
((Button) findViewById(R.id.free_engraving_button)).setTypeface(typeface_500);
continueButton = (Button) findViewById(R.id.continue_button);
handleTypeButton = (Button) findViewById(R.id.handle_type_button);
freeEngravingButton = (Button) findViewById(R.id.free_engraving_button);
likeEngravedInput = (EditText) findViewById(R.id.like_engraved_input);
continueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedHand = handSpinner.getSelectedItem().toString();
selectedBladeType = bladeSpinner.getSelectedItem().toString();
selectedFreeEngraving = freeEngravingSpinner.getSelectedItem().toString();
selectedColors = favoriteColorSpinner.getSelectedItem().toString();
selectedGarmentSize = garmentSizeSpinner.getSelectedItem().toString();
selectedPreferredHandleType = handleTypeSpinner.getSelectedItem().toString();
likeEngraved = likeEngravedInput.getText().toString();
selectedLength = lengthSpinner.getSelectedItem().toString();
Intent planIntent = new Intent(ProductDetailActivity.this, PlanActivity.class);
planIntent.putExtra("Hand", selectedHand);
planIntent.putExtra("BladeType", selectedBladeType);
planIntent.putExtra("FreeEngraving", selectedFreeEngraving);
planIntent.putExtra("Colors", selectedColors);
planIntent.putExtra("GarmentSize", selectedGarmentSize);
planIntent.putExtra("HandleyType", selectedPreferredHandleType);
planIntent.putExtra("LikeEngraved", likeEngraved);
planIntent.putExtra("Length", selectedLength);
startActivity(planIntent);
}
});
handleTypeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = new Uri.Builder()
.scheme(UriUtil.LOCAL_RESOURCE_SCHEME) // "res"
.path(String.valueOf(R.drawable.handletype))
.build();
Uri[] list = new Uri[]{uri};
new ImageViewer.Builder(ProductDetailActivity.this, list).setStartPosition(0).show();
}
});
freeEngravingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = new Uri.Builder()
.scheme(UriUtil.LOCAL_RESOURCE_SCHEME) // "res"
.path(String.valueOf(R.drawable.freeengaging))
.build();
Uri[] list = new Uri[]{uri};
new ImageViewer.Builder(ProductDetailActivity.this, list).setStartPosition(0).show();
}
});
handSpinner = (Spinner) findViewById(R.id.hand_spinner);
bladeSpinner = (Spinner) findViewById(R.id.blade_spinner);
freeEngravingSpinner = (Spinner) findViewById(R.id.free_engraving_spinner);
garmentSizeSpinner = (Spinner) findViewById(R.id.garment_size_spinner);
handleTypeSpinner = (Spinner) findViewById(R.id.handle_type_spinner);
setAdapter(handSpinner, hands);
setAdapter(bladeSpinner, bladeTypes);
setAdapter(freeEngravingSpinner, freeEngravings);
setAdapter(garmentSizeSpinner, garmentSizes);
setAdapter(handleTypeSpinner, preferredHandleTypes);
favoriteColorSpinner = (MultiSelectSpinner) findViewById(R.id.favorite_color_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter <String>(this, android.R.layout.simple_list_item_multiple_choice, colors);
favoriteColorSpinner.setListAdapter(adapter);
lengthSpinner = (MultiSelectSpinner) findViewById(R.id.length_spinner);
ArrayAdapter<String> lengthAdapter = new ArrayAdapter <String>(this, android.R.layout.simple_list_item_multiple_choice, lengthTypes);
lengthSpinner.setListAdapter(lengthAdapter);
}
public void setAdapter(Spinner spinner, ArrayList<String> array) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
private void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView) {
((TextView) v).setTypeface(typeface_500);
}
} catch (Exception e) {
}
}
}
| true |
d9aedead882dea19138ecb9ded41cbd02c7ea10b | Java | nuving/castafioreframework | /casta-searchengine/casta-searchengine/org/castafiore/designable/EXSearchProductBar.java | UTF-8 | 4,104 | 1.992188 | 2 | [] | no_license | package org.castafiore.designable;
import java.util.List;
import java.util.Map;
import org.castafiore.KeyValuePair;
import org.castafiore.SimpleKeyValuePair;
import org.castafiore.searchengine.MallUtil;
import org.castafiore.shoppingmall.merchant.FinanceUtil;
import org.castafiore.shoppingmall.merchant.Merchant;
import org.castafiore.ui.Container;
import org.castafiore.ui.UIException;
import org.castafiore.ui.engine.ClientProxy;
import org.castafiore.ui.events.Event;
import org.castafiore.ui.ex.form.EXInput;
import org.castafiore.ui.ex.form.button.EXButton;
import org.castafiore.ui.ex.form.button.EXIconButton;
import org.castafiore.ui.ex.form.button.Icons;
import org.castafiore.ui.ex.form.list.DefaultDataModel;
import org.castafiore.ui.ex.form.list.EXSelect;
import org.castafiore.utils.ComponentUtil;
import org.castafiore.utils.ComponentVisitor;
import org.castafiore.utils.StringUtil;
import org.castafiore.wfs.Util;
public class EXSearchProductBar extends AbstractXHTML implements Event{
public EXSearchProductBar(String name) {
super(name);
addChild(new EXInput("searchInput"));
addChild(new EXIconButton("search", Icons.ICON_SEARCH).removeClass("ui-corner-all").setAttribute("title", "Search Products").addEvent(this, Event.CLICK));
addChild(new EXIconButton("myCart",Icons.ICON_CART).removeClass("ui-corner-all").setAttribute("title", "Show my shopping cart").setStyle("float", "left").addEvent(this, Event.CLICK));
try{
addChild(new EXSelect("currency", new DefaultDataModel<Object>((List)FinanceUtil.getCurrencies())).setStyle("float", "right").setStyle("font-size", "10px").setStyle("margin", "4px").addEvent(this, CHANGE));
String path = (String)getRoot().getConfigContext().get("portalPath");
String username = MallUtil.getEcommerceMerchant();
Merchant m = MallUtil.getMerchant(username);
getDescendentOfType(EXSelect.class).setValue(new SimpleKeyValuePair(m.getCurrency(), ""));
}catch(Exception e){
e.printStackTrace();
}
}
public String getCurrency(){
return ((KeyValuePair)getDescendentOfType(EXSelect.class).getValue()).getKey();
}
@Override
public void ClientAction(ClientProxy container) {
container.mask().makeServerRequest(this);
}
@Override
public boolean ServerAction(Container container, Map<String, String> request)
throws UIException {
if(container.getName().equals("currency")){
ComponentUtil.iterateOverDescendentsOfType(getAncestorOfType(EXEcommerce.class), CurrencySensitive.class, new ComponentVisitor() {
@Override
public void doVisit(Container c) {
// TODO Auto-generated method stub
try{
((CurrencySensitive)c).changeCurrency();
}catch(Exception e){
e.printStackTrace();
}
}
});
return true;
}
EXEcommerce ecommerce = container.getAncestorOfType(EXEcommerce.class);
String path = (String)getRoot().getConfigContext().get("portalPath");
String username = MallUtil.getEcommerceMerchant();
if(container.getName().equals("search")){
String value = getDescendentOfType(EXInput.class).getValue().toString();
if(StringUtil.isNotEmpty(value)){
EXCatalogue cat = (EXCatalogue)ecommerce.getPageOfType(EXCatalogue.class);
if(cat == null){
cat = new EXCatalogue("");
ecommerce.getBody().addChild(cat);
}
cat.search("fulltext", value,username);
ecommerce.showPage(EXCatalogue.class);
return true;
}
}else{
EXCartDetail cart =(EXCartDetail)ecommerce.getPageOfType(EXCartDetail.class);
if(cart == null){
cart = new EXCartDetail("");
ecommerce.getBody().addChild(cart);
}
cart.init(ecommerce.getDescendentOfType(EXMiniCart.class));
ecommerce.showPage(EXCartDetail.class);
return true;
}
return false;
}
@Override
public void Success(ClientProxy container, Map<String, String> request)
throws UIException {
if(request.containsKey("msg")){
container.alert(request.get("msg"));
}
}
}
| true |
7ed8389beaa2d8acb6e24405c5909e39deb9999b | Java | nightshp/night | /ssmDemo/src/main/java/dao/UserMapper.java | UTF-8 | 249 | 1.992188 | 2 | [] | no_license | package dao;
import entity.User;
import java.util.List;
public interface UserMapper {
List<User> selectAll();
User selectById(Integer id);
int deleteById(Integer id);
int insertOne(User user);
int updateById(User user);
} | true |
f13551667bff2752f219531231cdf63653e17981 | Java | fogelvogel/BDDSite | /BDD/src/StepDefinition/CatCreation.java | UTF-8 | 3,364 | 2.546875 | 3 | [] | no_license | package StepDefinition;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;
public class CatCreation {
public static WebDriver driver;
WebElement[] columns = new WebElement[5];
@Given("^i opened browser window$")
public void i_opened_browser_window() throws Throwable {
System.setProperty("webdriver.chrome.driver", "C:\\BDDSite\\chromedriver_win32\\chromedriver.exe");
driver= new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://newbdd/cat/");
}
@When("^i clicked new button$")
public void i_clicked_new_button() throws Throwable {
CatCreation.driver.findElement(By.cssSelector(".new-cat")).click();
}
@When("^i typed \"(.*?)\" in imya field$")
public void i_typed_in_imya_field(String arg1) throws Throwable {
driver.findElement(By.cssSelector("#cat_imya")).sendKeys(arg1);
}
@When("^i typed \"(.*?)\" in poroda field$")
public void i_typed_in_poroda_field(String arg1) throws Throwable {
driver.findElement(By.cssSelector("#cat_poroda")).sendKeys(arg1);
}
@When("^i typed \"(.*?)\" in cvet field$")
public void i_typed_in_cvet_field(String arg1) throws Throwable {
driver.findElement(By.cssSelector("#cat_cvet")).sendKeys(arg1);
}
@When("^i typed \"(.*?)\" in harakter field$")
public void i_typed_in_harakter_field(String arg1) throws Throwable {
driver.findElement(By.cssSelector("#cat_harakter")).sendKeys(arg1);
}
@When("^i clicked save button$")
public void i_clicked_save_button() throws Throwable {
driver.findElement(By.cssSelector("button")).click();
}
@Then("^new cat should be visible$")
public void new_cat_should_be_visible() throws Throwable {
Assert.assertNotNull(driver.findElement(By.cssSelector("td")));
}
@Then("^first cell should be \"(.*?)\"$")
public void first_cell_should_be(String arg1) throws Throwable {
Assert.assertEquals(arg1, driver.findElements(By.cssSelector("td")).get(1).getText());
}
@Then("^second cell should be \"(.*?)\"$")
public void second_cell_should_be(String arg1) throws Throwable {
Assert.assertEquals(arg1, driver.findElements(By.cssSelector("td")).get(2).getText());
}
@Then("^third cell should be \"(.*?)\"$")
public void third_cell_should_be(String arg1) throws Throwable {
Assert.assertEquals(arg1, driver.findElements(By.cssSelector("td")).get(3).getText());
}
@Then("^fourth cell should be \"(.*?)\"$")
public void fourth_cell_should_be(String arg1) throws Throwable {
Assert.assertEquals(arg1, driver.findElements(By.cssSelector("td")).get(4).getText());
}
@When("^i clicked show button$")
public void i_clicked_show_button() throws Throwable {
driver.findElement(By.cssSelector("a")).click();
}
@When("^clicked delete button$")
public void clicked_delete_button() throws Throwable {
driver.findElement(By.cssSelector("button")).click();
driver.switchTo().alert().accept();
}
@Then("^new cat should not be visible$")
public void new_cat_should_not_be_visible() throws Throwable {
Assert.assertEquals(1, driver.findElements(By.cssSelector("td")).size());
driver.close();
}
}
| true |
6984cfae3ddb9603f0c4f319e2037e6a31c531e3 | Java | Zoly90/EMZOtours | /src/main/java/ro/emzo/turismapp/home_page/service/HomePageService.java | UTF-8 | 994 | 2.078125 | 2 | [] | no_license | package ro.emzo.turismapp.home_page.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ro.emzo.turismapp.holiday.model.HolidayMainCategories;
import ro.emzo.turismapp.holiday.model.HolidaySubcategories;
import ro.emzo.turismapp.holiday.model.HolidayTypes;
import ro.emzo.turismapp.home_page.dao.HomePageDataService;
@Service
public class HomePageService {
@Autowired
private HomePageDataService homePageDataService;
private List<HolidayMainCategories> getHolidaySubcategories() {
return homePageDataService.getHolidaySubcategories();
}
private List<HolidayTypes> getHolidayTypes() {
return homePageDataService.getHolidayTypes();
}
public HomePage getHomePageData() {
HomePage homePageData = new HomePage();
homePageData.setHolidayMainCategoriesList(getHolidaySubcategories());
homePageData.setHolidayTypesList(getHolidayTypes());
return homePageData;
}
}
| true |
e8c1dbfbd7ee0173ffb767a50b464332ae5bf7af | Java | weicheng95/mydiary | /app/src/main/java/com/example/weichenglau/personalDiary/StoryContentActivity.java | UTF-8 | 898 | 2.203125 | 2 | [] | no_license | package com.example.weichenglau.personalDiary;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class StoryContentActivity extends AppCompatActivity {
private TextView date, title, content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment2_layout);
date = (TextView)findViewById(R.id.date);
title = (TextView)findViewById(R.id.title);
content = (TextView)findViewById(R.id.content);
String getdate = getIntent().getStringExtra("day") + "-" + getIntent().getStringExtra("month") + "-" + getIntent().getStringExtra("year");
date.setText(getdate);
title.setText(getIntent().getStringExtra("title"));
content.setText(getIntent().getStringExtra("content"));
}
}
| true |
9140d1ea9f99fc166e1bd8213881b4cac65151bd | Java | vipinv95/Java-programs | /Video_Database_Project_MVC/View.java | UTF-8 | 15,730 | 2.265625 | 2 | [] | no_license | /*
* 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 videos_database_project2;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.*;
/**
*
* @author VipinRajan
*/
public class View extends javax.swing.JFrame {
public JFrame frame = new JFrame();
protected JButton btnViewVideos = new JButton("View All Videos in Database");
protected JButton btnAddVideos = new JButton("Add Video into Database");
protected JButton btnSubmitVideos = new JButton("Submit");
protected JTextField txtVideoTitle = new JTextField(10);
protected JTextField txtURL = new JTextField(10);
protected JTextField txtDesc = new JTextField(10);
protected JLabel lblVideoTitle = new JLabel("Video Title: ");
protected JLabel lblURL = new JLabel("URL: ");
protected JLabel lblDesc = new JLabel("Description: ");
public static JLabel lblError = new JLabel("Error! The video was not saved into the database!");
public static JTable database = new JTable();
public static DefaultTableModel datamodel1;
public JScrollPane jsp;
int sx=frame.getSize().width;
int sy=frame.getSize().height;
/**
* Creates new form View
*/
public View() {
initComponents();
errUserLogin.setVisible(false);
errPassLogin.setVisible(false);
errUserSignup.setVisible(false);
errPassSignup.setVisible(false);
frame.setLocation(448,183);
frame.setSize(449,367);
frame.setVisible(false);
frame.setLayout(new FlowLayout());
frame.add(btnViewVideos);
frame.add(btnAddVideos);
frame.add(database);
database.setModel(new DefaultTableModel(new Object [][] {}, new String[] {"Video Title","URL","Description"}));
jsp = new JScrollPane(database);
frame.add(jsp);
jsp.setViewportView(database);
jsp.setVisible(true);
datamodel1 = (DefaultTableModel) database.getModel();
database.setVisible(false);
frame.add(lblVideoTitle).setVisible(false);
frame.add(txtVideoTitle).setVisible(false);
frame.add(lblURL).setVisible(false);
frame.add(txtURL).setVisible(false);
frame.add(lblDesc).setVisible(false);
frame.add(txtDesc).setVisible(false);
frame.add(btnSubmitVideos).setVisible(false);
frame.add(lblError).setVisible(false);
lblError.setForeground(Color.red);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
Controller controller = new Controller();
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblPassSignup1 = new javax.swing.JLabel();
pwdUserSignup1 = new javax.swing.JPasswordField();
lblUserSignup = new javax.swing.JLabel();
lblLogin = new javax.swing.JLabel();
txtUserSignup = new javax.swing.JTextField();
lblUserLogin = new javax.swing.JLabel();
lblPassLogin = new javax.swing.JLabel();
txtUserLogin = new javax.swing.JTextField();
lblPassSignup2 = new javax.swing.JLabel();
pwdUserSignup2 = new javax.swing.JPasswordField();
lblTitle = new javax.swing.JLabel();
btnSignup = new javax.swing.JButton();
lblCreateAccount = new javax.swing.JLabel();
btnLogin = new javax.swing.JButton();
pwdUserLogin = new javax.swing.JPasswordField();
errUserLogin = new javax.swing.JLabel();
errPassLogin = new javax.swing.JLabel();
errUserSignup = new javax.swing.JLabel();
errPassSignup = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblPassSignup1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblPassSignup1.setText("Password:");
lblUserSignup.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblUserSignup.setText("Username:");
lblLogin.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
lblLogin.setText("Login");
lblUserLogin.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblUserLogin.setText("Username:");
lblPassLogin.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblPassLogin.setText("Password:");
lblPassSignup2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lblPassSignup2.setText("Confirm Password:");
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblTitle.setText("Online Videos URL Database");
btnSignup.setText("Signup");
lblCreateAccount.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
lblCreateAccount.setText("Create an account");
btnLogin.setText("Login");
errUserLogin.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
errUserLogin.setForeground(new java.awt.Color(255, 0, 0));
errUserLogin.setText("Username Does not exist!");
errPassLogin.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
errPassLogin.setForeground(new java.awt.Color(255, 0, 0));
errPassLogin.setText("Wrong Password!");
errUserSignup.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
errUserSignup.setForeground(new java.awt.Color(255, 0, 0));
errUserSignup.setText("Username already exist!");
errPassSignup.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
errPassSignup.setForeground(new java.awt.Color(255, 0, 0));
errPassSignup.setText("Password Does not match!");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(lblLogin))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(lblUserLogin)
.addGap(10, 10, 10)
.addComponent(txtUserLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(errUserLogin))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(lblPassLogin)
.addGap(10, 10, 10)
.addComponent(pwdUserLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(errPassLogin))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(lblCreateAccount))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(lblUserSignup)
.addGap(10, 10, 10)
.addComponent(txtUserSignup, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(errUserSignup))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(lblPassSignup1)
.addGap(10, 10, 10)
.addComponent(pwdUserSignup1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(lblPassSignup2)
.addGap(10, 10, 10)
.addComponent(pwdUserSignup2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(errPassSignup))
.addGroup(layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(btnSignup, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addComponent(lblTitle)))
.addGap(29, 29, 29))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(lblTitle)
.addGap(11, 11, 11)
.addComponent(lblLogin)
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblUserLogin))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtUserLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(errUserLogin)))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblPassLogin))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pwdUserLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(errPassLogin)))
.addGap(6, 6, 6)
.addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(lblCreateAccount)
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblUserSignup))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtUserSignup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(errUserSignup)))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblPassSignup1))
.addComponent(pwdUserSignup1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(lblPassSignup2))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pwdUserSignup2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(errPassSignup)))
.addGap(6, 6, 6)
.addComponent(btnSignup, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
void btnSignupActionListener(ActionListener signup) {
btnSignup.addActionListener(signup);
}
void btnLoginActionListener(ActionListener login) {
btnLogin.addActionListener(login);
}
protected String gettxtUserLogin() {
return txtUserLogin.getText();
}
protected char[] getpwdUserLogin() {
return pwdUserLogin.getPassword();
}
protected char[] getpwdUserSignup1() {
return pwdUserSignup1.getPassword();
}
protected char[] getpwdUserSignup2() {
return pwdUserSignup2.getPassword();
}
void btnViewVideosActionListener(ActionListener viewvideos) {
btnViewVideos.addActionListener(viewvideos);
}
void btnAddVideosActionListener(ActionListener addvideos) {
btnAddVideos.addActionListener(addvideos);
}
void btnSubmitVideosActionListener(ActionListener addvideos) {
btnSubmitVideos.addActionListener(addvideos);
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
protected javax.swing.JButton btnLogin;
protected javax.swing.JButton btnSignup;
public javax.swing.JLabel errPassLogin;
public javax.swing.JLabel errPassSignup;
public javax.swing.JLabel errUserLogin;
public javax.swing.JLabel errUserSignup;
public javax.swing.JLabel lblCreateAccount;
public javax.swing.JLabel lblLogin;
public javax.swing.JLabel lblPassLogin;
public javax.swing.JLabel lblPassSignup1;
public javax.swing.JLabel lblPassSignup2;
public javax.swing.JLabel lblTitle;
public javax.swing.JLabel lblUserLogin;
public javax.swing.JLabel lblUserSignup;
protected javax.swing.JPasswordField pwdUserLogin;
protected javax.swing.JPasswordField pwdUserSignup1;
protected javax.swing.JPasswordField pwdUserSignup2;
protected javax.swing.JTextField txtUserLogin;
protected javax.swing.JTextField txtUserSignup;
// End of variables declaration//GEN-END:variables
}
| true |
6b733689d4d0b08be6a170b9675ec39b84cded26 | Java | lxinghui/situ | /src/main/java/service/Market_Service.java | UTF-8 | 249 | 1.695313 | 2 | [] | no_license | package service;
import entity.Market;
import utils.SearchInfo;
public interface Market_Service extends Basic_Service<Market> {
public int getCount();
public Market selectJson(SearchInfo info);
public void updateJson(Market a);
}
| true |
c8f255bfe7bdac5fc1b72a30bdfb7d0fce774f93 | Java | nabind/prism_test | /INORS/AESDecryptionUtility/src/com/drc/util/ApplicationConstants.java | UTF-8 | 1,215 | 1.53125 | 2 | [] | no_license | package com.drc.util;
public class ApplicationConstants {
public static final String AES_DECRYPTION_PROPERTIES_FILE = "aesDecryption.properties";
public static final String LOCAL_AES_DECRYPTION_PROPERTIES_FILE = "properties/aesDecryption.properties";
public static final String XML_FILE_PATH_KEY = "XML_FILE_PATH";
public static final String PRIVATEKEY_KEY = "PRIVATE_KEY";
public static final String DEMO_ENCRYPTED_ATTRIBUTE_KEY = "DEMO_ENCRYPTED_ATTR";
public static final String LOG4J_FILE_APPENDER_KEY = "LOG4J_FILE_APPENDER_FILE";
public static final String LOG4J_FILE_THRESHOLD_KEY = "LOG4J_FILE_THRESHOLD_KEY";
public static final String CANDIDATE_TAG = "Candidate";
public static final String DEMOGRAPHIC_TAG = "Demographic";
public static final String CANDIDATE_ID_ATTRIBUTE = "candidateID";
public static final String DECRYPTED_FILE_SUFFIX = ".DECRYPTED";
public static final String SUFFIX = ".properties";
public static final String XSD_FILE = "XSD_FILE_PATH";
public static final boolean LOAD_AS_RESOURCE_BUNDLE = false;
public static final boolean THROW_EXCEPTION_ON_LOAD_FAILURE = true;
public static final String VALIDATE_SSN_ATTR_KEY = "VALIDATE_SSN_ATTR";
}
| true |
5cdd12dc8aabb9aafd15b8b92e31f626bb16b8a3 | Java | Ygyeong/semi | /src/dto/BoardDTO.java | UTF-8 | 1,450 | 2.484375 | 2 | [] | no_license | package dto;
import java.sql.Date;
public class BoardDTO {
private int board_seq;
private String id;
private String title;
private String content;
private Date write_date;
private int view_count;
private String notice;
public BoardDTO() {
super();
}
public BoardDTO(int board_seq, String id, String title, String content, Date write_date, int view_count,
String notice) {
super();
this.board_seq = board_seq;
this.id = id;
this.title = title;
this.content = content;
this.write_date = write_date;
this.view_count = view_count;
this.notice = notice;
}
public int getBoard_seq() {
return board_seq;
}
public void setBoard_seq(int board_seq) {
this.board_seq = board_seq;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getWrite_date() {
return write_date;
}
public void setWrite_date(Date write_date) {
this.write_date = write_date;
}
public int getView_count() {
return view_count;
}
public void setView_count(int view_count) {
this.view_count = view_count;
}
public String getNotice() {
return notice;
}
public void setNotice(String notice) {
this.notice = notice;
}
}
| true |
4859a332e3678cc0b8a4dcd6eb1c02d556750ea3 | Java | azizmeiman/hajj-permit-demo-app | /src/main/java/com/example/hajjpermitdemoapp/controllers/UserController.java | UTF-8 | 868 | 2.171875 | 2 | [] | no_license | package com.example.hajjpermitdemoapp.controllers;
import com.example.hajjpermitdemoapp.entities.User;
import com.example.hajjpermitdemoapp.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/user")
public Page<User> getUser (Pageable pageable){
return userService.getUser(pageable);
}
@PostMapping("/user")
public User createUser (@Valid @RequestBody User user){
return userService.createUser(user);
}
@DeleteMapping("/user")
public void deleteUser (){
userService.deleteUser();
}
}
| true |
71c27dcdf05d2d62b922047ede05ad73dc3c6de7 | Java | MarkoRadunovic/MavenCommonMuseum | /src/test/java/rs/ac/bg/student/marko/MavenCommonMuseum/domain/KustosTest.java | UTF-8 | 3,590 | 2.59375 | 3 | [] | no_license | package rs.ac.bg.student.marko.MavenCommonMuseum.domain;
import static org.junit.jupiter.api.Assertions.*;
import java.sql.ResultSet;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.Mock;
import org.mockito.Mockito;
class KustosTest {
Kustos k;
@BeforeEach
void setUp() throws Exception {
k = new Kustos();
}
@AfterEach
void tearDown() throws Exception {
k = null;
}
@Mock
ResultSet resultSet;
@Test
void testGetList() {
try {
resultSet = Mockito.mock(ResultSet.class);
Mockito.when(resultSet.getLong("specijalnostId")).thenReturn(15l);
Mockito.when(resultSet.getString("oblast")).thenReturn("oblast");
Mockito.when(resultSet.getLong("kustosId")).thenReturn(155l);
Mockito.when(resultSet.getString("adresa")).thenReturn("a");
Mockito.when(resultSet.getInt("godine")).thenReturn(28);
Mockito.when(resultSet.getString("ime")).thenReturn("m");
Mockito.when(resultSet.getString("prezime")).thenReturn("r");
Mockito.when(resultSet.next()).thenReturn(true).thenReturn(false);
List<DomainObject> kustosi= k.getList(resultSet);
Kustos k= (Kustos) kustosi.get(0);
assertNotNull(kustosi);
assertNotNull(k);
assertEquals("m", k.getIme());
assertEquals("a", k.getAdresa());
assertEquals(28, k.getGodine());
assertEquals("r", k.getPrezime());
assertEquals(15l, k.getSpecijalnost().getSpecijalnostId());
assertEquals("oblast", k.getSpecijalnost().getOblast());
assertEquals(155l, k.getKustosId());
}catch(Exception e){
e.printStackTrace();
}
}
@Test
void testGetQueryForDelete() {
assertThrows(UnsupportedOperationException.class, () -> k.getQueryForDelete());
}
@Test
void testSetId() {
k.setId(15l);
assertEquals(15l, k.getKustosId());
}
@Test
void testKustos() {
k = new Kustos();
assertNotNull(k);
}
@Test
void testKustosLongStringStringIntStringSpecijalnost() {
Specijalnost s = new Specijalnost(15,"spec1");
k = new Kustos(15l, "m", "r", 28, "a", s);
assertNotNull(k);
assertEquals(15l, k.getKustosId());
assertEquals("m", k.getIme());
assertEquals("r", k.getPrezime());
assertEquals(28, k.getGodine());
assertEquals("a", k.getAdresa());
assertEquals(s, k.getSpecijalnost());
}
@Test
void testSetKustosId() {
k.setKustosId(15l);
assertEquals(15l, k.getKustosId());
}
@Test
void testSetIme() {
k.setIme("m");
assertEquals("m", k.getIme());
}
@Test
void testSetPrezime() {
k.setPrezime("m");
assertEquals("m", k.getPrezime());
}
@Test
void testSetGodine() {
k.setGodine(28);
assertEquals(28, k.getGodine());
}
@Test
void testSetAdresa() {
k.setAdresa("m");
assertEquals("m", k.getAdresa());
}
@Test
void testSetSpecijalnost() {
Specijalnost s = new Specijalnost(15, "s");
k.setSpecijalnost(s);
assertEquals(s, k.getSpecijalnost());
}
@ParameterizedTest
@CsvSource({
"1, 2, false",
"1, 1, true",
"12, 12, true",
"6, 4, false"
})
void testEqualsObject(String id1, String id2, boolean eq) {
k.setKustosId(Long.valueOf(id1));
Kustos k1 = new Kustos();
k1.setKustosId(Long.valueOf(id2));
assertEquals(eq, k.equals(k1));
}
@Test
void testToString() {
k.setIme("m");
k.setPrezime("r");
assertEquals("m r", k.toString());
}
}
| true |
4ac294b6a2b2dd16be564ab9bbde96704ab3c43b | Java | Aetra/java-1-class-demos | /week6-objects-classes/week6/dogs/UntrainedDog.java | UTF-8 | 218 | 2.625 | 3 | [
"MIT"
] | permissive | package dogs;
public class UntrainedDog extends Dog {
public UntrainedDog() {
// TODO Auto-generated constructor stub
}
public String rollover() {
return getName() + " looks at you and does nothing";
}
}
| true |
1ff724c0b9fd8631fc6fec4aeb6b5c04b77a61a5 | Java | J-karthick/JAVA-concepts | /RangeExceedsException.java | UTF-8 | 103 | 2.15625 | 2 | [] | no_license |
class RangeExceedsException extends Exception{
RangeExceedsException(String s){
super(s);
}
} | true |
7d59fb7e1b49efb479782c47bf0d441071901081 | Java | kanghq/ChatRobot | /src/com/hqkang/ChatRobot/Sequence/Segment.java | UTF-8 | 298 | 1.929688 | 2 | [] | no_license | package com.hqkang.ChatRobot.Sequence;
public class Segment {
public String word;
public String endChar;
public String lastChar;
public double cost;
public String part;
public final static String START_SIGN = "<< STARTING >>";
public final static String END_SIGN = "<< ENDING >>";
} | true |
377ef0895313762abbd949f2db0bb44bd96e8252 | Java | viruJavi/prices | /prices/src/main/java/com/inditex/prueba/prices/utils/ObjectEntityMapper.java | UTF-8 | 762 | 2.1875 | 2 | [] | no_license | package com.inditex.prueba.prices.utils;
import com.inditex.prueba.prices.model.PriceResponse;
import com.inditex.prueba.prices.model.entity.Price;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.stereotype.Component;
@Component
public class ObjectEntityMapper {
private MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
private MapperFacade mapper = mapperFactory.getMapperFacade();
public PriceResponse toResponse(Price price){
return mapper.map(price, PriceResponse.class);
}
public Price toEntity(PriceResponse priceResponse){
return mapper.map(priceResponse, Price.class);
}
}
| true |
c2bfa8ca4b3f523d4eef51364a5475acbe9e8626 | Java | Yarin78/yal | /java/test/yarin/yal/graph/TestRootedTree.java | UTF-8 | 2,078 | 2.828125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | package yarin.yal.graph;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class TestRootedTree {
@Test
public void testTreeLCA() {
Random r = new Random(0);
for (int i = 0; i < 10; i++) {
int N = 30000 + r.nextInt(10000);
int[] perm = new int[N];
for (int j = 0; j < N; j++) {
perm[j] = j;
}
for (int j = 0; j < N; j++) {
int swap = j + r.nextInt(N-j);
int tmp = perm[j];
perm[j] = perm[swap];
perm[swap] = tmp;
}
Graph g = new Graph(N);
for (int j = 1; j < N; j++) {
int a = r.nextInt(j);
g.addEdge(perm[a], perm[j]);
}
RootedTree tree = new RootedTree(g.getNode(perm[0]));
for (int j = 0; j < 100; j++) {
int a = r.nextInt(N), b = r.nextInt(N);
RootedTree.Node p = tree.getNode(a), q = tree.getNode(b);
// Naive solution
RootedTree.Node pp = p, qq = q;
List<RootedTree.Node> ptrail = new ArrayList<RootedTree.Node>(), qtrail = new ArrayList<RootedTree.Node>();
while (pp != null) {
ptrail.add(pp);
pp = pp.getParent();
}
while (qq != null) {
qtrail.add(qq);
qq = qq.getParent();
}
Collections.reverse(ptrail);
Collections.reverse(qtrail);
int k = 0;
while (k+1 < ptrail.size() && k+1 < qtrail.size() && ptrail.get(k+1) == qtrail.get(k+1)) {
k++;
}
RootedTree.Node expected = ptrail.get(k);
RootedTree.Node lca = tree.getLowestCommonAncestor(p, q);
Assert.assertSame(lca, expected);
}
}
}
}
| true |
7f9b7bea4de2ca079746bff3fa4d0f8f6147e9e8 | Java | phlocbg/phloc-commons | /phloc-commons/src/main/java/com/phloc/commons/annotations/CustomizingAPI.java | UTF-8 | 1,255 | 2.5 | 2 | [] | no_license | package com.phloc.commons.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Documentation measure to denote all classes or methods which are public JAVA
* APIs (PublicAPI) explicitly provided for customizers. The CustomizingAPI
* annotation should be used for all basic public services and important classes
* a customizer needs to access. Like public APIs, CustomizingAPIs must not be
* changed in terms of removed or renamed methods or changed method signature.
* Only new methods may be added. Methods that should be removed are to be
* marked as deprecated (using the <code>{@literal @}deprecated</code>
* annotation) and can be removed in a later release.
*
* @author Boris Gregorcic
*/
@Retention (RetentionPolicy.RUNTIME)
@Target ({ ElementType.TYPE,
ElementType.FIELD,
ElementType.METHOD,
ElementType.PARAMETER,
ElementType.CONSTRUCTOR,
ElementType.LOCAL_VARIABLE,
ElementType.ANNOTATION_TYPE,
ElementType.PACKAGE })
@Documented
public @interface CustomizingAPI
{
String value() default "";
}
| true |
0eb7feb54487578a3b42ce00e0306f1192e279f9 | Java | JohnnyFloyd/komunikator | /klient/src/ListaKontaktow.java | UTF-8 | 4,539 | 2.5625 | 3 | [] | no_license | import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListModel;
public class ListaKontaktow extends JList implements MouseListener
{
DefaultListModel kontakty = new DefaultListModel();
int licznikKonwersacji = 0;
GlowneOkno parent;
Kontakt kontaktJA;
public ListaKontaktow(GlowneOkno parent, Kontakt kontaktJA, DefaultListModel kontakty)
{
super(kontakty);
this.kontakty = kontakty;
this.parent = parent;
this.kontaktJA = kontaktJA;
this.setVisibleRowCount(4);
this.setCellRenderer(new ZnajomiCellRenderer());
addMouseListener(this);
//wczytajDane();
}
public ListaKontaktow(ListModel dataModel)
{
super(dataModel);
this.setCellRenderer(new ZnajomiCellRenderer());
}
public void ustawStanyKontaktow(Map<Integer, Integer> mapa)
{
int licznik = 0;
Set<Integer> zbiorKluczy = mapa.keySet();
for (int id : zbiorKluczy)
{
ustawStan(id, mapa.get(id));
}
}
private void ustawStan(int id, Integer status)
{
Kontakt kontakt;
for (int i = 0; i < kontakty.size(); i++)
{
kontakt = (Kontakt) kontakty.get(i);
if (kontakt.getId() == id)
{
if (status == 0)
kontakt.setOnline(false);
else
kontakt.setOnline(true);
}
}
}
public String zwrocNick(int idKontaktu)
{
Kontakt kontakt;
for (int i = 0; i < kontakty.size(); i++)
{
kontakt = (Kontakt) kontakty.get(i);
if (kontakt.getId() == idKontaktu)
{
return kontakt.getNazwa();
}
}
return "Nieznany " + String.valueOf(idKontaktu);
}
public Kontakt zwrocZaznaczonyKontakt()
{
int numer = this.getSelectedIndex();
Kontakt kontakt = (Kontakt) this.kontakty.get(numer);
return kontakt;
}
public void zmienZaznaczonyNick(String ostatecznyNick)
{
int numer = this.getSelectedIndex();
Kontakt kontakt = (Kontakt) this.kontakty.get(numer);
kontakt.setNazwa(ostatecznyNick);
}
public void dodajKontakt(String nazwa, int id)
{
int rozmiar;
Kontakt nowyKontakt = new Kontakt(nazwa, id);
rozmiar = kontakty.getSize();
kontakty.add(rozmiar, nowyKontakt);
}
public void dodajKontakt(Kontakt osoba)
{
int rozmiar = kontakty.getSize();
kontakty.add(rozmiar, osoba);
}
public void usunKontakt()
{
int n = getSelectedIndex();
kontakty.remove(n);
}
public void usunKontakt(int id)
{
for (int i = 0; i < kontakty.getSize(); i++)
{
if (((Kontakt) kontakty.get(i)).getId() == id)
{
kontakty.remove(i);
break;
}
}
}
public DefaultListModel zwrocKontakty()
{
return kontakty;
}
@Override
public void mouseClicked(MouseEvent arg0)
{
if (arg0.getClickCount() < 2)
return;
int numer = this.locationToIndex(arg0.getPoint());
Kontakt osoba = (Kontakt) kontakty.get(numer);
if (!osoba.czyKonwersacja())
{
osoba.setKonwersacja(true);
this.parent.dodajKarteRozmowy(osoba);
this.licznikKonwersacji++;
}
else
{
this.parent.ustawAktualnaRozmowa(osoba);
}
}
@Override
public void mouseEntered(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
}
| true |