hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
list | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
list | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
list | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9242391f91107aea86ebfd5328a17054dffda799
| 9,534 |
java
|
Java
|
alert-service/src/main/java/net/opentsdb/horizon/service/ContactService.java
|
OpenTSDB/opentsdb-horizon-config
|
ef836b4f4924f7c1bd15ac8163d20dfc9adbe256
|
[
"Apache-2.0"
] | 3 |
2021-06-24T23:37:16.000Z
|
2022-02-24T06:49:01.000Z
|
alert-service/src/main/java/net/opentsdb/horizon/service/ContactService.java
|
OpenTSDB/opentsdb-horizon-config
|
ef836b4f4924f7c1bd15ac8163d20dfc9adbe256
|
[
"Apache-2.0"
] | 2 |
2021-12-16T08:38:37.000Z
|
2021-12-17T08:20:45.000Z
|
alert-service/src/main/java/net/opentsdb/horizon/service/ContactService.java
|
OpenTSDB/opentsdb-horizon-config
|
ef836b4f4924f7c1bd15ac8163d20dfc9adbe256
|
[
"Apache-2.0"
] | 3 |
2021-06-23T23:01:37.000Z
|
2021-12-15T06:28:34.000Z
| 32.209459 | 96 | 0.684917 | 1,002,175 |
/*
* This file is part of OpenTSDB.
* Copyright (C) 2021 Yahoo.
*
* 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 implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.opentsdb.horizon.service;
import net.opentsdb.horizon.NamespaceCache;
import net.opentsdb.horizon.model.Namespace;
import net.opentsdb.horizon.model.User;
import net.opentsdb.horizon.converter.BaseConverter;
import net.opentsdb.horizon.converter.BatchContactConverter;
import net.opentsdb.horizon.model.Contact;
import net.opentsdb.horizon.model.ContactType;
import net.opentsdb.horizon.store.ContactStore;
import net.opentsdb.horizon.util.Utils;
import net.opentsdb.horizon.view.BatchContact;
import net.opentsdb.horizon.view.EmailContact;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static net.opentsdb.horizon.profile.Utils.validateNamespace;
import static net.opentsdb.horizon.converter.BatchContactConverter.EMAIL;
import static net.opentsdb.horizon.util.Utils.isNullOrEmpty;
public class ContactService
extends AuthenticatedBaseService<BatchContact, List<Contact>, BatchContactConverter> {
public static final String SO_SERVICE = "HZ_CONTACT_SERVICE";
private final NamespaceMemberService namespaceMemberService;
private ContactStore store;
private String adminEmailDomain;
public ContactService(
final ContactStore contactStore,
final AuthService authService,
final NamespaceCache namespaceCache,
final NamespaceMemberService namespaceMemberService,
final String adminEmailDomain) {
super(new BatchContactConverter(), contactStore, authService, namespaceCache);
this.store = contactStore;
this.namespaceMemberService = namespaceMemberService;
this.adminEmailDomain = adminEmailDomain;
}
@Override
protected void doCreate(final List<Contact> contacts, final Connection connection)
throws IOException, SQLException {
if (!contacts.isEmpty()) {
int namespaceId = contacts.get(0).getNamespaceid();
if (namespaceId == BaseConverter.NOT_PASSED) {
throw badRequestException("NamespaceId not found");
}
int[] result = store.createContact(namespaceId, contacts, connection);
for (int i = 0; i < result.length; i++) {
if (result[i] == 0) {
throw internalServerError("One or more creates failed");
}
}
}
}
@Override
protected List<Contact> doUpdate(List<Contact> contacts, Connection connection)
throws IOException, SQLException {
List<Contact> updateContacts = new ArrayList<>();
for (Contact contact : contacts) {
updateContacts.add(getAndUpdate(contact, connection));
}
if (!updateContacts.isEmpty()) {
int[] result = store.update(updateContacts, connection);
for (int i = 0; i < result.length; i++) {
if (result[i] == 0) {
throw internalServerError("One or more updates failed");
}
}
}
return updateContacts;
}
@Override
protected void doDelete(List<Contact> contacts, Connection connection) throws SQLException {
List<Integer> ids = new ArrayList<>();
List<Contact> contactsWithoutIds = new ArrayList<>();
for (int i = 0; i < contacts.size(); i++) {
Contact contact = contacts.get(i);
int id = contact.getId();
if (id > 0) {
ids.add(id);
} else {
contactsWithoutIds.add(contact);
}
}
if (!ids.isEmpty()) {
int[] result = store.deleteByIds(ids, connection);
for (int i = 0; i < result.length; i++) {
if (result[i] == 0) {
throw internalServerError("one or more deletes failed");
}
}
}
if (!contactsWithoutIds.isEmpty()) {
int[] result = store.delete(contactsWithoutIds, connection);
for (int i = 0; i < result.length; i++) {
if (result[i] == 0) {
throw internalServerError("one or more deletes failed");
}
}
}
}
public BatchContact getContactForAlert(long alertId) {
final String format = "Error reading contact for alertId: %d";
return get((connection) -> store.getContactsForAlert(alertId, connection), format, alertId);
}
public BatchContact getContactsByNamespaceAndType(String namespaceName, ContactType type) {
Namespace namespace;
try {
namespace = namespaceCache.getByName(namespaceName);
} catch (Exception e) {
String message = "Error reading namespace with name: " + namespaceName;
logger.error(message, e);
throw internalServerError(message);
}
validateNamespace(namespace, namespaceName);
int namespaceId = namespace.getId();
final String format = "Error reading contact for namespaceId: %d and type: %s";
BatchContact batchContact =
get(
(connection) -> store.getContactByType(namespaceId, type, connection),
format,
namespaceId,
type);
if (type == ContactType.email) {
addAdminContacts(namespaceId, batchContact);
}
return batchContact;
}
public BatchContact getContactsByNamespace(String namespaceName) {
Namespace namespace;
try {
namespace = namespaceCache.getByName(namespaceName);
} catch (Exception e) {
String message = "Error reading namespace with name: " + namespaceName;
logger.error(message, e);
throw internalServerError(message);
}
validateNamespace(namespace, namespaceName);
int namespaceId = namespace.getId();
final String format = "Error reading contact for namespaceId: %d";
BatchContact batchContact =
get(
(connection) -> store.getContactsByNamespace(namespaceId, connection),
format,
namespaceId);
addAdminContacts(namespaceId, batchContact);
return batchContact;
}
private void addAdminContacts(int namespaceId, BatchContact batchContact) {
List<EmailContact> emails = batchContact.getEmail();
if (emails == null) {
emails = new ArrayList<>();
batchContact.setEmail(emails);
}
Set<EmailContact> adminEmails = buildAdminEmailContacts(namespaceId);
for (int i = 0; i < emails.size(); i++) {
EmailContact email = emails.get(i);
if (adminEmails.contains(email)) {
email.setAdmin(true);
adminEmails.remove(email);
}
}
emails.addAll(adminEmails);
}
private Set<EmailContact> buildAdminEmailContacts(final int namespaceId) {
List<User> users = namespaceMemberService.getNamespaceMember(namespaceId);
Set<EmailContact> adminEmails = new HashSet<>();
for (int i = 0; i < users.size(); i++) {
String userId = users.get(i).getUserid();
EmailContact email = new EmailContact();
email.setAdmin(true);
String emailId = userId.substring(userId.indexOf(".") + 1) + adminEmailDomain;
email.setEmail(emailId);
email.setName(emailId);
adminEmails.add(email);
}
return adminEmails;
}
private Contact getAndUpdate(Contact modifiedContact, Connection connection)
throws IOException, SQLException {
int id = modifiedContact.getId();
Contact originalContact = store.getContactById(id, connection);
if (originalContact == null) {
throw notFoundException("Contact not found with id: " + id);
}
updateFields(originalContact, modifiedContact);
return originalContact;
}
private void updateFields(Contact original, Contact modified) {
String newName = modified.getName();
if (!isNullOrEmpty(newName)) {
original.setName(newName);
}
Map<String, String> newDetails = modified.getDetails();
if (!isNullOrEmpty(newDetails)) {
original.setDetails(newDetails);
}
original.setUpdatedBy(modified.getUpdatedBy());
original.setUpdatedTime(modified.getUpdatedTime());
}
@Override
protected void preCreate(List<Contact> contacts) {
contacts.stream()
.filter(contact -> contact.getType().equals(ContactType.email))
.forEach(
contact -> {
if (Utils.isNullOrEmpty(contact.getName())) {
Map<String, String> details = contact.getDetails();
contact.setName(details.get(EMAIL));
}
});
}
@Override
protected void preUpdate(List<Contact> contacts) {
preCreate(contacts);
}
@Override
protected void setCreatorUpdatorIdAndTime(
List<Contact> contacts, String principal, Timestamp timestamp) {
for (Contact contact : contacts) {
contact.setCreatedBy(principal);
contact.setCreatedTime(timestamp);
}
setUpdaterIdAndTime(contacts, principal, timestamp);
}
@Override
protected void setUpdaterIdAndTime(
List<Contact> contacts, String principal, Timestamp timestamp) {
for (Contact contact : contacts) {
contact.setUpdatedBy(principal);
contact.setUpdatedTime(timestamp);
}
}
}
|
92423a911aad7aa1714ba80d153d206eb8941d5f
| 357 |
java
|
Java
|
src/de/uxnr/tsoexpert/game/communication/vo/BuildQueueVO.java
|
mback2k/tsoexpert
|
8a82052f1950caa5acdadd48b558b6dd6180c428
|
[
"MIT"
] | 1 |
2015-10-02T14:28:45.000Z
|
2015-10-02T14:28:45.000Z
|
src/de/uxnr/tsoexpert/game/communication/vo/BuildQueueVO.java
|
mback2k/tsoexpert
|
8a82052f1950caa5acdadd48b558b6dd6180c428
|
[
"MIT"
] | 1 |
2015-11-16T19:18:04.000Z
|
2015-11-16T19:18:04.000Z
|
src/de/uxnr/tsoexpert/game/communication/vo/BuildQueueVO.java
|
mback2k/tsoexpert
|
8a82052f1950caa5acdadd48b558b6dd6180c428
|
[
"MIT"
] | null | null | null | 18.789474 | 48 | 0.742297 | 1,002,176 |
package de.uxnr.tsoexpert.game.communication.vo;
import java.util.List;
import de.uxnr.amf.v3.AMF3_Object;
public class BuildQueueVO extends AMF3_Object {
private List<BuildingVO> buildings;
private int maxCount;
public List<BuildingVO> getBuildings() {
return this.buildings;
}
public int getMaxCount() {
return this.maxCount;
}
}
|
92423ad2846619ce1f32eb4ebceedfb8ad347acf
| 9,965 |
java
|
Java
|
protocol/src/main/java/com/zfoo/protocol/serializer/gd/GenerateGdUtils.java
|
cynthiaZV/zfoo
|
0a7fdd1b4d03f68995a649575e9019112f687aca
|
[
"Apache-2.0"
] | 475 |
2021-05-20T07:27:14.000Z
|
2022-03-31T18:11:59.000Z
|
protocol/src/main/java/com/zfoo/protocol/serializer/gd/GenerateGdUtils.java
|
cynthiaZV/zfoo
|
0a7fdd1b4d03f68995a649575e9019112f687aca
|
[
"Apache-2.0"
] | 2 |
2021-06-19T09:16:10.000Z
|
2022-03-26T07:19:14.000Z
|
protocol/src/main/java/com/zfoo/protocol/serializer/gd/GenerateGdUtils.java
|
cynthiaZV/zfoo
|
0a7fdd1b4d03f68995a649575e9019112f687aca
|
[
"Apache-2.0"
] | 104 |
2021-05-21T07:29:14.000Z
|
2022-03-31T10:07:29.000Z
| 41.869748 | 193 | 0.690115 | 1,002,177 |
/*
* Copyright (C) 2020 The zfoo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.serializer.gd;
import com.zfoo.protocol.generate.GenerateOperation;
import com.zfoo.protocol.generate.GenerateProtocolDocument;
import com.zfoo.protocol.generate.GenerateProtocolFile;
import com.zfoo.protocol.generate.GenerateProtocolPath;
import com.zfoo.protocol.registration.IProtocolRegistration;
import com.zfoo.protocol.registration.ProtocolRegistration;
import com.zfoo.protocol.registration.field.IFieldRegistration;
import com.zfoo.protocol.serializer.reflect.*;
import com.zfoo.protocol.util.ClassUtils;
import com.zfoo.protocol.util.FileUtils;
import com.zfoo.protocol.util.IOUtils;
import com.zfoo.protocol.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import static com.zfoo.protocol.util.FileUtils.LS;
import static com.zfoo.protocol.util.StringUtils.TAB;
/**
* @author jaysunxiao
* @version 3.0
*/
public abstract class GenerateGdUtils {
private static String protocolOutputRootPath = "gdProtocol/";
private static Map<ISerializer, IGdSerializer> gdSerializerMap;
public static IGdSerializer gdSerializer(ISerializer serializer) {
return gdSerializerMap.get(serializer);
}
public static void init(GenerateOperation generateOperation) {
protocolOutputRootPath = FileUtils.joinPath(generateOperation.getProtocolPath(), protocolOutputRootPath);
FileUtils.deleteFile(new File(protocolOutputRootPath));
FileUtils.createDirectory(protocolOutputRootPath);
gdSerializerMap = new HashMap<>();
gdSerializerMap.put(BooleanSerializer.INSTANCE, new GdBooleanSerializer());
gdSerializerMap.put(ByteSerializer.INSTANCE, new GdByteSerializer());
gdSerializerMap.put(ShortSerializer.INSTANCE, new GdShortSerializer());
gdSerializerMap.put(IntSerializer.INSTANCE, new GdIntSerializer());
gdSerializerMap.put(LongSerializer.INSTANCE, new GdLongSerializer());
gdSerializerMap.put(FloatSerializer.INSTANCE, new GdFloatSerializer());
gdSerializerMap.put(DoubleSerializer.INSTANCE, new GdDoubleSerializer());
gdSerializerMap.put(CharSerializer.INSTANCE, new GdCharSerializer());
gdSerializerMap.put(StringSerializer.INSTANCE, new GdStringSerializer());
gdSerializerMap.put(ArraySerializer.INSTANCE, new GdArraySerializer());
gdSerializerMap.put(ListSerializer.INSTANCE, new GdListSerializer());
gdSerializerMap.put(SetSerializer.INSTANCE, new GdSetSerializer());
gdSerializerMap.put(MapSerializer.INSTANCE, new GdMapSerializer());
gdSerializerMap.put(ObjectProtocolSerializer.INSTANCE, new GdObjectProtocolSerializer());
}
public static void clear() {
gdSerializerMap = null;
protocolOutputRootPath = null;
}
public static void createProtocolManager(List<IProtocolRegistration> protocolList) throws IOException {
var list = List.of("gd/buffer/ByteBuffer.gd");
for (var fileName : list) {
var fileInputStream = ClassUtils.getFileFromClassPath(fileName);
var createFile = new File(StringUtils.format("{}/{}", protocolOutputRootPath, StringUtils.substringAfterFirst(fileName, "gd/")));
FileUtils.writeInputStreamToFile(createFile, fileInputStream);
}
// 生成ProtocolManager.gd文件
var gdBuilder = new StringBuilder();
protocolList.stream()
.filter(it -> Objects.nonNull(it))
.forEach(it -> {
var name = it.protocolConstructor().getDeclaringClass().getSimpleName();
var path = GenerateProtocolPath.getProtocolPath(it.protocolId());
gdBuilder.append(StringUtils.format("const {} = preload(\"res://gdProtocol/{}/{}.gd\")", name, path, name)).append(LS);
});
gdBuilder.append(LS);
var protocolManagerStr = StringUtils.bytesToString(IOUtils.toByteArray(ClassUtils.getFileFromClassPath("gd/ProtocolManager.gd")));
gdBuilder.append(protocolManagerStr);
gdBuilder.append("static func initProtocol():").append(LS);
protocolList.stream()
.filter(it -> Objects.nonNull(it))
.forEach(it -> gdBuilder.append(TAB).append(StringUtils.format("protocols[{}] = {}", it.protocolId(), it.protocolConstructor().getDeclaringClass().getSimpleName())).append(LS));
FileUtils.writeStringToFile(new File(StringUtils.format("{}/{}", protocolOutputRootPath, "ProtocolManager.gd")), gdBuilder.toString());
}
public static void createGdProtocolFile(ProtocolRegistration registration) {
// 初始化index
GenerateProtocolFile.index.set(0);
var protocolId = registration.protocolId();
var registrationConstructor = registration.getConstructor();
var protocolClazzName = registrationConstructor.getDeclaringClass().getSimpleName();
var gdBuilder = new StringBuilder();
// 协议的属性生成
gdBuilder.append(protocolClass(registration));
// protocolId
gdBuilder.append(protocolIdField(registration));
// writeObject method
gdBuilder.append(writeObject(registration));
// readObject method
gdBuilder.append(readObject(registration));
var protocolOutputPath = StringUtils.format("{}/{}/{}.gd"
, protocolOutputRootPath
, GenerateProtocolPath.getProtocolPath(protocolId)
, protocolClazzName);
FileUtils.writeStringToFile(new File(protocolOutputPath), gdBuilder.toString());
}
private static String protocolClass(ProtocolRegistration registration) {
var protocolId = registration.getId();
var fields = registration.getFields();
var protocolClazzName = registration.getConstructor().getDeclaringClass().getSimpleName();
var protocolDocument = GenerateProtocolDocument.getProtocolDocument(protocolId);
var docTitle = protocolDocument.getKey();
var docFieldMap = protocolDocument.getValue();
var gdBuilder = new StringBuilder();
if (!StringUtils.isBlank(docTitle)) {
gdBuilder.append(gdDocument(docTitle)).append(LS);
}
for (var field : fields) {
var propertyName = field.getName();
// 生成注释
var doc = docFieldMap.get(propertyName);
if (!StringUtils.isBlank(doc)) {
Arrays.stream(doc.split(LS)).forEach(it -> gdBuilder.append(gdDocument(it)).append(LS));
}
gdBuilder.append(StringUtils.format("var {}", propertyName))
.append(" # ").append(field.getGenericType().getTypeName()) // 生成类型的注释
.append(LS);
}
gdBuilder.append(LS);
return gdBuilder.toString();
}
private static String protocolIdField(ProtocolRegistration registration) {
var protocolId = registration.getId();
var gdBuilder = new StringBuilder();
gdBuilder.append(StringUtils.format("const PROTOCOL_ID = {}", protocolId)).append(LS).append(LS);
return gdBuilder.toString();
}
private static String writeObject(ProtocolRegistration registration) {
var fields = registration.getFields();
var fieldRegistrations = registration.getFieldRegistrations();
var gdBuilder = new StringBuilder();
gdBuilder.append(StringUtils.format("static func write(buffer, packet):")).append(LS);
gdBuilder.append(TAB).append("if (buffer.writePacketFlag(packet)):").append(LS);
gdBuilder.append(TAB + TAB).append("return").append(LS);
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
IFieldRegistration fieldRegistration = fieldRegistrations[i];
gdSerializer(fieldRegistration.serializer()).writeObject(gdBuilder, "packet." + field.getName(), 1, field, fieldRegistration);
}
gdBuilder.append(LS).append(LS);
return gdBuilder.toString();
}
private static String readObject(ProtocolRegistration registration) {
var fields = registration.getFields();
var fieldRegistrations = registration.getFieldRegistrations();
var protocolClazzName = registration.getConstructor().getDeclaringClass().getSimpleName();
var jsBuilder = new StringBuilder();
jsBuilder.append(StringUtils.format("static func read(buffer):")).append(LS);
jsBuilder.append(TAB).append("if (!buffer.readBool()):").append(LS);
jsBuilder.append(TAB + TAB).append("return null").append(LS);
jsBuilder.append(TAB).append(StringUtils.format("var packet = buffer.newInstance({})", registration.protocolId())).append(LS);
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var fieldRegistration = fieldRegistrations[i];
var readObject = gdSerializer(fieldRegistration.serializer()).readObject(jsBuilder, 1, field, fieldRegistration);
jsBuilder.append(TAB).append(StringUtils.format("packet.{} = {}", field.getName(), readObject)).append(LS);
}
jsBuilder.append(TAB).append("return packet").append(LS);
return jsBuilder.toString();
}
private static String gdDocument(String doc) {
return doc.replaceAll("//", "#");
}
}
|
92423b12a26bbb0e02e404afdd852380ceb5cd9d
| 1,335 |
java
|
Java
|
src/main/java/com/brighttalk/channels/reportingapi/client/resource/package-info.java
|
BrightTALK/brighttalk-channel-reporting-api-client
|
541440d6aff9c72002cc272267500caff8176209
|
[
"Apache-2.0"
] | 8 |
2019-09-09T21:37:49.000Z
|
2021-07-02T10:11:31.000Z
|
src/main/java/com/brighttalk/channels/reportingapi/client/resource/package-info.java
|
BrightTALK/brighttalk-channel-reporting-api-client
|
541440d6aff9c72002cc272267500caff8176209
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/brighttalk/channels/reportingapi/client/resource/package-info.java
|
BrightTALK/brighttalk-channel-reporting-api-client
|
541440d6aff9c72002cc272267500caff8176209
|
[
"Apache-2.0"
] | 4 |
2018-05-11T04:42:06.000Z
|
2020-09-26T14:40:46.000Z
| 46.034483 | 118 | 0.776779 | 1,002,178 |
/*
* Copyright 2014-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Package containing the classes which make up the BrightTALK reporting API resource model - the RESTful
* resource-oriented view of the BrightTALK domain. Classes are given the 'Resource' suffix to make it easier to
* use them in conjunction with similarly named domain objects in utilising applications.
*/
// Use a custom JAXB XmlAdapter for unmarshalling integer strings to overcome a bug in the one supplied in the JAXB RI
@XmlJavaTypeAdapter(type = int.class, value = IntegerXmlAdapter.class)
package com.brighttalk.channels.reportingapi.client.resource;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.brighttalk.channels.reportingapi.client.jaxb.IntegerXmlAdapter;
|
92423b62d495fe0ec3575633cc8ddbfd879dde95
| 2,274 |
java
|
Java
|
MulS/src/me/seaeclipse/string/hash/strings/SHA256.java
|
SeaEclipse/muls
|
1171155b8fa72cc4a6148a1a6c10622965954463
|
[
"BSD-3-Clause"
] | null | null | null |
MulS/src/me/seaeclipse/string/hash/strings/SHA256.java
|
SeaEclipse/muls
|
1171155b8fa72cc4a6148a1a6c10622965954463
|
[
"BSD-3-Clause"
] | null | null | null |
MulS/src/me/seaeclipse/string/hash/strings/SHA256.java
|
SeaEclipse/muls
|
1171155b8fa72cc4a6148a1a6c10622965954463
|
[
"BSD-3-Clause"
] | null | null | null | 36.095238 | 78 | 0.735708 | 1,002,179 |
/**
*
License for MulS: BSD 3 Clause
Copyright (c) 4 mar 2020 SeaEclipse. 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, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder 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 HOLDER 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.
*/
package me.seaeclipse.string.hash.strings;
import java.security.MessageDigest;
/**
* @author SeaEclipse
*
*/
public final class SHA256 {
public static String mkSHA256(String input) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
}
|
92423beec068d839a1fd31361aec99dd9a4b8008
| 1,230 |
java
|
Java
|
dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationFactoryFactoryTest.java
|
d2fn/dropwizard
|
f6202ec0a7087f04e3a34ac2c85aeb892e499630
|
[
"Apache-2.0"
] | 4 |
2015-01-09T23:19:56.000Z
|
2020-11-24T17:07:18.000Z
|
dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationFactoryFactoryTest.java
|
bwmeier/dropwizard
|
9ac4b139e98c5fa52e2d92cff012afd3729eb4ac
|
[
"Apache-2.0"
] | null | null | null |
dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationFactoryFactoryTest.java
|
bwmeier/dropwizard
|
9ac4b139e98c5fa52e2d92cff012afd3729eb4ac
|
[
"Apache-2.0"
] | 2 |
2016-11-18T09:06:14.000Z
|
2021-03-17T16:25:21.000Z
| 33.243243 | 139 | 0.731707 | 1,002,180 |
package io.dropwizard.configuration;
import static org.fest.assertions.api.Assertions.assertThat;
import io.dropwizard.configuration.ConfigurationFactoryTest.Example;
import io.dropwizard.jackson.Jackson;
import java.io.File;
import javax.validation.Validation;
import javax.validation.Validator;
import org.junit.Before;
import org.junit.Test;
import com.google.common.io.Resources;
public class ConfigurationFactoryFactoryTest {
private final ConfigurationFactoryFactory<Example> factoryFactory = new DefaultConfigurationFactoryFactory<Example>();
private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
private File validFile;
@Before
public void setUp() throws Exception {
this.validFile = new File(Resources.getResource("factory-test-valid.yml").toURI());
}
@Test
public void createDefaultFactory() throws Exception {
ConfigurationFactory<Example> factory = factoryFactory.create(Example.class, validator, Jackson.newObjectMapper(), "dw");
final Example example = factory.build(validFile);
assertThat(example.getName())
.isEqualTo("Coda Hale");
}
}
|
92423f1700196369b6adb08ea9385e509fd804d3
| 357 |
java
|
Java
|
src/main/java/com/justinschaaf/industrialtech/gui/widgets/SuppliedTooltip.java
|
justinhschaaf/IndustrialTech
|
4a0fca543493bfc01a1edf30fae21a701af88a86
|
[
"MIT"
] | null | null | null |
src/main/java/com/justinschaaf/industrialtech/gui/widgets/SuppliedTooltip.java
|
justinhschaaf/IndustrialTech
|
4a0fca543493bfc01a1edf30fae21a701af88a86
|
[
"MIT"
] | null | null | null |
src/main/java/com/justinschaaf/industrialtech/gui/widgets/SuppliedTooltip.java
|
justinhschaaf/IndustrialTech
|
4a0fca543493bfc01a1edf30fae21a701af88a86
|
[
"MIT"
] | null | null | null | 19.833333 | 54 | 0.753501 | 1,002,181 |
package com.justinschaaf.industrialtech.gui.widgets;
import net.minecraft.text.Text;
import java.util.function.Supplier;
public interface SuppliedTooltip {
void setTooltipCallback(Supplier<Text> tooltip);
Supplier<Text> getTooltipCallback();
default void withTooltip(Supplier<Text> tooltip) {
setTooltipCallback(tooltip);
}
}
|
92423f5cdd12aea606cbba14b195bc0327e3ab57
| 1,274 |
java
|
Java
|
jspringbot-csv/src/main/java/org/jspringbot/keyword/csv/DisjunctionEndCSVRestriction.java
|
siegcollado/jspringbot-libraries
|
c0babdaaad0e255183853a0d328155e32f4714e0
|
[
"Apache-2.0"
] | null | null | null |
jspringbot-csv/src/main/java/org/jspringbot/keyword/csv/DisjunctionEndCSVRestriction.java
|
siegcollado/jspringbot-libraries
|
c0babdaaad0e255183853a0d328155e32f4714e0
|
[
"Apache-2.0"
] | null | null | null |
jspringbot-csv/src/main/java/org/jspringbot/keyword/csv/DisjunctionEndCSVRestriction.java
|
siegcollado/jspringbot-libraries
|
c0babdaaad0e255183853a0d328155e32f4714e0
|
[
"Apache-2.0"
] | null | null | null | 34.432432 | 131 | 0.755102 | 1,002,182 |
/*
* Copyright (c) 2012. JSpringBot. All Rights Reserved.
*
* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The JSpringBot 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.jspringbot.keyword.csv;
import org.jspringbot.KeywordInfo;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
@KeywordInfo(name = "Disjunction End CSV Restriction", description = "End of disjunction or restriction for the current criteria.")
public class DisjunctionEndCSVRestriction extends AbstractCSVKeyword {
@Override
public Object execute(Object[] params) throws IOException {
helper.endDisjunction();
return null;
}
}
|
92424063360d06dc0a4b1453da536fe53b30c5eb
| 113 |
java
|
Java
|
src/main/java/com/bilitech/yilimusic/music/enums/PlayListStatus.java
|
programmer-yili/yili-music
|
687a1db337923ff134edf890ef048a989b87e9d2
|
[
"MIT"
] | 31 |
2021-12-15T01:59:10.000Z
|
2022-03-31T08:39:09.000Z
|
src/main/java/com/bilitech/yilimusic/music/enums/PlayListStatus.java
|
programmer-yili/yili-music
|
687a1db337923ff134edf890ef048a989b87e9d2
|
[
"MIT"
] | 1 |
2021-12-27T15:21:29.000Z
|
2021-12-27T15:21:29.000Z
|
src/main/java/com/bilitech/yilimusic/music/enums/PlayListStatus.java
|
programmer-yili/yili-music
|
687a1db337923ff134edf890ef048a989b87e9d2
|
[
"MIT"
] | 5 |
2021-12-24T05:26:41.000Z
|
2022-03-08T03:15:32.000Z
| 14.125 | 43 | 0.716814 | 1,002,183 |
package com.bilitech.yilimusic.music.enums;
public enum PlayListStatus {
DRAFT,
PUBLISHED,
CLOSED
}
|
924240edac9d044069b3b2e9f3b5fc351f4414a6
| 2,678 |
java
|
Java
|
ruoyi-common/ruoyi-common-swagger/src/main/java/com/ruoyi/common/swagger/SwaggerConfig.java
|
Random-pro/caes-cloud
|
91312e2867a1f484a4e7cf2e078679f02cb0856b
|
[
"MIT"
] | 347 |
2019-08-09T10:13:42.000Z
|
2022-03-28T09:00:57.000Z
|
ruoyi-common/ruoyi-common-swagger/src/main/java/com/ruoyi/common/swagger/SwaggerConfig.java
|
standonthetop/ruoyi-cloud
|
105af4ee4b8852b50f21bbcb7d396812ba3c0ec6
|
[
"MIT"
] | 31 |
2020-04-21T08:29:12.000Z
|
2021-05-21T05:59:26.000Z
|
ruoyi-common/ruoyi-common-swagger/src/main/java/com/ruoyi/common/swagger/SwaggerConfig.java
|
standonthetop/ruoyi-cloud
|
105af4ee4b8852b50f21bbcb7d396812ba3c0ec6
|
[
"MIT"
] | 207 |
2019-08-11T05:05:29.000Z
|
2022-02-28T08:04:16.000Z
| 38.811594 | 121 | 0.735624 | 1,002,184 |
package com.ruoyi.common.swagger;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
/**
* @ClassName SwaggerConfig
* @PackageName com.ruoyi.system.config
* @Description
* @Author daiz
* @Date 2019/8/16 9:57
* @Version 1.0
*/
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig
{
@Bean(value = "userApi")
@Order(value = 1)
public Docket groupRestApi()
{
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any())
.build().securityContexts(Lists.newArrayList(securityContext()))
.securitySchemes(Lists.<SecurityScheme> newArrayList(apiKey()));
}
private ApiInfo apiInfo()
{
return new ApiInfoBuilder().title("RuoYi Cloud 接口文档").description("springcloud版本的若依")
.contact(new Contact("wind", "", "")).version("1.0.1").build();
}
private ApiKey apiKey()
{
return new ApiKey("TOKEN", "token", "header");
}
private SecurityContext securityContext()
{
return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/.*")).build();
}
List<SecurityReference> defaultAuth()
{
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes));
}
}
|
92424164401e36a0d14b14832002904ff111bf8d
| 710 |
java
|
Java
|
src/main/java/io/devfactory/tag/domain/Tag.java
|
mvmaniac/standard-spring-boot-study
|
f87da22cff8835d4c90f7f1ccfcb5749189b5932
|
[
"MIT"
] | null | null | null |
src/main/java/io/devfactory/tag/domain/Tag.java
|
mvmaniac/standard-spring-boot-study
|
f87da22cff8835d4c90f7f1ccfcb5749189b5932
|
[
"MIT"
] | null | null | null |
src/main/java/io/devfactory/tag/domain/Tag.java
|
mvmaniac/standard-spring-boot-study
|
f87da22cff8835d4c90f7f1ccfcb5749189b5932
|
[
"MIT"
] | null | null | null | 19.189189 | 43 | 0.753521 | 1,002,185 |
package io.devfactory.tag.domain;
import static lombok.AccessLevel.PROTECTED;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
@EqualsAndHashCode(of = "id")
@NoArgsConstructor(access = PROTECTED)
@Getter
@Table(name = "tb_tag")
@Entity
public class Tag {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String title;
private Tag(String title) {
this.title = title;
}
public static Tag of(String title) {
return new Tag(title);
}
}
|
924242351a8a4134299fad9d24474dc6a9f4942b
| 1,081 |
java
|
Java
|
eureka-feign/src/main/java/com/eureka/cloud/eurekafeignhystrixnode1/controller/HelloController.java
|
Willie-lin/eureka-cloud
|
e96c4717d1fdbb5c18b1954caf506df7b626280e
|
[
"MIT"
] | 2 |
2018-09-14T04:42:21.000Z
|
2018-10-25T02:47:07.000Z
|
eureka-feign/src/main/java/com/eureka/cloud/eurekafeignhystrixnode1/controller/HelloController.java
|
willie-lin/eureka-cloud
|
e96c4717d1fdbb5c18b1954caf506df7b626280e
|
[
"MIT"
] | null | null | null |
eureka-feign/src/main/java/com/eureka/cloud/eurekafeignhystrixnode1/controller/HelloController.java
|
willie-lin/eureka-cloud
|
e96c4717d1fdbb5c18b1954caf506df7b626280e
|
[
"MIT"
] | 1 |
2018-10-25T02:46:46.000Z
|
2018-10-25T02:46:46.000Z
| 25.738095 | 71 | 0.73728 | 1,002,186 |
package com.eureka.cloud.eurekafeignhystrixnode1.controller;
import com.eureka.cloud.eurekafeignhystrixnode1.interfaces.HelloRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* Created with IntelliJ IDEA.
*
* @author YuAn
* @Package com.eureka.cloud.eurekafeign.controller
* @auther YuAn
* @Date 2018/9/14
* @Time 18:14
* @Project_name: eureka-cloud
* To change this template use File | Settings | File Templates.
* @Description:
*/
@RestController
public class HelloController {
@Autowired
HelloRemote helloRemote;
public HelloRemote getHelloRemote() {
return helloRemote;
}
public void setHelloRemote(HelloRemote helloRemote) {
this.helloRemote = helloRemote;
}
@GetMapping("/hello/{name}")
public String index(@PathVariable("name") String name){
return helloRemote.hello(name + "!!!");
}
}
|
924242d42f3767501370625f294ed448833ab07c
| 3,069 |
java
|
Java
|
aws-s3-log4j-appender/src/main/java/io/github/technologize/log4j/appender/aws/s3/AwsS3Appender.java
|
databox/fluency-log4j-appender
|
c607983b968eb8465d729d474324f7a54526fcd4
|
[
"Apache-2.0"
] | 1 |
2021-11-01T04:12:54.000Z
|
2021-11-01T04:12:54.000Z
|
aws-s3-log4j-appender/src/main/java/io/github/technologize/log4j/appender/aws/s3/AwsS3Appender.java
|
databox/fluency-log4j-appender
|
c607983b968eb8465d729d474324f7a54526fcd4
|
[
"Apache-2.0"
] | 10 |
2021-08-24T03:14:19.000Z
|
2022-03-31T03:19:48.000Z
|
aws-s3-log4j-appender/src/main/java/io/github/technologize/log4j/appender/aws/s3/AwsS3Appender.java
|
databox/fluency-log4j-appender
|
c607983b968eb8465d729d474324f7a54526fcd4
|
[
"Apache-2.0"
] | 3 |
2021-10-20T02:18:12.000Z
|
2022-03-17T11:39:12.000Z
| 36.105882 | 129 | 0.762138 | 1,002,187 |
/**
* Copyright [2021] [Bharat Gadde]
*
* 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 io.github.technologize.log4j.appender.aws.s3;
import java.io.Serializable;
import java.util.Objects;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Core;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
import io.github.technologize.log4j.appender.fluency.core.Field;
import io.github.technologize.log4j.appender.fluency.core.FluencyAppender;
import io.github.technologize.log4j.appender.fluency.core.FluencyConfig;
/**
* @author Bharat Gadde
*
*/
@Plugin(name = AwsS3Appender.PLUGIN_NAME, category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true)
public class AwsS3Appender extends FluencyAppender {
/**
* Aws S3 Plugin Name
*/
public static final String PLUGIN_NAME = "AwsS3";
/**
* @param name
* @param tag
* @param fields
* @param fluentdConfig
* @param filter
* @param layout
* @param ignoreExceptions
*/
protected AwsS3Appender(String name, String tag, Field[] fields, FluencyConfig fluentdConfig, Filter filter,
Layout<? extends Serializable> layout, String ignoreExceptions) {
super(name, tag, fields, fluentdConfig, filter, layout, ignoreExceptions);
}
/**
* Creates Appender
* @param name
* @param tag
* @param ignoreExceptions
* @param fields
* @param awsS3Config
* @param layout
* @param filter
* @return
*/
@PluginFactory
public static AwsS3Appender createAppender(@PluginAttribute("name") final String name,
@PluginAttribute("tag") @Required(message = "tag is required") final String tag,
@PluginAttribute("ignoreExceptions") final String ignoreExceptions,
@PluginElement(Field.ELEMENT_TYPE) final Field[] fields,
@PluginElement(FluencyConfig.ELEMENT_TYPE) final AwsS3Config awsS3Config,
@PluginElement(Layout.ELEMENT_TYPE) Layout<? extends Serializable> layout,
@PluginElement(Filter.ELEMENT_TYPE) final Filter filter) {
AwsS3Config config = Objects.nonNull(awsS3Config) ? awsS3Config : new AwsS3Config();
return new AwsS3Appender(name, tag, fields, config, filter, layout, ignoreExceptions);
}
}
|
924243dbde0a14d3083efb4bd6e5b8a66a498b1d
| 1,064 |
java
|
Java
|
bundles/com.zeligsoft.base.zdl.domain.staticapi/api-gen/com/zeligsoft/base/zdl/staticapi/Validation/DomainConstraint.java
|
elder4p/CX4CBDDS
|
9f46115f3e4b075ceb4f6692bd9f95410df50895
|
[
"Apache-2.0"
] | null | null | null |
bundles/com.zeligsoft.base.zdl.domain.staticapi/api-gen/com/zeligsoft/base/zdl/staticapi/Validation/DomainConstraint.java
|
elder4p/CX4CBDDS
|
9f46115f3e4b075ceb4f6692bd9f95410df50895
|
[
"Apache-2.0"
] | null | null | null |
bundles/com.zeligsoft.base.zdl.domain.staticapi/api-gen/com/zeligsoft/base/zdl/staticapi/Validation/DomainConstraint.java
|
elder4p/CX4CBDDS
|
9f46115f3e4b075ceb4f6692bd9f95410df50895
|
[
"Apache-2.0"
] | null | null | null | 23.644444 | 101 | 0.786654 | 1,002,188 |
package com.zeligsoft.base.zdl.staticapi.Validation;
import com.zeligsoft.base.zdl.staticapi.core.ZObject;
import com.zeligsoft.base.zdl.staticapi.functions.TypeSelectPredicate;
public interface DomainConstraint extends ZObject {
EvaluationModeKind getEvaluationMode();
void setEvaluationMode(EvaluationModeKind val);
SeverityKind getSeverity();
void setSeverity(SeverityKind val);
String getMessage();
void setMessage(String val);
String getId();
void setId(String val);
ConstraintKind getKind();
void setKind(ConstraintKind val);
Integer getStatusCode();
void setStatusCode(Integer val);
java.util.List<DomainConstraint> getRedefinedConstraint();
void addRedefinedConstraint(DomainConstraint val);
org.eclipse.uml2.uml.Constraint asConstraint();
/**
* A predicate which returns true if the Object is an
* instance of DomainConstraint
*/
static final TypeSelectPredicate<DomainConstraint> type = new TypeSelectPredicate<DomainConstraint>(
"ZDL::Validation::DomainConstraint", //$NON-NLS-1$
DomainConstraint.class);
}
|
92424476f129b2e9d21e35d5b61d7d50ef3d9eb4
| 1,550 |
java
|
Java
|
src/main/java/org/laladev/moneyjinn/sepa/camt/model/common/party/Debtor.java
|
OlliL/moneyjinn-sepa-camt
|
0b5094a875a89bb6a08d1cb40ff1c33b71e2acd4
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/org/laladev/moneyjinn/sepa/camt/model/common/party/Debtor.java
|
OlliL/moneyjinn-sepa-camt
|
0b5094a875a89bb6a08d1cb40ff1c33b71e2acd4
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/org/laladev/moneyjinn/sepa/camt/model/common/party/Debtor.java
|
OlliL/moneyjinn-sepa-camt
|
0b5094a875a89bb6a08d1cb40ff1c33b71e2acd4
|
[
"BSD-2-Clause"
] | null | null | null | 39.794872 | 77 | 0.765464 | 1,002,189 |
//
// Copyright (c) 2015 Oliver Lehmann <[email protected]>
// 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, this list of conditions and the following disclaimer
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
//
package org.laladev.moneyjinn.sepa.camt.model.common.party;
public class Debtor extends AbstractParty {
public Debtor() {
}
public Debtor(final String name) {
super(name);
}
}
|
924244f75a69adc5b6194a1ebd4b9dd8ec264e1a
| 870 |
java
|
Java
|
src/jp/narr/reader/ProgressWebViewClient.java
|
tohateam/narr-code-pad
|
96f85eedffecfb0b384aad2cdb2ac719c74982b8
|
[
"Apache-2.0"
] | null | null | null |
src/jp/narr/reader/ProgressWebViewClient.java
|
tohateam/narr-code-pad
|
96f85eedffecfb0b384aad2cdb2ac719c74982b8
|
[
"Apache-2.0"
] | null | null | null |
src/jp/narr/reader/ProgressWebViewClient.java
|
tohateam/narr-code-pad
|
96f85eedffecfb0b384aad2cdb2ac719c74982b8
|
[
"Apache-2.0"
] | null | null | null | 25.588235 | 71 | 0.683908 | 1,002,190 |
package jp.narr.reader;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;
class ProgressWebViewClient extends WebViewClient {
private ProgressDialog progressDialog;
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
if (progressDialog != null) {
progressDialog.dismiss();
}
progressDialog = null;
super.onPageFinished(view, url);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog = ProgressDialog.show( view.getContext(),
"Please wait...",
"Opening File...",
true );
super.onPageStarted(view, url, favicon);
}
}
|
924245d999e8698a21bbbf12cca6eb19054f1a6a
| 1,412 |
java
|
Java
|
qirk-parent/qirk-main-parent/qirk-services-api/src/main/java/org/wrkr/clb/services/util/exception/ApplicationException.java
|
nydevel/qirk
|
8538826c6aec6bf9de9e59b9d5bd1849e2588c6a
|
[
"MIT"
] | 11 |
2020-11-04T05:58:23.000Z
|
2021-12-17T09:50:05.000Z
|
qirk-parent/qirk-main-parent/qirk-services-api/src/main/java/org/wrkr/clb/services/util/exception/ApplicationException.java
|
nydevel/qirk
|
8538826c6aec6bf9de9e59b9d5bd1849e2588c6a
|
[
"MIT"
] | null | null | null |
qirk-parent/qirk-main-parent/qirk-services-api/src/main/java/org/wrkr/clb/services/util/exception/ApplicationException.java
|
nydevel/qirk
|
8538826c6aec6bf9de9e59b9d5bd1849e2588c6a
|
[
"MIT"
] | 7 |
2020-11-04T15:28:02.000Z
|
2022-03-01T11:31:29.000Z
| 29.416667 | 98 | 0.723796 | 1,002,191 |
package org.wrkr.clb.services.util.exception;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wrkr.clb.services.util.http.JsonStatusCode;
public class ApplicationException extends Exception {
private static final long serialVersionUID = 1871506672523044774L;
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(ApplicationException.class);
private int httpStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
private String jsonStatusCode = JsonStatusCode.INTERNAL_SERVER_ERROR;
public ApplicationException(String message, Throwable cause) {
super(message, cause);
}
public ApplicationException(String code, String message, Throwable cause) {
super(message, cause);
this.jsonStatusCode = code;
}
protected ApplicationException(int httpStatus, String code, String message) {
super(message);
this.httpStatus = httpStatus;
this.jsonStatusCode = code;
}
protected ApplicationException(int httpStatus, String code, String message, Throwable cause) {
super(message, cause);
this.httpStatus = httpStatus;
this.jsonStatusCode = code;
}
public int getHttpStatus() {
return httpStatus;
}
public String getJsonStatusCode() {
return jsonStatusCode;
}
}
|
924245f49e92bd00cd374f4561e9ebaed6222bd0
| 3,213 |
java
|
Java
|
src/main/java/no/ssb/avro/convert/csv/CsvParserSettings.java
|
statisticsnorway/avro-buddy-csv
|
162b65913bdba258a54e063f8998920a6f37a726
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/no/ssb/avro/convert/csv/CsvParserSettings.java
|
statisticsnorway/avro-buddy-csv
|
162b65913bdba258a54e063f8998920a6f37a726
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/no/ssb/avro/convert/csv/CsvParserSettings.java
|
statisticsnorway/avro-buddy-csv
|
162b65913bdba258a54e063f8998920a6f37a726
|
[
"Apache-2.0"
] | null | null | null | 35.7 | 118 | 0.693744 | 1,002,192 |
package no.ssb.avro.convert.csv;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CsvParserSettings {
public static final String DELIMITERS = "delimiters";
public static final String HEADERS = "headers";
public static final String COLUMN_NAME_OVERRIDES = "columnNameOverrides";
public static final String COLUMN_HEADERS_PRESENT = "columnHeadersPresent";
public static final Map<String, String> columnNameOverrides = new HashMap<>();
private final com.univocity.parsers.csv.CsvParserSettings settings;
public CsvParserSettings() {
settings = new com.univocity.parsers.csv.CsvParserSettings();
// default settings:
settings.detectFormatAutomatically();
settings.setHeaderExtractionEnabled(true);
settings.setCommentProcessingEnabled(false);
}
@Override
public String toString() {
return settings.toString();
}
/**
* String with valid csv delimiter characters. This setting is optional, but not specifying this could lead to
* unexpected csv parsing errors, since without this, we have to guess the delimters.
*/
public CsvParserSettings delimiters(String delimiters) {
settings.setDelimiterDetectionEnabled(true, delimiters.toCharArray());
return this;
}
public CsvParserSettings headers(List<String> headers) {
settings.setHeaders(headers.toArray(new String[0]));
return this;
}
public CsvParserSettings columnHeadersPresent(boolean columnHeadersPresent) {
settings.setHeaderExtractionEnabled(columnHeadersPresent);
return this;
}
/**
* Map of column name overrides that should be used in the converted results. If not specified, the converter will
* assume that the target avro schema field name is the same as the source csv column name.
*
* Sometimes a CSV file will have column names that are not valid field names in Avro. In order to prevent errors
* during record assembly, you can specify mapping overrides using this setting.
*/
public Map<String, String> getColumnNameOverrides() {
return this.columnNameOverrides;
}
public CsvParserSettings columnNameOverrides(Map<String, String> columnNameOverrides) {
this.columnNameOverrides.putAll(columnNameOverrides);
return this;
}
public CsvParserSettings configure(Map<String, Object> configMap) {
if (configMap == null) {
return this;
}
if (configMap.containsKey(DELIMITERS)) {
delimiters((String) configMap.get(DELIMITERS));
}
if (configMap.containsKey(HEADERS)) {
headers((List<String>) configMap.get(HEADERS));
}
if (configMap.containsKey(COLUMN_NAME_OVERRIDES)) {
columnNameOverrides((Map<String, String>) configMap.get(COLUMN_NAME_OVERRIDES));
}
if (configMap.containsKey(COLUMN_HEADERS_PRESENT)) {
columnHeadersPresent((Boolean) configMap.get(COLUMN_HEADERS_PRESENT));
}
return this;
}
public com.univocity.parsers.csv.CsvParserSettings getInternal() {
return settings;
}
}
|
924246225fd9b55eacf919fe2485eb2e706a3ef5
| 1,046 |
java
|
Java
|
lab2/src/main/java/cg/lab2/ui/EditButton.java
|
laskovenko1/computer-graphics
|
6a2fcf420dfe9aeb0f0ba761cffd609f112a676e
|
[
"Unlicense"
] | null | null | null |
lab2/src/main/java/cg/lab2/ui/EditButton.java
|
laskovenko1/computer-graphics
|
6a2fcf420dfe9aeb0f0ba761cffd609f112a676e
|
[
"Unlicense"
] | null | null | null |
lab2/src/main/java/cg/lab2/ui/EditButton.java
|
laskovenko1/computer-graphics
|
6a2fcf420dfe9aeb0f0ba761cffd609f112a676e
|
[
"Unlicense"
] | null | null | null | 23.244444 | 79 | 0.614723 | 1,002,193 |
package cg.lab2.ui;
import cg.lab2.Application;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.net.URL;
import java.util.Objects;
class EditButton extends Button {
private final MainWindow mainWindow;
private boolean isEnabled;
EditButton(MainWindow mainWindow) {
this.mainWindow = mainWindow;
isEnabled = true;
changeState();
addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
changeState();
mainWindow.editMode();
}
private void changeState() {
String text;
String iconName;
if (isEnabled) {
text = "Edit mode";
iconName = "edit.png";
} else {
text = "Close edit mode";
iconName = "closeEdit.png";
}
setToolTipText(text);
URL nextURL = Application.class.getClassLoader().getResource(iconName);
setIcon(new ImageIcon(Objects.requireNonNull(nextURL)));
isEnabled = !isEnabled;
}
}
|
92424665e4e5e1c7978ad0a787c15d1a8ffd96d4
| 267 |
java
|
Java
|
app/src/main/java/com/example/android/courtcounter/ScoreViewModel.java
|
pfieffer/Court-Counter
|
946e7b84b72fbd03b597bef08f2760d2dfbb81f7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/android/courtcounter/ScoreViewModel.java
|
pfieffer/Court-Counter
|
946e7b84b72fbd03b597bef08f2760d2dfbb81f7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/android/courtcounter/ScoreViewModel.java
|
pfieffer/Court-Counter
|
946e7b84b72fbd03b597bef08f2760d2dfbb81f7
|
[
"Apache-2.0"
] | null | null | null | 22.25 | 46 | 0.734082 | 1,002,194 |
package com.example.android.courtcounter;
import android.arch.lifecycle.ViewModel;
public class ScoreViewModel extends ViewModel{
// Tracks the score for Team A
public int scoreTeamA = 0;
// Tracks the score for Team B
public int scoreTeamB = 0;
}
|
924246fdc273585f9213e166ec9a6a62dad21434
| 847 |
java
|
Java
|
src/main/java/com/github/blindpirate/gogradle/core/dependency/parse/NotationParser.java
|
LaudateCorpus1/gogradle
|
7706d4e2d18e7c70075930cd5ac3007e09e0ed35
|
[
"Apache-2.0"
] | 663 |
2017-05-04T19:58:33.000Z
|
2022-03-29T21:52:14.000Z
|
src/main/java/com/github/blindpirate/gogradle/core/dependency/parse/NotationParser.java
|
LaudateCorpus1/gogradle
|
7706d4e2d18e7c70075930cd5ac3007e09e0ed35
|
[
"Apache-2.0"
] | 223 |
2017-05-04T11:45:14.000Z
|
2022-03-16T16:54:28.000Z
|
src/main/java/com/github/blindpirate/gogradle/core/dependency/parse/NotationParser.java
|
LaudateCorpus1/gogradle
|
7706d4e2d18e7c70075930cd5ac3007e09e0ed35
|
[
"Apache-2.0"
] | 99 |
2017-06-02T07:52:53.000Z
|
2022-02-25T03:13:41.000Z
| 33.88 | 75 | 0.752066 | 1,002,195 |
/*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.github.blindpirate.gogradle.core.dependency.parse;
import com.github.blindpirate.gogradle.core.dependency.GolangDependency;
public interface NotationParser<T> {
GolangDependency parse(T notation);
}
|
92424749f570c2145798620b3234dde86cd14e33
| 482 |
java
|
Java
|
01_Java Basico/op-sesion-resumen/src/Main.java
|
rikhen/OpenBootcampPublic
|
e9d0edb1dd5104002d832170e9d1c943aacf6351
|
[
"MIT"
] | null | null | null |
01_Java Basico/op-sesion-resumen/src/Main.java
|
rikhen/OpenBootcampPublic
|
e9d0edb1dd5104002d832170e9d1c943aacf6351
|
[
"MIT"
] | null | null | null |
01_Java Basico/op-sesion-resumen/src/Main.java
|
rikhen/OpenBootcampPublic
|
e9d0edb1dd5104002d832170e9d1c943aacf6351
|
[
"MIT"
] | null | null | null | 28.352941 | 67 | 0.724066 | 1,002,196 |
public class Main {
public static void main(String[] args) {
String userDataIn = "userdata.csv";
String userDataOut = "userdataOut.csv";
ProcessFile userFile = new ProcessFile(userDataIn);
ProcessUser userList = new ProcessUser();
userFile.openCSV(userFile.getFilePath());
userList.setUserList(userFile.readCSV(userFile.getFilePath()));
userList.createUser(userList.getUserList());
userFile.writeCSV(userList.getUserList(), userDataOut);
}
}
|
9242492987be72b32d708083c13b0710eed29ede
| 7,007 |
java
|
Java
|
subprojects/core/src/main/java/org/gradle/api/internal/initialization/DefaultScriptHandler.java
|
samyak-jn/gradle
|
8059df93878142fdda203e9fd038dee6e6a8c72e
|
[
"Apache-2.0"
] | 2 |
2018-02-10T18:44:02.000Z
|
2018-03-25T07:17:04.000Z
|
subprojects/core/src/main/java/org/gradle/api/internal/initialization/DefaultScriptHandler.java
|
samyak-jn/gradle
|
8059df93878142fdda203e9fd038dee6e6a8c72e
|
[
"Apache-2.0"
] | 12 |
2020-07-11T15:43:32.000Z
|
2020-10-13T23:39:44.000Z
|
subprojects/core/src/main/java/org/gradle/api/internal/initialization/DefaultScriptHandler.java
|
samyak-jn/gradle
|
8059df93878142fdda203e9fd038dee6e6a8c72e
|
[
"Apache-2.0"
] | 1 |
2022-01-12T12:33:48.000Z
|
2022-01-12T12:33:48.000Z
| 41.461538 | 152 | 0.758955 | 1,002,197 |
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.initialization;
import groovy.lang.Closure;
import org.gradle.api.JavaVersion;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.artifacts.dsl.DependencyLockingHandler;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.attributes.AttributeContainer;
import org.gradle.api.attributes.Bundling;
import org.gradle.api.attributes.LibraryElements;
import org.gradle.api.attributes.Usage;
import org.gradle.api.attributes.java.TargetJvmVersion;
import org.gradle.api.initialization.dsl.ScriptHandler;
import org.gradle.api.internal.DynamicObjectAware;
import org.gradle.api.internal.artifacts.DependencyResolutionServices;
import org.gradle.api.internal.artifacts.JavaEcosystemSupport;
import org.gradle.api.internal.model.NamedObjectInstantiator;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.groovy.scripts.ScriptSource;
import org.gradle.internal.classpath.ClassPath;
import org.gradle.internal.metaobject.BeanDynamicObject;
import org.gradle.internal.metaobject.DynamicObject;
import org.gradle.internal.resource.ResourceLocation;
import org.gradle.util.ConfigureUtil;
import java.io.File;
import java.net.URI;
public class DefaultScriptHandler implements ScriptHandler, ScriptHandlerInternal, DynamicObjectAware {
private static final Logger LOGGER = Logging.getLogger(DefaultScriptHandler.class);
private final ResourceLocation scriptResource;
private final ClassLoaderScope classLoaderScope;
private final ScriptClassPathResolver scriptClassPathResolver;
private final DependencyResolutionServices dependencyResolutionServices;
private final NamedObjectInstantiator instantiator;
private final DependencyLockingHandler dependencyLockingHandler;
// The following values are relatively expensive to create, so defer creation until required
private RepositoryHandler repositoryHandler;
private DependencyHandler dependencyHandler;
private ConfigurationContainer configContainer;
private Configuration classpathConfiguration;
private DynamicObject dynamicObject;
public DefaultScriptHandler(ScriptSource scriptSource, DependencyResolutionServices dependencyResolutionServices, ClassLoaderScope classLoaderScope,
ScriptClassPathResolver scriptClassPathResolver, NamedObjectInstantiator instantiator) {
this.dependencyResolutionServices = dependencyResolutionServices;
this.scriptResource = scriptSource.getResource().getLocation();
this.classLoaderScope = classLoaderScope;
this.scriptClassPathResolver = scriptClassPathResolver;
this.instantiator = instantiator;
this.dependencyLockingHandler = dependencyResolutionServices.getDependencyLockingHandler();
JavaEcosystemSupport.configureSchema(dependencyResolutionServices.getAttributesSchema(), dependencyResolutionServices.getObjectFactory());
}
@Override
public void dependencies(Closure configureClosure) {
ConfigureUtil.configure(configureClosure, getDependencies());
}
@Override
public void addScriptClassPathDependency(Object notation) {
getDependencies().add(ScriptHandler.CLASSPATH_CONFIGURATION, notation);
}
@Override
public ClassPath getScriptClassPath() {
return scriptClassPathResolver.resolveClassPath(classpathConfiguration);
}
@Override
public DependencyHandler getDependencies() {
defineConfiguration();
if (dependencyHandler == null) {
dependencyHandler = dependencyResolutionServices.getDependencyHandler();
}
return dependencyHandler;
}
@Override
public RepositoryHandler getRepositories() {
if (repositoryHandler == null) {
repositoryHandler = dependencyResolutionServices.getResolveRepositoryHandler();
}
return repositoryHandler;
}
@Override
public void repositories(Closure configureClosure) {
ConfigureUtil.configure(configureClosure, getRepositories());
}
@Override
public ConfigurationContainer getConfigurations() {
defineConfiguration();
return configContainer;
}
private void defineConfiguration() {
// Defer creation and resolution of configuration until required. Short-circuit when script does not require classpath
if (configContainer == null) {
configContainer = dependencyResolutionServices.getConfigurationContainer();
}
if (classpathConfiguration == null) {
classpathConfiguration = configContainer.create(CLASSPATH_CONFIGURATION);
AttributeContainer attributes = classpathConfiguration.getAttributes();
attributes.attribute(Usage.USAGE_ATTRIBUTE, instantiator.named(Usage.class, Usage.JAVA_RUNTIME));
attributes.attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, instantiator.named(LibraryElements.class, LibraryElements.JAR));
attributes.attribute(Bundling.BUNDLING_ATTRIBUTE, instantiator.named(Bundling.class, Bundling.EXTERNAL));
attributes.attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, Integer.valueOf(JavaVersion.current().getMajorVersion()));
}
}
@Override
public void dependencyLocking(Closure configureClosure) {
ConfigureUtil.configure(configureClosure, getDependencyLocking());
}
@Override
public DependencyLockingHandler getDependencyLocking() {
return dependencyLockingHandler;
}
@Override
public File getSourceFile() {
return scriptResource.getFile();
}
@Override
public URI getSourceURI() {
return scriptResource.getURI();
}
@Override
public ClassLoader getClassLoader() {
if (!classLoaderScope.isLocked()) {
LOGGER.debug("Eager creation of script class loader for {}. This may result in performance issues.", scriptResource.getDisplayName());
}
return classLoaderScope.getLocalClassLoader();
}
@Override
public DynamicObject getAsDynamicObject() {
if (dynamicObject == null) {
dynamicObject = new BeanDynamicObject(this);
}
return dynamicObject;
}
}
|
924249e499ac6c10f08b2a9bded175e2380f2c30
| 6,529 |
java
|
Java
|
tunnel-client/src/main/java/com/ehensin/tunnel/client/cache/DataFileReadCache.java
|
ehensin/ehensin-tunnel
|
b63de115259297c228a4bdb800de061ce32aa5b7
|
[
"Apache-2.0"
] | null | null | null |
tunnel-client/src/main/java/com/ehensin/tunnel/client/cache/DataFileReadCache.java
|
ehensin/ehensin-tunnel
|
b63de115259297c228a4bdb800de061ce32aa5b7
|
[
"Apache-2.0"
] | null | null | null |
tunnel-client/src/main/java/com/ehensin/tunnel/client/cache/DataFileReadCache.java
|
ehensin/ehensin-tunnel
|
b63de115259297c228a4bdb800de061ce32aa5b7
|
[
"Apache-2.0"
] | null | null | null | 29.677273 | 99 | 0.670394 | 1,002,198 |
/*
* Copyright 2013 The Ehensin Project
*
* The Ehensin Project 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 com.ehensin.tunnel.client.cache;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import com.ehensin.tunnel.client.util.LogUtil;
import com.ehensin.tunnel.client.util.file.EhensinFileReader;
import com.ehensin.tunnel.client.util.file.FileScan;
import com.ehensin.tunnel.client.util.file.FileUtil;
/**
* <pre>
* CLASS:
* 同步数据,通过文件进行缓存,读取文件操作类.
*
* RESPONSIBILITIES:
* High level list of things that the class does
* -)
*
* COLABORATORS:
* List of descriptions of relationships with other classes, i.e. uses, contains, creates, calls...
* -) class relationship
* -) class relationship
*
* USAGE:
* Description of typical usage of class. Include code samples.
*
*
**/
public class DataFileReadCache extends DataFileCache implements
Runnable {
/* 文件扫描器 */
private FileScan scan;
/* 当前正在进行的文件读取 */
private List<EhensinFileReader> readers;
private Map<String, EhensinFileReader> readersMap;
/* 读取文件的数据缓存队列 */
private BlockingQueue<String> dataCache;
/* 同时允许多少个读文件存在 */
private int readThreadSize = 0;
/*备份路径*/
private String backup = null;
public void initForRead(Map<String, String> params) {
LogUtil.debug("init SyncDataFileCache for read", null);
readers = new ArrayList<EhensinFileReader>();
readersMap = new HashMap<String, EhensinFileReader>();
dataCache = new LinkedBlockingQueue<String>();
String dir = params.get("scandir");
backup = params.get("backup");
String extName = params.get("ext") == null ? "sync" : params.get("ext");
readThreadSize = params.get("readthreadsize") == null ? 1 : Integer
.valueOf(params.get("readthreadsize"));
/* 初始化所有有checkpoint的读文件线程,启动读操作 */
List<File> files = FileUtil.retrieveFiles(dir);
Iterator<File> it = files.iterator();
/* 过滤文件: 过滤后缀,过滤是否已经被放到候选列表 */
LogUtil.debug("init SyncDataFileCache, load history file", null);
while (it.hasNext()) {
File file = it.next();
if (file.getName().lastIndexOf("." + "checkpoint") <= 0) {
it.remove();
continue;
}
/* 获取同步文件名 */
LogUtil.debug("get a checkpoint file " + file.getName(), null);
String syncFileName = file.getAbsolutePath().substring(0,
file.getAbsolutePath().lastIndexOf(".checkpoint"))
+"." + extName;
/* 创建读 */
LogUtil.debug("creat a reader for file " + syncFileName, null);
EhensinFileReader reader = new EhensinFileReader(new File(syncFileName),
file.getAbsolutePath());
readers.add(reader);
readersMap.put(file.getName(), reader);
}
/* 初始化scan */
LogUtil.debug("init file scan,dir {0} ext {1}", new String[]{dir,extName});
scan = new FileScan(dir, extName, 1, 1);
Thread t = new Thread(scan);
t.start();
/*等待一下scan初始化*/
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
/* 如果未有未处理完的文件,可以触发scan获取文件 */
if (readers.size() < readThreadSize) {
List<File> candidateFiles = scan.getFiles(readThreadSize
- readers.size());
for (File file : candidateFiles) {
if (readersMap.get(file.getName()) == null) {
/* 创建读 */
EhensinFileReader reader = new EhensinFileReader(file, null);
readers.add(reader);
readersMap.put(file.getName(), reader);
}
}
}
/*启动读线程处理*/
Thread readThread = new Thread(this);
readThread.start();
}
@Override
public List<String> read(int size) {
List<String> readItems = new ArrayList<String>(size);
dataCache.drainTo(readItems, size);
return readItems;
}
@Override
public void checkpoint() {
for (EhensinFileReader reader : readers) {
reader.storeCheckPoint();
}
}
@Override
public void run() {
while (true) {
if (readers.size() <= 0){
File file = scan.getFile();
if (file != null && readersMap.get(file.getName()) == null) {
/* 创建读 */
LogUtil.debug("creat a reader for file" + file.getName(), null);
EhensinFileReader reader = new EhensinFileReader(file, null);
readers.add(reader);
readersMap.put(file.getName(), reader);
}else{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
continue;
}
}
EhensinFileReader reader = readers.get(0);
String line = null;
try {
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.equalsIgnoreCase("end") || line.isEmpty()) {
/* 文件结束处理 */
LogUtil.debug("close reader for handled file " + reader.getFileName(), null);
readers.remove(reader);
readersMap.remove(reader.getFileName());
reader.close();
backup(new File(reader.getFileName()));
/*删除checkpoint文件*/
reader.rmCheckPoint();
scan.remove(reader.getFileName());
break;
}
dataCache.put(line);
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
} catch (IOException e) {
LogUtil.error(DataFileReadCache.class, "read file error : "
+ reader.getFileName(), e);
} catch (InterruptedException e) {
LogUtil.error(DataFileReadCache.class,
"put info to queue error : " + line, e);
}
}
}
private void backup(File file){
/* move file */
String targetPath = backup;
LogUtil.debug(DataFileReadCache.class,
"move old file: {0}, to: {1}.",
new Object[] { file.getName(), targetPath });
boolean moveDone = false;
while (!moveDone) {
try {
FileUtil.moveFile(targetPath, file);
moveDone = true;
} catch (IOException e) {
LogUtil.error(DataFileReadCache.class,
e.getMessage(), e);
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e1) {
LogUtil.error(DataFileReadCache.class,
e1.getMessage(), e1);
}
}
}
}
}
|
924249e503321cdfdc05a0a8c8aaf359b5b13e3c
| 253 |
java
|
Java
|
NdsBeisUi/src/test/java/com/northgateps/nds/beis/ui/view/nonjavascript/registersearchpenalties/RegisterSearchPenaltiesTest.java
|
UKGovernmentBEIS/PRS-Exemptions-Register
|
8dfc74d7c85eeeeb3c74c5fbdb0858aec4902a69
|
[
"MIT"
] | 1 |
2021-10-20T13:59:01.000Z
|
2021-10-20T13:59:01.000Z
|
NdsBeisUi/src/test/java/com/northgateps/nds/beis/ui/view/nonjavascript/registersearchpenalties/RegisterSearchPenaltiesTest.java
|
UKGovernmentBEIS/PRS-Exemptions-Register
|
8dfc74d7c85eeeeb3c74c5fbdb0858aec4902a69
|
[
"MIT"
] | null | null | null |
NdsBeisUi/src/test/java/com/northgateps/nds/beis/ui/view/nonjavascript/registersearchpenalties/RegisterSearchPenaltiesTest.java
|
UKGovernmentBEIS/PRS-Exemptions-Register
|
8dfc74d7c85eeeeb3c74c5fbdb0858aec4902a69
|
[
"MIT"
] | 1 |
2021-04-11T08:58:26.000Z
|
2021-04-11T08:58:26.000Z
| 23 | 79 | 0.849802 | 1,002,199 |
package com.northgateps.nds.beis.ui.view.nonjavascript.registersearchpenalties;
import org.junit.runner.RunWith;
import net.serenitybdd.cucumber.CucumberWithSerenity;
@RunWith(CucumberWithSerenity.class)
public class RegisterSearchPenaltiesTest {
}
|
92424b38196735ef8b5900c151751f8ec1c1a6cc
| 8,554 |
java
|
Java
|
src/main/java/happynewmoonwithreport/Wasm.java
|
fishjd/HappyNewMoonWithReport
|
5a274211668927ea2033124f7d90e929d86fdacc
|
[
"Apache-2.0"
] | 23 |
2017-07-25T18:44:36.000Z
|
2022-03-15T22:05:33.000Z
|
src/main/java/happynewmoonwithreport/Wasm.java
|
fishjd/HappyNewMoonWithReport
|
5a274211668927ea2033124f7d90e929d86fdacc
|
[
"Apache-2.0"
] | 5 |
2017-08-31T20:17:50.000Z
|
2022-03-05T15:03:39.000Z
|
src/main/java/happynewmoonwithreport/Wasm.java
|
fishjd/HappyNewMoonWithReport
|
5a274211668927ea2033124f7d90e929d86fdacc
|
[
"Apache-2.0"
] | 7 |
2017-08-31T20:13:26.000Z
|
2021-07-09T13:23:05.000Z
| 28.513333 | 121 | 0.709843 | 1,002,200 |
/*
* Copyright 2017 - 2021 Whole Bean Software, LTD.
*
* 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 happynewmoonwithreport;
import happynewmoonwithreport.section.*;
import happynewmoonwithreport.type.UInt32;
import happynewmoonwithreport.type.VarUInt32;
import happynewmoonwithreport.type.WasmVector;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
/**
* Start Here, The class to loads a WebAssembly file
*/
public class Wasm {
public Wasm() {
super();
sectionStart = new SectionStartEmpty();
}
private WasmModule module;
private BytesFile bytesFile;
private UInt32 magicNumber;
private UInt32 version;
private Boolean valid;
private ArrayList<ExportEntry> exportAll;
/* Initialize all sections except Start and Code to be empty.
This may not be to the Wasm specification, but avoids Null pointer exceptions.
Start Section must be null if not defined.
Code Section must exist. A module with out code make no sense.
*/
private SectionCustom sectionCustom = new SectionCustom();
private SectionType sectionType = new SectionType();
private SectionFunction sectionFunction = new SectionFunction();
private SectionTable sectionTable = new SectionTable();
private SectionMemory sectionMemory = new SectionMemory();
private SectionGlobal sectionGlobal = new SectionGlobal();
private SectionExport sectionExport = new SectionExport();
private SectionStart sectionStart = null;
private SectionCode sectionCode = null;
/**
* <br>
* This is a convenience constructor. Constructors which throw exceptions are
* to be used cautiously. Consider using the constructor <code>Wasm(byte[])</code>
* <br>
* <h2>Use instead</h2>
* <pre>
* {@code
* try {
* WasmFile wasmFile = new WasmFile(fileName);
* byte[] bytesAll = wasmFile.bytes();
* Wasm wasm = new Wasm(bytesAll);
* Boolean valid = wasm.validate();
* } catch (IOException ioException) {
*
* }
* }
* </pre>
*
* @param fileName The fileName. This parameter will be used in <code>new File(fileName)
* </code>
* @throws IOException Thrown if the file does not exist and other reasons.
*/
public Wasm(String fileName) throws IOException {
this();
WasmFile wasmFile = new WasmFile(fileName);
byte[] bytesAll = wasmFile.bytes();
bytesFile = new BytesFile(bytesAll);
}
/**
* Construct a Wasm module with an array of bytes.
*
* @param bytesAll An array of bytes that contain the wasm module.
*/
public Wasm(byte[] bytesAll) {
bytesFile = new BytesFile(bytesAll);
}
/**
* <br>
* Source:
* <pre>
* <a href="https://github.com/WebAssembly/design/blob/master/JS.md#user-content-webassemblyinstantiate" target="_top">
* https://github.com/WebAssembly/design/blob/master/JS.md#user-content-webassemblyinstantiate
* </a>
* </pre>
*
* @return Web Assembly Module.
*/
public WasmModule instantiate() {
SectionName sectionName;
UInt32 u32PayloadLength;
/*
* payloadLength needs to be a java type as it is used in math (+). Should be Long but
* copyOfRange only handles int.
*/
Integer payloadLength;
magicNumber = readMagicNumber();
checkMagicNumber();
version = readVersion();
instantiateSections();
fillExport(sectionExport);
fillFunction(sectionType, sectionCode);
module = new WasmModule(sectionType.getFunctionSignatures(), //
functionAll, //
sectionTable.getTables(),//
sectionMemory.getMemoryTypeAll(),//
sectionGlobal.getGlobals(),
// to do element
// to do data
sectionStart.getIndex(), sectionExport.getExports()
// to do import
);
return module;
}
private void instantiateSections() {
UInt32 nameLength = new UInt32(0L);
SectionName sectionName;
UInt32 u32PayloadLength;
Integer payloadLength;
while (bytesFile.atEndOfFile() == false) {
// Section Code
sectionName = readSectionName();
// Payload Length
u32PayloadLength = new VarUInt32(bytesFile);
payloadLength = u32PayloadLength.integerValue();
payloadLength = payloadLength - nameLength.integerValue();
BytesFile payload = bytesFile.copy(payloadLength);
switch (sectionName.getValue()) {
case SectionName.CUSTOM:
sectionCustom = new SectionCustom();
sectionCustom.instantiate(payload);
break;
case SectionName.TYPE:
sectionType = new SectionType();
sectionType.instantiate(payload);
break;
case SectionName.FUNCTION:
sectionFunction = new SectionFunction();
sectionFunction.instantiate(payload);
break;
case SectionName.TABLE:
sectionTable = new SectionTable();
sectionTable.instantiate(payload);
break;
case SectionName.MEMORY:
sectionMemory = new SectionMemory();
sectionMemory.instantiate(payload);
break;
case SectionName.GLOBAL:
sectionGlobal = new SectionGlobal();
sectionGlobal.instantiate(payload);
break;
case SectionName.EXPORT:
sectionExport = new SectionExport();
sectionExport.instantiate(payload);
break;
case SectionName.START:
sectionStart = new SectionStart();
sectionStart.instantiate(payload);
break;
case SectionName.CODE:
sectionCode = new SectionCode();
sectionCode.instantiate(payload);
break;
default:
throw new WasmRuntimeException(
UUID.fromString("e737f67f-5935-4c61-a14f-eeb97e393178"),
"Unknown Section in Module. Section = " + sectionName.getValue());
}
}
assert bytesFile.atEndOfFile() : "File length is not correct";
}
/**
* Returns true if module is valid. Call only after <code>instantiate();</code>
* <br>
* Source:
* <a href="https://github.com/WebAssembly/design/blob/master/JS.md#user-content-webassemblyvalidate"
* target="_top">
* https://github.com/WebAssembly/design/blob/master/JS.md#user-content-webassemblyvalidate
* </a>
* <br>
* Source:
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate"
* target="_top">
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
* /WebAssembly/validate
* </a>
*
* @return true if valid.
*/
public Boolean validate() {
valid = module.validation();
return valid;
}
private SectionName readSectionName() {
SectionName result = new SectionName(bytesFile);
return result;
}
private UInt32 readVersion() {
UInt32 version = new UInt32(bytesFile);
return version;
}
private UInt32 readMagicNumber() {
UInt32 magicNumber = new UInt32(bytesFile);
return magicNumber;
}
private void checkMagicNumber() {
// magicNumberExpected ‘\0asm’ = 1836278016
UInt32 magicNumberExpected = new UInt32((byte) 0x00, (byte) 0x61, (byte) 0x73,
(byte) 0x6D);
Boolean result = magicNumber.equals(magicNumberExpected);
if (result == false) {
throw new WasmRuntimeException(UUID.fromString("402c27fb-0633-4191-bb86-8e5b44479230"),
"Magic Number does not match. May not be a *.wasm file");
}
}
private void fillExport(SectionExport sectionExport) {
exportAll = new ArrayList<>(sectionExport.getCount().integerValue());
final ArrayList<ExportEntry> exportEntryAll = sectionExport.getExports();
Integer count = 0;
for (ExportEntry exportEntry : exportEntryAll) {
exportAll.add(count, exportEntry);
count++;
}
}
private WasmVector<WasmFunction> functionAll;
private void fillFunction(SectionType type, SectionCode code) {
functionAll = new WasmVector<>(type.getCount().integerValue());
for (Integer index = 0; index < type.getCount().integerValue(); index++) {
WasmFunction function =
new WasmFunction(new UInt32(index), code.getFunctionAll().get(index));
functionAll.add(function);
}
}
public UInt32 getVersion() {
return version;
}
public UInt32 getMagicNumber() {
return magicNumber;
}
public SectionType getFunctionSignatures() {
return sectionType;
}
public ArrayList<ExportEntry> exports() {
return exportAll;
}
}
|
92424b8ea12d610e088d4dffafc9e80319488690
| 2,344 |
java
|
Java
|
app/src/main/java/com/shenhua/openeyesreading/bean/NewsData.java
|
shenhuanet/OpenEyesReading
|
d6257e864a2ad6d8cbd58569d5dcc29bd595a03b
|
[
"Apache-2.0"
] | 1 |
2017-12-01T09:51:33.000Z
|
2017-12-01T09:51:33.000Z
|
app/src/main/java/com/shenhua/openeyesreading/bean/NewsData.java
|
shenhuanet/OpenEyesReading-android
|
d6257e864a2ad6d8cbd58569d5dcc29bd595a03b
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/shenhua/openeyesreading/bean/NewsData.java
|
shenhuanet/OpenEyesReading-android
|
d6257e864a2ad6d8cbd58569d5dcc29bd595a03b
|
[
"Apache-2.0"
] | null | null | null | 25.478261 | 61 | 0.671502 | 1,002,201 |
package com.shenhua.openeyesreading.bean;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* 网易新闻列表
* Created by shenhua on 8/25/2016.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class NewsData {
@JsonProperty("postid")
public String postid;
@JsonProperty("hasCover")
public boolean hasCover;
@JsonProperty("hasHead")
public int hasHead;
@JsonProperty("replyCount")
public int replyCount;
@JsonProperty("hasImg")
public int hasImg;
@JsonProperty("digest")
public String digest;
@JsonProperty("hasIcon")
public boolean hasIcon;
@JsonProperty("docid")
public String docid;
@JsonProperty("title")
public String title;
@JsonProperty("order")
public int order;
@JsonProperty("priority")
public int priority;
@JsonProperty("lmodify")
public String lmodify;
@JsonProperty("boardid")
public String boardid;
@JsonProperty("photosetID")
public String photosetID;
@JsonProperty("template")
public String template;
@JsonProperty("votecount")
public int votecount;
@JsonProperty("skipID")
public String skipID;
@JsonProperty("alias")
public String alias;
@JsonProperty("skipType")
public String skipType;
@JsonProperty("cid")
public String cid;
@JsonProperty("hasAD")
public int hasAD;
@JsonProperty("imgsrc")
public String imgsrc;
@JsonProperty("tname")
public String tname;
@JsonProperty("ename")
public String ename;
@JsonProperty("ptime")
public String ptime;
@JsonProperty("ads")
public List<AdsEntity> ads;
@JsonProperty("imgextra")
public List<ImgextraEntity> imgextra;
@JsonIgnoreProperties(ignoreUnknown = true)
public static class AdsEntity {
@JsonProperty("title")
public String title;
@JsonProperty("tag")
public String tag;
@JsonProperty("imgsrc")
public String imgsrc;
@JsonProperty("subtitle")
public String subtitle;
@JsonProperty("url")
public String url;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ImgextraEntity {
@JsonProperty("imgsrc")
public String imgsrc;
}
}
|
92424c2ccfcf68354949e404eea711398a35ea54
| 1,335 |
java
|
Java
|
future-auth/future-auth-cas-server/src/main/java/com/github/peterchenhdu/future/auth/cas/util/CustomBeanValidationPostProcessor.java
|
peterchenhdu/plib
|
e41555f876ffe18cf9b8aa5fee867165afc363d6
|
[
"Apache-2.0"
] | null | null | null |
future-auth/future-auth-cas-server/src/main/java/com/github/peterchenhdu/future/auth/cas/util/CustomBeanValidationPostProcessor.java
|
peterchenhdu/plib
|
e41555f876ffe18cf9b8aa5fee867165afc363d6
|
[
"Apache-2.0"
] | null | null | null |
future-auth/future-auth-cas-server/src/main/java/com/github/peterchenhdu/future/auth/cas/util/CustomBeanValidationPostProcessor.java
|
peterchenhdu/plib
|
e41555f876ffe18cf9b8aa5fee867165afc363d6
|
[
"Apache-2.0"
] | null | null | null | 34.230769 | 150 | 0.714607 | 1,002,202 |
/*
* Copyright (c) 2011-2025 PiChen
*/
package com.github.peterchenhdu.future.auth.cas.util;
import org.springframework.validation.beanvalidation.BeanValidationPostProcessor;
import javax.validation.*;
import java.lang.annotation.ElementType;
/**
* Provides a custom {@link javax.validation.TraversableResolver} that should work in JPA2 environments without the JPA2
* restrictions (i.e. getters for all properties).
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.4
*/
public final class CustomBeanValidationPostProcessor extends BeanValidationPostProcessor {
public CustomBeanValidationPostProcessor() {
final Configuration configuration = Validation.byDefaultProvider().configure();
configuration.traversableResolver(new TraversableResolver() {
public boolean isReachable(final Object o, final Path.Node node, final Class<?> aClass, final Path path, final ElementType elementType) {
return true;
}
public boolean isCascadable(final Object o, final Path.Node node, final Class<?> aClass, final Path path, final ElementType elementType) {
return true;
}
});
final Validator validator = configuration.buildValidatorFactory().getValidator();
setValidator(validator);
}
}
|
92424c315f9e34bfb11d1994e00ccd60a04a0e94
| 2,386 |
java
|
Java
|
Technology Fundamentals 4.0/13. Regular Expressions/Regular Expressions - Exercise/src/P5_Star_Enigma.java
|
GabrielGardev/skill-receiving
|
7227323d065f3472a6aedc1cbf3efd41562269f2
|
[
"MIT"
] | 3 |
2019-01-24T20:22:38.000Z
|
2019-08-19T13:45:31.000Z
|
Technology Fundamentals 4.0/13. Regular Expressions/Regular Expressions - Exercise/src/P5_Star_Enigma.java
|
GabrielGardev/soft-uni
|
7227323d065f3472a6aedc1cbf3efd41562269f2
|
[
"MIT"
] | null | null | null |
Technology Fundamentals 4.0/13. Regular Expressions/Regular Expressions - Exercise/src/P5_Star_Enigma.java
|
GabrielGardev/soft-uni
|
7227323d065f3472a6aedc1cbf3efd41562269f2
|
[
"MIT"
] | null | null | null | 32.684932 | 173 | 0.441324 | 1,002,203 |
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class P5_Star_Enigma {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
List<String> decrypted = new ArrayList<>();
for (int i = 0; i < n; i++) {
String line = scanner.nextLine();
int count = 0;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < line.length(); j++) {
char currentChar = line.charAt(j);
switch (currentChar){
case 's':
case 'S':
case 't':
case 'T':
case 'a':
case 'A':
case 'r':
case 'R':
count++;
break;
}
}
for (int j = 0; j < line.length(); j++) {
char currentChar = (char)(line.charAt(j) - count);
sb.append(currentChar);
}
decrypted.add(sb.toString());
}
List<String> attacked = new ArrayList<>();
List<String> destroyed = new ArrayList<>();
for (String s : decrypted) {
Pattern pattern = Pattern
.compile("([^@:!\\->]*)@(?<planet>[A-Za-z]+)([^@:!\\->]*):(?<population>\\d+)([^@:!\\->]*)!(?<type>[AD])!([^@:!\\->]*)->(?<soldiers>\\d+)([^@:!\\->]*)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
String type = matcher.group("type");
String name = matcher.group("planet");
if (type.equals("A")){
attacked.add(name);
}else {
destroyed.add(name);
}
}
}
Collections.sort(attacked);
Collections.sort(destroyed);
System.out.println(String.format("Attacked planets: %d",attacked.size()));
for (String s1 : attacked) {
System.out.println(String.format("-> %s",s1));
}
System.out.println(String.format("Destroyed planets: %d",destroyed.size()));
for (String s1 : destroyed) {
System.out.println(String.format("-> %s",s1));
}
}
}
|
92424c56e98d5cc927b21c5bf0f866f372ad0301
| 2,883 |
java
|
Java
|
Android/Olora_beta/app/src/main/java/com/team_olora/olora_beta/ListChannelAdapter.java
|
Gibartes/O-LoRa
|
368a80076e2b66a41f393e986645665b5ad8bcdc
|
[
"MIT"
] | 1 |
2022-01-14T23:05:01.000Z
|
2022-01-14T23:05:01.000Z
|
Android/Olora_beta/app/src/main/java/com/team_olora/olora_beta/ListChannelAdapter.java
|
Gibartes/O-LoRa
|
368a80076e2b66a41f393e986645665b5ad8bcdc
|
[
"MIT"
] | null | null | null |
Android/Olora_beta/app/src/main/java/com/team_olora/olora_beta/ListChannelAdapter.java
|
Gibartes/O-LoRa
|
368a80076e2b66a41f393e986645665b5ad8bcdc
|
[
"MIT"
] | 1 |
2018-11-29T10:35:59.000Z
|
2018-11-29T10:35:59.000Z
| 29.121212 | 113 | 0.660423 | 1,002,204 |
package com.team_olora.olora_beta;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class ListChannelAdapter extends BaseAdapter {
// Adapter에 추가된 데이터를 저장하기 위한 ArrayList
private ArrayList<ListChannelBtnItem> listViewItemList = new ArrayList<>();
Button connect,delete;
C_DB DB = null;
// ListViewAdapter의 생성자
public ListChannelAdapter() {
}
// Adapter에 사용되는 데이터의 개수를 리턴. : 필수 구현
@Override
public int getCount() {
return listViewItemList.size();
}
// position에 위치한 데이터를 화면에 출력하는데 사용될 View를 리턴. : 필수 구현
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
// "listview_item" Layout을 inflate하여 convertView 참조 획득.
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_channel, parent, false);
}
DB=new C_DB(convertView.getContext());
// 화면에 표시될 View(Layout이 inflate된)으로부터 위젯에 대한 참조 획득
TextView channelNameView = convertView.findViewById(R.id.viewChannelName);
// Data Set(listViewItemList)에서 position에 위치한 데이터 참조 획득
ListChannelBtnItem listChannelItem = listViewItemList.get(position);
if (listChannelItem.getName() != null) {
// 아이템 내 각 위젯에 데이터 반영
channelNameView.setText(listChannelItem.getKey()+":"+listChannelItem.getName());
} else {
channelNameView.setText(String.valueOf( listChannelItem.getAddr()));
}
return convertView;
}
// 지정한 위치에 있는 아이템 삭제
public void remove(int index) {
listViewItemList.remove(index);
}
public void clear() {
listViewItemList.clear();
}
// 지정한 위치(position)에 있는 데이터와 관계된 아이템(row)의 ID를 리턴. : 필수 구현
@Override
public long getItemId(int position) {
return position;
}
// 지정한 위치(position)에 있는 데이터 리턴 : 필수 구현
@Override
public Object getItem(int position) {
return listViewItemList.get(position);
}
// 아이템 데이터 추가를 위한 함수. 원하는대로 작성 가능.
public void addItem(int key, int addr, String name) {
ListChannelBtnItem item = new ListChannelBtnItem();
item.setKey(key);
item.setAddr(addr);
item.setName(name);
listViewItemList.add(item);
}
public String getName(int position) {
return listViewItemList.get(position).getName();
}
public int getKEY(int position){
return listViewItemList.get(position).getKey();
}
}
|
92424c61502cecebc5f15f2ecf244a0adcea6383
| 1,303 |
java
|
Java
|
sdk/batch/azure-resourcemanager-batch/src/samples/java/com/azure/resourcemanager/batch/CertificateGetSamples.java
|
Manny27nyc/azure-sdk-for-java
|
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
|
[
"MIT"
] | 1,350 |
2015-01-17T05:22:05.000Z
|
2022-03-29T21:00:37.000Z
|
sdk/batch/azure-resourcemanager-batch/src/samples/java/com/azure/resourcemanager/batch/CertificateGetSamples.java
|
Manny27nyc/azure-sdk-for-java
|
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
|
[
"MIT"
] | 16,834 |
2015-01-07T02:19:09.000Z
|
2022-03-31T23:29:10.000Z
|
sdk/batch/azure-resourcemanager-batch/src/samples/java/com/azure/resourcemanager/batch/CertificateGetSamples.java
|
Manny27nyc/azure-sdk-for-java
|
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
|
[
"MIT"
] | 1,586 |
2015-01-02T01:50:28.000Z
|
2022-03-31T11:25:34.000Z
| 31.780488 | 115 | 0.638526 | 1,002,205 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.batch;
import com.azure.core.util.Context;
/** Samples for Certificate Get. */
public final class CertificateGetSamples {
/**
* Sample code: Get Certificate with Deletion Error.
*
* @param batchManager Entry point to BatchManager.
*/
public static void getCertificateWithDeletionError(com.azure.resourcemanager.batch.BatchManager batchManager) {
batchManager
.certificates()
.getWithResponse(
"default-azurebatch-japaneast",
"sampleacct",
"sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e",
Context.NONE);
}
/**
* Sample code: Get Certificate.
*
* @param batchManager Entry point to BatchManager.
*/
public static void getCertificate(com.azure.resourcemanager.batch.BatchManager batchManager) {
batchManager
.certificates()
.getWithResponse(
"default-azurebatch-japaneast",
"sampleacct",
"sha1-0a0e4f50d51beadeac1d35afc5116098e7902e6e",
Context.NONE);
}
}
|
92424ca3aa5b51072e726795e02473f7a5a88ed1
| 4,239 |
java
|
Java
|
src/Shopping/Cart.java
|
Parag001/Shopping-Cart-Website
|
390e74e3a5cbd9228f02613b8bfaa2ed70148fe8
|
[
"MIT"
] | null | null | null |
src/Shopping/Cart.java
|
Parag001/Shopping-Cart-Website
|
390e74e3a5cbd9228f02613b8bfaa2ed70148fe8
|
[
"MIT"
] | null | null | null |
src/Shopping/Cart.java
|
Parag001/Shopping-Cart-Website
|
390e74e3a5cbd9228f02613b8bfaa2ed70148fe8
|
[
"MIT"
] | null | null | null | 30.717391 | 119 | 0.665015 | 1,002,206 |
package Shopping;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Cart
*/
public class Cart extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection con;
/**
* @see HttpServlet#HttpServlet()
*/
public Cart() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
System.out.println("In init");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "admin123");
}//try
catch(ClassNotFoundException e1){
e1.printStackTrace();
}
catch(SQLException e2){
e2.printStackTrace();
}
catch(Exception e3){
e3.printStackTrace();
}
}//init
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String selected_product = request.getParameter("product");
String qty = request.getParameter("qty");
int cid = 0,price = 0;
String email="";
//int quantity = Integer.parseInt(qty);
HttpSession sess_user = request.getSession(false);
if(sess_user != null)
{
String user = (String) sess_user.getAttribute("name");
//out.println("your selected product "+selected_product+" "+qty);
RequestDispatcher rd = request.getRequestDispatcher("link.html");
rd.include(request, response);
out.println("<h2><i>Welcome "+user+"</i></h2>");
try
{
//Generating card id
Statement stmt = con.createStatement();
String query = "select cart_seq1.nextval from dual";
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
cid = rs.getInt(1);
//retrieving price of the selected product
Statement stmt1 = con.createStatement();
String query1 = "select price from products where product_name = '"+selected_product+"'";
ResultSet rs1 = stmt1.executeQuery(query1);
while(rs1.next())
price = rs1.getInt("price");
//retrieving userid of the particular session
Statement stmt2 = con.createStatement();
String query2 = "select * from register where name='"+user+"'";
ResultSet rs2 = stmt2.executeQuery(query2);
while(rs2.next())
email = rs2.getString("email");
//inserting cart items into table Cart;
String insert_cart = "insert into cart values(?,?,?,?,?)";
PreparedStatement psmt = con.prepareStatement(insert_cart);
psmt.setInt(1, cid);
psmt.setString(2,email);
psmt.setString(3, selected_product);
int quantity = Integer.parseInt(qty);
psmt.setInt(4,quantity);
psmt.setInt(5,quantity*price);
int rec = psmt.executeUpdate();
if(rec >0)
out.println("<center><i>Added to Cart Successfully!<a href='Products'> Continue Shopping</a></i><center>");
// request.getRequestDispatcher("Products").include(request, response);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
out.println("<center><i>Session expired! Please Login again</i></center>");
request.getRequestDispatcher("index.html").include(request,response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
92424d5687168f7162845eb1eee3ad55efb53926
| 8,110 |
java
|
Java
|
src/main/java/com/pattexpattex/servergods2/core/listeners/SlashEventListener.java
|
PattexPattex/ServerGods-2.0.0
|
583ae40f142d3c3464b6c56b1e87f26780f4f11a
|
[
"MIT"
] | 1 |
2022-03-09T10:00:36.000Z
|
2022-03-09T10:00:36.000Z
|
src/main/java/com/pattexpattex/servergods2/core/listeners/SlashEventListener.java
|
PattexPattex/ServerGods-2.0.0
|
583ae40f142d3c3464b6c56b1e87f26780f4f11a
|
[
"MIT"
] | 4 |
2022-03-21T16:22:02.000Z
|
2022-03-23T15:18:56.000Z
|
src/main/java/com/pattexpattex/servergods2/core/listeners/SlashEventListener.java
|
PattexPattex/ServerGods-2.0.0
|
583ae40f142d3c3464b6c56b1e87f26780f4f11a
|
[
"MIT"
] | null | null | null | 42.239583 | 156 | 0.553021 | 1,002,207 |
package com.pattexpattex.servergods2.core.listeners;
import com.pattexpattex.servergods2.commands.slash.AboutCmd;
import com.pattexpattex.servergods2.commands.slash.PingCmd;
import com.pattexpattex.servergods2.commands.slash.config.ConfigCmd;
import com.pattexpattex.servergods2.commands.slash.config.EnableCmd;
import com.pattexpattex.servergods2.commands.slash.fun.*;
import com.pattexpattex.servergods2.commands.slash.moderation.BanCmd;
import com.pattexpattex.servergods2.commands.slash.moderation.KickCmd;
import com.pattexpattex.servergods2.commands.slash.moderation.MuteCmd;
import com.pattexpattex.servergods2.commands.slash.moderation.WakeUpCmd;
import com.pattexpattex.servergods2.core.commands.BotSlash;
import com.pattexpattex.servergods2.core.exceptions.BotException;
import com.pattexpattex.servergods2.util.FormatUtil;
import com.pattexpattex.servergods2.util.OtherUtil;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* This is the listener that executes the bots' {@link BotSlash slash commands}.
* @since 2.1.0
* @see BotSlash
* */
public class SlashEventListener extends ListenerAdapter {
private static final List<BotSlash> cmdList = new ArrayList<>();
private static final List<BotSlash> cmdListEnabled = new ArrayList<>();
public SlashEventListener() {
//Create instances of all commands
cmdList.add(new ConfigCmd());
cmdList.add(new EnableCmd());
cmdList.add(new AboutCmd());
cmdList.add(new BanCmd());
cmdList.add(new KickCmd());
cmdList.add(new MuteCmd());
cmdList.add(new WakeUpCmd());
cmdList.add(new RolesCmd());
cmdList.add(new PingCmd());
cmdList.add(new InviteCmd());
cmdList.add(new GiveawayCmd());
cmdList.add(new PollCmd());
cmdList.add(new RickrollCmd());
cmdList.add(new MusicCmd());
cmdList.add(new EmoteCmd());
cmdList.add(new UserCmd());
cmdList.add(new AvatarCmd());
//Enables the commands given in the config.json
cmdList.forEach((cmd) -> {
if (cmd.isEnabled(cmd)) cmdListEnabled.add(cmd);
});
}
@Override
public void onReady(@NotNull ReadyEvent event) {
/* This is commented out, because no command should be enabled globally */
//event.getJDA().updateCommands().queue();
/* Clears all commands in all servers */
//event.getJDA().getGuilds().forEach((guild) -> guild.updateCommands().queue());
List<String> disabled = new ArrayList<>();
cmdList.forEach((cmd) -> {
if (!cmdListEnabled.contains(cmd)) {
disabled.add(cmd.getName());
}
});
event.getJDA().getGuilds().forEach((guild) -> {
List<Command> commands = guild.retrieveCommands().complete().stream()
.filter((cmd) -> cmd.getApplicationId().equals(event.getJDA().getSelfUser().getApplicationId())).toList();
commands.forEach((cmd) -> {
if (disabled.contains(cmd.getName())) {
cmd.delete().queue();
}
});
});
/* Runs the setup() method in each command,
here is checked whether a command is enabled in a guild or not */
cmdListEnabled.forEach((cmd) -> cmd.setup(cmd, event.getJDA()));
}
@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
//Iterates through the enabled commands
for (BotSlash cmd : cmdListEnabled) {
//If the command exists,
if (event.getName().equals(cmd.getName())) {
//If the command was run in a guild,
if (event.getGuild() != null) {
//If the command is enabled in the guild,
//(Should always be true, because this is already checked in the onReady method)
if (cmd.isEnabledInGuild(event.getGuild())) {
//And if the member has the permissions,
if (Objects.requireNonNull(event.getMember()).hasPermission(cmd.getPermissions())) {
if (event.getGuild().getSelfMember().hasPermission(cmd.getSelfPermissions())) {
//Then actually try to run it,
try {
cmd.run(event);
}
//But it could still fail
catch (Exception e) {
MessageEmbed embed = FormatUtil.errorEmbed(e, this.getClass()).build();
if (e instanceof BotException && ((BotException) e).canOverwriteReply()) {
event.replyEmbeds(embed).setEphemeral(true).queue(null,
(f) -> event.getHook().editOriginalEmbeds(embed).queue((msg) ->
{
msg.editMessageComponents(Collections.emptyList()).queue();
if (!msg.isEphemeral()) {
msg.clearReactions().queue();
}
}));
}
else {
event.replyEmbeds(embed).setEphemeral(true).queue(null,
(f) -> event.getChannel().sendMessageEmbeds(embed).queue());
}
OtherUtil.handleBotException(event, e);
}
}
//Bot has insufficient permissions
else event.replyEmbeds(FormatUtil.noSelfPermissionEmbed(cmd.getSelfPermissions()).build()).setEphemeral(true).queue();
}
//No permission
else event.replyEmbeds(FormatUtil.noPermissionEmbed(cmd.getPermissions()).build()).setEphemeral(true).queue();
}
/* Not enabled in guild
This should never execute, because this is already checked in the onReady method */
else event.replyEmbeds(FormatUtil.notEnabledEmbed().build()).queue();
/* After the command executed, break the loop, because two commands cannot have the same name, it would lead to unnecessary confusion */
break;
}
//else {
// try {
// cmd.run(event);
// }
// catch (Exception e) {
// event.replyEmbeds(FormatUtil.errorEmbed(e, this.getClass()).build()).queue(null,
// (f) -> event.getChannel().sendMessageEmbeds(FormatUtil.errorEmbed(e, this.getClass()).build()).queue());
// }
//}
}
}
}
/**
* Returns all the bots' slash commands, also those which are disabled in the config.json
* @return {@link SlashEventListener#cmdList}
* @since 2.1.0
* */
public static List<BotSlash> getCommands() {
return cmdList;
}
/**
* Returns only the slash commands enabled in the config.json
* @return {@link SlashEventListener#cmdListEnabled}
* @since 2.1.0
* */
public static List<BotSlash> getEnabledCommands() {
return cmdListEnabled;
}
}
|
92424e68865515327be9093598a490a5e6aead5e
| 3,974 |
java
|
Java
|
distribute/src/main/java/org/glamey/training/jvm/ast/BuilderProcessor.java
|
glameyzhou/training
|
7f3186ab18dafdd8f8f80c2090d15cf54b2c2af2
|
[
"Apache-2.0"
] | null | null | null |
distribute/src/main/java/org/glamey/training/jvm/ast/BuilderProcessor.java
|
glameyzhou/training
|
7f3186ab18dafdd8f8f80c2090d15cf54b2c2af2
|
[
"Apache-2.0"
] | null | null | null |
distribute/src/main/java/org/glamey/training/jvm/ast/BuilderProcessor.java
|
glameyzhou/training
|
7f3186ab18dafdd8f8f80c2090d15cf54b2c2af2
|
[
"Apache-2.0"
] | null | null | null | 37.740741 | 127 | 0.665604 | 1,002,208 |
package org.glamey.training.jvm.ast;
import com.google.common.collect.Sets;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.Writer;
import java.util.Set;
/**
* http://www.moniaa.cn/blog/2019/01/15/how-to-write-code-generator/
* <p>
* {@link SupportedSourceVersion} {@link SupportedAnnotationTypes}两个注解相等于重写的
* {@link AbstractProcessor#getSupportedSourceVersion()}和 {@link AbstractProcessor#getSupportedAnnotationTypes()}
* <p>
* 两者保留一个即可
*
* @author yang.zhou 2020.01.14.22
*/
[email protected]"})
[email protected])
public class BuilderProcessor extends AbstractProcessor {
private static final String LINE = System.getProperty("line.separator");
private Messager messager;
private Elements elementUtils;
private Filer filer;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.messager = processingEnv.getMessager();
this.filer = processingEnv.getFiler();
this.elementUtils = processingEnv.getElementUtils();
messager.printMessage(Diagnostic.Kind.NOTE, "init");
}
@Override
public SourceVersion getSupportedSourceVersion() {
System.out.println("--> getSupportedSourceVersion");
return SourceVersion.latestSupported();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
messager.printMessage(Diagnostic.Kind.NOTE, "getSupportedAnnotationTypes");
Set<String> annotationTypes = Sets.newHashSet(
Builder.class.getCanonicalName()
);
return annotationTypes;
}
/**
* 按照轮次遍历所有源代码中符合条件的类
*
* @param annotations 支持的注解类
* @param roundEnv 每个轮次中携带的环境相关信息
* @return
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
messager.printMessage(Diagnostic.Kind.NOTE, "process");
Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(Builder.class);
elementsAnnotatedWith.stream()
.filter(element -> element.getKind() == ElementKind.CLASS)
.forEach(element -> {
TypeElement typeElement = (TypeElement) element;
PackageElement packageElement = elementUtils.getPackageOf(typeElement);
String packagePath = packageElement.getQualifiedName().toString();
String className = typeElement.getSimpleName().toString();
try {
JavaFileObject sourceFile = filer.createSourceFile(packagePath + "." + className + "_xx", typeElement);
Writer writer = sourceFile.openWriter();
writer.write(generateSource(packagePath, className));
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
});
return false;
}
private String generateSource(String packagePath, String className) {
StringBuilder builder = new StringBuilder();
builder.append("package ").append(packagePath).append(";").append(LINE);
builder.append("import ").append(packagePath).append(".").append(className).append(";").append(LINE);
builder.append(LINE);
builder.append("public class ").append(className).append("_xx").append(" {").append(LINE);
builder.append(" public ").append(className).append(" ").append(" proxy;").append(LINE);
builder.append("}").append(LINE);
return "0";
}
}
|
92424e9f3e7896512d822e69728e796eeaceafd2
| 1,833 |
java
|
Java
|
smart-hadoop-support/smart-hadoop-3.1/src/main/java/org/smartdata/hdfs/action/DisableErasureCodingPolicy.java
|
zhiqiangx/SSM
|
e6f6c47eb3fcf1cf3ae104e2b7def401d3ac1a48
|
[
"Apache-2.0"
] | 1 |
2019-05-14T13:54:38.000Z
|
2019-05-14T13:54:38.000Z
|
smart-hadoop-support/smart-hadoop-3.1/src/main/java/org/smartdata/hdfs/action/DisableErasureCodingPolicy.java
|
huangjing-nl/SSM
|
1e162942a50c97882e6a8932c05ffd9ba1239765
|
[
"Apache-2.0"
] | 3 |
2019-03-11T05:04:20.000Z
|
2019-03-11T05:06:17.000Z
|
smart-hadoop-support/smart-hadoop-3.1/src/main/java/org/smartdata/hdfs/action/DisableErasureCodingPolicy.java
|
huangjing-nl/SSM
|
1e162942a50c97882e6a8932c05ffd9ba1239765
|
[
"Apache-2.0"
] | 1 |
2018-10-01T06:57:23.000Z
|
2018-10-01T06:57:23.000Z
| 33.944444 | 83 | 0.744681 | 1,002,209 |
/**
* 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.smartdata.hdfs.action;
import org.smartdata.action.annotation.ActionSignature;
import org.smartdata.conf.SmartConf;
import org.smartdata.hdfs.HadoopUtil;
import java.util.Map;
/**
* An action to disable an EC policy.
*/
@ActionSignature(
actionId = "disableec",
displayName = "disableec",
usage = DisableErasureCodingPolicy.EC_POLICY_NAME + " $policy"
)
public class DisableErasureCodingPolicy extends HdfsAction {
public static final String EC_POLICY_NAME = "-policy";
private SmartConf conf;
private String policyName;
@Override
public void init(Map<String, String> args) {
super.init(args);
this.conf = getContext().getConf();
this.policyName = args.get(EC_POLICY_NAME);
}
@Override
public void execute() throws Exception {
this.setDfsClient(HadoopUtil.getDFSClient(
HadoopUtil.getNameNodeUri(conf), conf));
dfsClient.disableErasureCodingPolicy(policyName);
appendResult(String.format("The EC policy named %s is disabled!", policyName));
}
}
|
92424eed0e8b018a060a47768db7a24c754f5879
| 714 |
java
|
Java
|
backend/filescanner-api/src/main/java/de/egladil/web/filescanner_api/infrastructure/rest/FilescannerObjectMapperCustomizer.java
|
heike2718/filescanner
|
a7efb274025387a6935fac2350b8b4d45c76aa22
|
[
"MIT"
] | null | null | null |
backend/filescanner-api/src/main/java/de/egladil/web/filescanner_api/infrastructure/rest/FilescannerObjectMapperCustomizer.java
|
heike2718/filescanner
|
a7efb274025387a6935fac2350b8b4d45c76aa22
|
[
"MIT"
] | 1 |
2021-05-20T06:02:07.000Z
|
2021-05-24T18:47:13.000Z
|
backend/filescanner-api/src/main/java/de/egladil/web/filescanner_api/infrastructure/rest/FilescannerObjectMapperCustomizer.java
|
heike2718/filescanner
|
a7efb274025387a6935fac2350b8b4d45c76aa22
|
[
"MIT"
] | 1 |
2021-08-16T11:40:30.000Z
|
2021-08-16T11:40:30.000Z
| 29.75 | 82 | 0.697479 | 1,002,210 |
// =====================================================
// Project: filescanner-api
// (c) Heike Winkelvoß
// =====================================================
package de.egladil.web.filescanner_api.infrastructure.rest;
import javax.inject.Singleton;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.jackson.ObjectMapperCustomizer;
@Singleton
public class FilescannerObjectMapperCustomizer implements ObjectMapperCustomizer {
@Override
public void customize(final ObjectMapper objectMapper) {
// To suppress serializing properties with null values
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
|
92424f75018e21974f8c227263a6049efe2d1839
| 4,463 |
java
|
Java
|
output/b9f924eff5ab401898dc6ec0321643d5.java
|
comprakt/comprakt-fuzz-tests
|
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
output/b9f924eff5ab401898dc6ec0321643d5.java
|
comprakt/comprakt-fuzz-tests
|
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
output/b9f924eff5ab401898dc6ec0321643d5.java
|
comprakt/comprakt-fuzz-tests
|
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
|
[
"Apache-2.0",
"MIT"
] | null | null | null | 42.913462 | 274 | 0.547166 | 1,002,211 |
class OmjIggHVhDP {
public uerp[][][][] Zxq6ZF;
public void rUPcPVniTm (ScWUXdW[][] GDLv4yEE6go8N, int[] NV_nE17H) {
return;
this[ -S_n()[ null.YatF()]];
int D;
int gONuN = !new WdaNZjipZA_Emq()[ -this.ez7()] = true.dsOly();
void[] Ma3ZI3 = ( -!363265.aG).p8HjkUAkRF() = 30[ t0a[ !false.da4VBYc()]];
int[] hJbRabcxvja_q = aiG03obICpiM.FH8SQ1XqS18Fx() = this.J3VtJfLfi();
MUtp3xVWQzvq gk4;
d9yONMuI k;
while ( ---this.aT()) while ( -!-( -this[ true[ 51.yd()]]).n4gj()) return;
while ( !!null[ -!true.xGZSEh2_]) return;
}
public boolean gQ (oFi[][] X0XXttzI4, jRr4qm1s PH, dqJG[] J0M2W48Q) throws ABMF4_c {
int bK0OTknTEK = !!-!new boolean[ null.Jhryd7Bfkm3NQ()][ !!!-1567410.CNZ3QVH()];
while ( new void[ this.Fcc8].mlbS8XTbnI9s) ;
{
boolean M_AKy4dP4;
while ( new rK1sDEjTCqLS7[ -!78[ !new dXyfxIJ().Oa1T]].KF2A) if ( !( !!new cnZJf8yG88V0IK()[ -!this[ zuZgWhKPaL[ Yg9dJal5HfK_uh()[ new gDerCptpdC06().TZaGo8ThV7()]]]])[ null.pE1np]) while ( this[ WkbZs7k[ this[ this.aP_JAwvqL]]]) !-!!bdTheVTVAzN.OLvdV5yyIlEh();
void[] V_hNiDY6zR5;
int nmiXymba;
qJkD LWEm9Zg;
return;
{
wKZH[] Bw;
}
void[] P;
boolean EB7bufN;
void ZJMY7;
;
boolean[] yot8TZndDqC6fW;
}
void DN = !!-new int[ !hnhAA4.J2OYH4_b2()][ !-new K4hsZPw7ewGL().O9sKpDP8] = !null.nndAaVk5();
void[] rr4WhPEDE8z = -!75.uXP();
wQRAlyp7n YiWHbdg_eaUp;
!!new BM7AV9DRh().m7IaL1CsNry_WZ;
ri58ym7tFvd xWt7uZZlN = -this.C5 = this.CfO;
xHz9[][] q = null.NcUB8Icx6() = MCeN2B1a.IaABI72A8RPqxX;
TZTXm_n a8N;
}
public int[] lL (pKANk5I9WF dYsiJ, int[] zSRabprYi) throws UB4Dr {
if ( null.ycvjiu) true.ATHI8MeGpnI;
}
public dxCOy[] Q;
public void[][][][] b;
public static void IsP8 (String[] qvJUK) throws jDsO {
void kXbhdC5;
void sUgppJmU4P;
if ( VAw_.eD2f) while ( !!!!-this.zB12sVw790bjNB) ;else return;
Kdng79PJ[][][][] zu3Hq;
hOHdl[] ezZ8IY0ua9r;
duGmZCn4JAFe ruggW29RA8Acp1;
zEhgzqGTiPNA RQjQ070 = !63625466[ true._uSC171] = 87[ -true[ !new ALMy9R().Ahjb0p0Us0]];
return -false.Wu1_();
}
public static void aFhHSIX (String[] vL) {
;
return new bK[ !-( !-true.tJ_IgEe6RNDIP)[ new boolean[ 0[ null.Dd4dDK1]].Qt8Y]].N_YFsYXqpAkgcj;
if ( this[ true.C8wa0e3kKlM]) if ( 494171[ !-!true.vr4wT]) {
return;
}
void BmG3MgI5qUY_ = -new _iuWRJSne().buOqb() = -5230.l;
int[] kb = o.o4G9mSR4Au() = k().WK8G1;
}
public static void BeEuaYFSP (String[] e5JXtu6K) throws G {
void b1RMsRk4IXZ;
void KV;
KF1RLnAkgVcq H;
if ( !!null.X7AE9()) {
;
}else while ( !-null[ null[ !new may().ECe02dDJS0P()]]) while ( new vzmG0y()[ -Gg().aGE0KYRj()]) while ( null.z_()) {
boolean IO_tbJbXWAwVt;
}
if ( true[ new ZKAVhonSfo[ -!-Kme2HcRPCA4aj[ this.ac]][ new RmoWW().Ycw()]]) {
while ( this[ !-3358.fJ7tA()]) {
boolean F6jZGVaN;
}
}else {
while ( this[ false.bQDDH2LgpWcNrA]) return;
}
if ( !!!!-new oD_dMYWRspHYim[ new void[ this[ !bVS8.JQ1tRL1]][ !( -!-!!-!ubeGYudrEUe().nXRgNDGR)[ Hbs().P93eUMi]]].WzQ()) if ( new MabbkymJ().N9LyrUnb4CRGw()) FDLy08mNR_v0J_.AK7YJhr9;
void[] b3sTl9y_;
int GkNS3yx2 = null.hAMvRbYyQyDdn() = 99[ ( true[ !!new BAMsaLkAy9IP[ false[ -new G().RfgFbZwR()]].wnGDM]).Jh6x7NCLl];
if ( ( -29586.B6ILcl0z())[ kMYm().SdW24cn1S()]) if ( -this.as()) {
while ( y4Yx[ -new void[ this.g].dz8dK]) !138657.IOL6I;
}
return;
void ZVe4QeL3zQ = new void[ false[ 64445[ new Dcx()[ new kPtIBMF_xs[ -HnX4S8B1tiB.znYSQyAc()].fELlu1()]]]].urhfUOYP();
}
public static void cypBzw5abHbK0 (String[] TxGFE5) {
boolean wA70Wp;
int aJvyK7 = -!this[ 27[ 94631587.Jb8ka]] = --!this.yY3UrwX_88;
return ( ( !true.VCSLYkzBje).CRyHs).fEWfE();
!!false[ false[ -!!08.TNbTGBWtrYi]];
while ( this.zmAKvCI()) return;
seemFKBrPC g = jYHOHZf9142AI.SiQO2b() = !-true.DX3esbi_pvKOw;
}
}
class Ja1ON8w2PRu {
}
|
92425037c9a813cbdc9eb4f257143413b2cb83c0
| 1,872 |
java
|
Java
|
app/src/main/java/com/android/lgf/demo/activity/CardViewActivity.java
|
Geroff/AndroidAdvanceDemo
|
c5b35303102d4fa6e40520a5421c713553ec0171
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/android/lgf/demo/activity/CardViewActivity.java
|
Geroff/AndroidAdvanceDemo
|
c5b35303102d4fa6e40520a5421c713553ec0171
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/android/lgf/demo/activity/CardViewActivity.java
|
Geroff/AndroidAdvanceDemo
|
c5b35303102d4fa6e40520a5421c713553ec0171
|
[
"Apache-2.0"
] | null | null | null | 31.2 | 100 | 0.696047 | 1,002,212 |
package com.android.lgf.demo.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.widget.SeekBar;
import com.android.lgf.demo.R;
/**
* Created by lgf on 17-12-4.
*/
public class CardViewActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private CardView cardView;
private SeekBar sbSetRoundCorner;
private SeekBar sbSetImageSpacing;
private SeekBar sbSetShadow;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
cardView = (CardView) findViewById(R.id.card_view);
sbSetRoundCorner = (SeekBar) findViewById(R.id.sb_set_round_corner);
sbSetImageSpacing = (SeekBar) findViewById(R.id.sb_set_image_spacing);
sbSetShadow = (SeekBar) findViewById(R.id.sb_set_shadow);
sbSetRoundCorner.setOnSeekBarChangeListener(this);
sbSetImageSpacing.setOnSeekBarChangeListener(this);
sbSetShadow.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
switch (seekBar.getId()) {
case R.id.sb_set_round_corner:
cardView.setRadius(progress);
break;
case R.id.sb_set_shadow:
cardView.setCardElevation(progress);
break;
case R.id.sb_set_image_spacing:
cardView.setContentPadding(progress, progress, progress, progress);
break;
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
|
9242507ebe3d63805ea78534e2726e4f371c632e
| 217 |
java
|
Java
|
api/src/main/java/edu/colostate/cs/cs414/p3/bdeining/api/Activity.java
|
bdeining/cs414-f18-801-singleton
|
ebe7556c205ee5abe688aba14b43cc729daeb16d
|
[
"Apache-2.0"
] | null | null | null |
api/src/main/java/edu/colostate/cs/cs414/p3/bdeining/api/Activity.java
|
bdeining/cs414-f18-801-singleton
|
ebe7556c205ee5abe688aba14b43cc729daeb16d
|
[
"Apache-2.0"
] | null | null | null |
api/src/main/java/edu/colostate/cs/cs414/p3/bdeining/api/Activity.java
|
bdeining/cs414-f18-801-singleton
|
ebe7556c205ee5abe688aba14b43cc729daeb16d
|
[
"Apache-2.0"
] | null | null | null | 19.727273 | 100 | 0.728111 | 1,002,213 |
package edu.colostate.cs.cs414.p3.bdeining.api;
/**
* An enumeration of activity types for a Customer. Currently, a customer can be marked as active or
* inactive.
*/
public enum Activity {
ACTIVE,
INACTIVE
}
|
9242508ae33d9f25d4c2850f54f7888687b91ed7
| 635 |
java
|
Java
|
sexy-tea/src/main/java/sexy/tea/mapper/StoreMapper.java
|
GeekGray-Code/sexy-tea-spring-boot
|
b26ab46ccc120a033787dbdab96340bd40b433fd
|
[
"Apache-2.0"
] | 2 |
2020-10-13T07:31:57.000Z
|
2020-10-13T07:32:06.000Z
|
sexy-tea/src/main/java/sexy/tea/mapper/StoreMapper.java
|
adanz1015/sexy-tea-spring-boot
|
b26ab46ccc120a033787dbdab96340bd40b433fd
|
[
"Apache-2.0"
] | 2 |
2020-10-13T06:38:56.000Z
|
2020-10-20T06:40:22.000Z
|
sexy-tea/src/main/java/sexy/tea/mapper/StoreMapper.java
|
GeekGray-Code/sexy-tea-spring-boot
|
b26ab46ccc120a033787dbdab96340bd40b433fd
|
[
"Apache-2.0"
] | 4 |
2020-09-23T03:14:25.000Z
|
2020-12-20T16:17:56.000Z
| 21.896552 | 77 | 0.729134 | 1,002,214 |
package sexy.tea.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import sexy.tea.model.Store;
import java.util.List;
/**
* author 大大大西西瓜皮🍉
* date 15:10 2020-09-26
* description:
*/
@Mapper
public interface StoreMapper extends tk.mybatis.mapper.common.Mapper<Store> {
int updateBatch(List<Store> list);
int updateBatchSelective(List<Store> list);
int batchInsert(@Param("list") List<Store> list);
int insertOrUpdate(Store record);
int insertOrUpdateSelective(Store record);
List<Store> findByCity(@Param("city") String city);
Long storeCount();
}
|
9242510d0862b57010443f1d101b92d6b1937acf
| 42 |
java
|
Java
|
JavaLibrary/JavaDefendSdkLibrary/src/test/java/test/Rectangle.java
|
gubaojian/CrashDefend
|
146f0064a9985a8c01126a6dfb305acc89489bdd
|
[
"MIT"
] | 1 |
2020-10-23T07:17:01.000Z
|
2020-10-23T07:17:01.000Z
|
CrashDefendApp/DefendCompiler/src/test/java/test/Rectangle.java
|
gubaojian/crash-defend
|
146f0064a9985a8c01126a6dfb305acc89489bdd
|
[
"MIT"
] | 2 |
2021-08-18T05:04:18.000Z
|
2021-09-23T09:23:28.000Z
|
old/JavaLibrary/JavaDefendSdkLibrary/src/test/java/test/Rectangle.java
|
gubaojian/CrashDefend
|
146f0064a9985a8c01126a6dfb305acc89489bdd
|
[
"MIT"
] | 1 |
2020-11-06T08:49:52.000Z
|
2020-11-06T08:49:52.000Z
| 8.4 | 24 | 0.738095 | 1,002,215 |
package test;
public class Rectangle {
}
|
924251a43fd29c3d7712fe46331bf7fadb420a57
| 3,774 |
java
|
Java
|
src/main/java/com/dbeer/pdf/PDFGenerator.java
|
dmbeer/pdf-test
|
e1cff627d79699ae102e2d2c59fcaab301a27333
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/dbeer/pdf/PDFGenerator.java
|
dmbeer/pdf-test
|
e1cff627d79699ae102e2d2c59fcaab301a27333
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/dbeer/pdf/PDFGenerator.java
|
dmbeer/pdf-test
|
e1cff627d79699ae102e2d2c59fcaab301a27333
|
[
"Apache-2.0"
] | null | null | null | 40.148936 | 249 | 0.668521 | 1,002,216 |
package com.dbeer.pdf;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by dbeer on 23/08/15.
*/
public class PDFGenerator {
public void generatePDF() {
Path pdf = Paths.get("/tmp", "test.pdf");
try {
FileOutputStream fileOutputStream = new FileOutputStream(pdf.toFile());
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
document.open();
document.add(new Phrase("Movies", FontFactory.getFont(FontFactory.HELVETICA, 26, Color.ORANGE)));
document.add(addTables());
document.add(new Paragraph("Second Paragraph", FontFactory.getFont(FontFactory.TIMES_BOLDITALIC, 32, Color.RED)));
document.newPage();
document.add(title());
document.add(addParagraph());
document.close();
} catch (FileNotFoundException e) {
Logger.getLogger(PDFGenerator.class.getName()).log(Level.SEVERE, "File Not Found {0}", pdf.toString());
Logger.getLogger(PDFGenerator.class.getName()).log(Level.SEVERE, "File Not Found", e);
} catch (DocumentException e) {
Logger.getLogger(PDFGenerator.class.getName()).log(Level.SEVERE, "Document error", e);
}
}
private Paragraph addTables() {
Paragraph paragraph1 = new Paragraph();
PdfPTable table1 = new PdfPTable(2);
PdfPTable table2 = new PdfPTable(2);
table1.setTotalWidth(400f);
table1.setLockedWidth(true);
table1.setSpacingAfter(10);
table1.addCell("Hello Table 1");
table1.completeRow();
table1.addCell("Blank Cell");
table1.addCell("Blank Cell");
table2.setTotalWidth(300f);
table2.setLockedWidth(true);
table2.addCell("Hello Table 2");
table2.completeRow();
table2.addCell("Blank Cell");
table2.addCell("Blank Cell");
paragraph1.add(table1);
paragraph1.add(table2);
return paragraph1;
}
private Paragraph title() {
Paragraph paragraph = new Paragraph();
Chunk title = new Chunk("Declaration", FontFactory.getFont(FontFactory.HELVETICA, 24, Color.MAGENTA));
paragraph.add(title);
paragraph.setSpacingAfter(5f);
return paragraph;
}
private Paragraph addParagraph() {
Paragraph paragraph1 = new Paragraph();
Phrase sentance = new Phrase("Lorem Ipsum is simply dummy text of the printing and typesetting industry.");
Phrase sentance1 = new Phrase(" Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.");
Phrase sentance2 = new Phrase(" It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.");
Phrase sentance3 = new Phrase("It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.");
paragraph1.setFont(FontFactory.getFont(FontFactory.HELVETICA, 12, Color.BLACK));
paragraph1.setFirstLineIndent(50);
paragraph1.add(sentance);
paragraph1.add(sentance1);
paragraph1.add(sentance2);
paragraph1.add(sentance3);
return paragraph1;
}
}
|
92425366142dffaed337b5373202a76a98d647a8
| 362 |
java
|
Java
|
src/geostoat/jankscript/shell/parsing/PrintNode.java
|
GeometricStoat/JankScript
|
715ac6819629fe08ae546101c929ffdfb6410644
|
[
"MIT"
] | null | null | null |
src/geostoat/jankscript/shell/parsing/PrintNode.java
|
GeometricStoat/JankScript
|
715ac6819629fe08ae546101c929ffdfb6410644
|
[
"MIT"
] | null | null | null |
src/geostoat/jankscript/shell/parsing/PrintNode.java
|
GeometricStoat/JankScript
|
715ac6819629fe08ae546101c929ffdfb6410644
|
[
"MIT"
] | null | null | null | 15.73913 | 53 | 0.674033 | 1,002,217 |
package geostoat.jankscript.shell.parsing;
class PrintNode extends KeywordNode {
ExprNode value;
PrintNode() {}
PrintNode(ExprNode value) {
this.value = value;
}
void setValue(ExprNode value) {
this.value = value;
}
@Override
ASTNode traverse() {
if (value != null)
System.out.println("[PRINT] " + value.traverse());
return null;
}
}
|
9242545487210fde09184d05fd5f84a759c2619b
| 1,682 |
java
|
Java
|
examples/simple-example/src/main/java/io/github/adobe/sign/impl/workflow/SimpleWorkflow.java
|
will-j-mccue/adobe-sign-sandbox
|
71670a24f2514d763be5a0fd2074fcd701dde9d7
|
[
"Apache-2.0"
] | null | null | null |
examples/simple-example/src/main/java/io/github/adobe/sign/impl/workflow/SimpleWorkflow.java
|
will-j-mccue/adobe-sign-sandbox
|
71670a24f2514d763be5a0fd2074fcd701dde9d7
|
[
"Apache-2.0"
] | null | null | null |
examples/simple-example/src/main/java/io/github/adobe/sign/impl/workflow/SimpleWorkflow.java
|
will-j-mccue/adobe-sign-sandbox
|
71670a24f2514d763be5a0fd2074fcd701dde9d7
|
[
"Apache-2.0"
] | 2 |
2021-03-31T20:21:35.000Z
|
2021-04-14T18:42:26.000Z
| 35.041667 | 94 | 0.746136 | 1,002,218 |
package io.github.adobe.sign.impl.workflow;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import io.github.adobe.sign.core.actions.SignAction;
import io.github.adobe.sign.core.auth.CredentialLoader;
import io.github.adobe.sign.impl.CliCommand;
import io.github.adobe.sign.impl.CliComponent;
import io.github.adobe.sign.impl.actions.TransientDocument;
import io.github.adobe.sign.impl.auth.BasicSignAuth;
import io.github.adobe.sign.impl.auth.FileCredentialLoader;
import io.github.adobe.sign.impl.executor.BasicWorkflowExecutor;
@CliComponent(name = "Simple Workflow")
public class SimpleWorkflow extends BasicWorkflowExecutor implements CliCommand {
SignAction transientDocument;
@Override
public Options getOptions() {
Options options = new Options();
options.addOption(Option.builder("c").hasArg().required().build());
return options;
}
@Override
public <T> T execute(Class<T> type, List<String> args) throws Exception {
CommandLineParser parser = new DefaultParser();
CommandLine cli = parser.parse(getOptions(), args.stream().toArray(String[]::new));
CredentialLoader credentialLoader = new FileCredentialLoader(cli.getOptionValue("c"));
this.transientDocument = new TransientDocument(credentialLoader);
// Add the work item to the workflow
this.addAction(this.transientDocument);
// Run it
return type.cast(this.invoke(new BasicSignAuth(), null, null));
}
}
|
92425469f083a0a8ae0b8fc6224df0c15fcd7a1d
| 822 |
java
|
Java
|
ScanConsoleApp.java
|
vipulchodankar/sms-java-programming
|
73c42b93022e258adb09efb9c621c0058062ad3c
|
[
"MIT"
] | null | null | null |
ScanConsoleApp.java
|
vipulchodankar/sms-java-programming
|
73c42b93022e258adb09efb9c621c0058062ad3c
|
[
"MIT"
] | null | null | null |
ScanConsoleApp.java
|
vipulchodankar/sms-java-programming
|
73c42b93022e258adb09efb9c621c0058062ad3c
|
[
"MIT"
] | null | null | null | 25.6875 | 50 | 0.618005 | 1,002,219 |
import java.util.*;
public class ScanConsoleApp
{
public static void main(String Args[])
{
Scanner scanner = new Scanner(System.in);
try
{
System.out.println("Enter an Integer :");
int v1=scanner.nextInt();
System.out.println("You entered : "+v1);
System.out.println("Enter a float value :");
float v2=scanner.nextFloat();
System.out.println("You entered : "+v2);
System.out.println("Enter a double value :");
double v3=scanner.nextDouble();
System.out.println("You entered : "+v3);
scanner.nextLine();
System.out.println("Enter a Sentence :");
String v5=scanner.nextLine();
System.out.println("You entered : "+v5);
}
catch(InputMismatchException e)
{
System.out.println("Mismatch exception:"+e);
}
}
}
|
924255906ea8c93f3b4360805c737e2a172602db
| 46,533 |
java
|
Java
|
libuvccamera/src/main/java/com/serenegiant/usb/UVCCamera.java
|
kumaraswins/UVCCamera
|
c9399e63dfab4b6d260d8cbef92182abc6de0ee0
|
[
"Apache-2.0"
] | 2,550 |
2015-01-11T18:03:35.000Z
|
2022-03-31T23:44:07.000Z
|
libuvccamera/src/main/java/com/serenegiant/usb/UVCCamera.java
|
kumaraswins/UVCCamera
|
c9399e63dfab4b6d260d8cbef92182abc6de0ee0
|
[
"Apache-2.0"
] | 617 |
2015-07-12T07:00:45.000Z
|
2022-03-31T07:27:15.000Z
|
libuvccamera/src/main/java/com/serenegiant/usb/UVCCamera.java
|
kumaraswins/UVCCamera
|
c9399e63dfab4b6d260d8cbef92182abc6de0ee0
|
[
"Apache-2.0"
] | 1,083 |
2015-01-27T23:42:34.000Z
|
2022-03-31T05:25:17.000Z
| 37.990204 | 191 | 0.686321 | 1,002,220 |
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2017 saki [email protected]
*
* 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.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the libjpeg-turbo, libusb, libuvc, rapidjson folder
* may have a different license, see the respective files.
*/
package com.serenegiant.usb;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.serenegiant.usb.USBMonitor.UsbControlBlock;
public class UVCCamera {
private static final boolean DEBUG = false; // TODO set false when releasing
private static final String TAG = UVCCamera.class.getSimpleName();
private static final String DEFAULT_USBFS = "/dev/bus/usb";
public static final int DEFAULT_PREVIEW_WIDTH = 640;
public static final int DEFAULT_PREVIEW_HEIGHT = 480;
public static final int DEFAULT_PREVIEW_MODE = 0;
public static final int DEFAULT_PREVIEW_MIN_FPS = 1;
public static final int DEFAULT_PREVIEW_MAX_FPS = 30;
public static final float DEFAULT_BANDWIDTH = 1.0f;
public static final int FRAME_FORMAT_YUYV = 0;
public static final int FRAME_FORMAT_MJPEG = 1;
public static final int PIXEL_FORMAT_RAW = 0;
public static final int PIXEL_FORMAT_YUV = 1;
public static final int PIXEL_FORMAT_RGB565 = 2;
public static final int PIXEL_FORMAT_RGBX = 3;
public static final int PIXEL_FORMAT_YUV420SP = 4;
public static final int PIXEL_FORMAT_NV21 = 5; // = YVU420SemiPlanar
//--------------------------------------------------------------------------------
public static final int CTRL_SCANNING = 0x00000001; // D0: Scanning Mode
public static final int CTRL_AE = 0x00000002; // D1: Auto-Exposure Mode
public static final int CTRL_AE_PRIORITY = 0x00000004; // D2: Auto-Exposure Priority
public static final int CTRL_AE_ABS = 0x00000008; // D3: Exposure Time (Absolute)
public static final int CTRL_AR_REL = 0x00000010; // D4: Exposure Time (Relative)
public static final int CTRL_FOCUS_ABS = 0x00000020; // D5: Focus (Absolute)
public static final int CTRL_FOCUS_REL = 0x00000040; // D6: Focus (Relative)
public static final int CTRL_IRIS_ABS = 0x00000080; // D7: Iris (Absolute)
public static final int CTRL_IRIS_REL = 0x00000100; // D8: Iris (Relative)
public static final int CTRL_ZOOM_ABS = 0x00000200; // D9: Zoom (Absolute)
public static final int CTRL_ZOOM_REL = 0x00000400; // D10: Zoom (Relative)
public static final int CTRL_PANTILT_ABS = 0x00000800; // D11: PanTilt (Absolute)
public static final int CTRL_PANTILT_REL = 0x00001000; // D12: PanTilt (Relative)
public static final int CTRL_ROLL_ABS = 0x00002000; // D13: Roll (Absolute)
public static final int CTRL_ROLL_REL = 0x00004000; // D14: Roll (Relative)
public static final int CTRL_FOCUS_AUTO = 0x00020000; // D17: Focus, Auto
public static final int CTRL_PRIVACY = 0x00040000; // D18: Privacy
public static final int CTRL_FOCUS_SIMPLE = 0x00080000; // D19: Focus, Simple
public static final int CTRL_WINDOW = 0x00100000; // D20: Window
public static final int PU_BRIGHTNESS = 0x80000001; // D0: Brightness
public static final int PU_CONTRAST = 0x80000002; // D1: Contrast
public static final int PU_HUE = 0x80000004; // D2: Hue
public static final int PU_SATURATION = 0x80000008; // D3: Saturation
public static final int PU_SHARPNESS = 0x80000010; // D4: Sharpness
public static final int PU_GAMMA = 0x80000020; // D5: Gamma
public static final int PU_WB_TEMP = 0x80000040; // D6: White Balance Temperature
public static final int PU_WB_COMPO = 0x80000080; // D7: White Balance Component
public static final int PU_BACKLIGHT = 0x80000100; // D8: Backlight Compensation
public static final int PU_GAIN = 0x80000200; // D9: Gain
public static final int PU_POWER_LF = 0x80000400; // D10: Power Line Frequency
public static final int PU_HUE_AUTO = 0x80000800; // D11: Hue, Auto
public static final int PU_WB_TEMP_AUTO = 0x80001000; // D12: White Balance Temperature, Auto
public static final int PU_WB_COMPO_AUTO = 0x80002000; // D13: White Balance Component, Auto
public static final int PU_DIGITAL_MULT = 0x80004000; // D14: Digital Multiplier
public static final int PU_DIGITAL_LIMIT = 0x80008000; // D15: Digital Multiplier Limit
public static final int PU_AVIDEO_STD = 0x80010000; // D16: Analog Video Standard
public static final int PU_AVIDEO_LOCK = 0x80020000; // D17: Analog Video Lock Status
public static final int PU_CONTRAST_AUTO = 0x80040000; // D18: Contrast, Auto
// uvc_status_class from libuvc.h
public static final int STATUS_CLASS_CONTROL = 0x10;
public static final int STATUS_CLASS_CONTROL_CAMERA = 0x11;
public static final int STATUS_CLASS_CONTROL_PROCESSING = 0x12;
// uvc_status_attribute from libuvc.h
public static final int STATUS_ATTRIBUTE_VALUE_CHANGE = 0x00;
public static final int STATUS_ATTRIBUTE_INFO_CHANGE = 0x01;
public static final int STATUS_ATTRIBUTE_FAILURE_CHANGE = 0x02;
public static final int STATUS_ATTRIBUTE_UNKNOWN = 0xff;
private static boolean isLoaded;
static {
if (!isLoaded) {
System.loadLibrary("jpeg-turbo1500");
System.loadLibrary("usb100");
System.loadLibrary("uvc");
System.loadLibrary("UVCCamera");
isLoaded = true;
}
}
private UsbControlBlock mCtrlBlock;
protected long mControlSupports; // カメラコントロールでサポートしている機能フラグ
protected long mProcSupports; // プロセッシングユニットでサポートしている機能フラグ
protected int mCurrentFrameFormat = FRAME_FORMAT_MJPEG;
protected int mCurrentWidth = DEFAULT_PREVIEW_WIDTH, mCurrentHeight = DEFAULT_PREVIEW_HEIGHT;
protected float mCurrentBandwidthFactor = DEFAULT_BANDWIDTH;
protected String mSupportedSize;
protected List<Size> mCurrentSizeList;
// these fields from here are accessed from native code and do not change name and remove
protected long mNativePtr;
protected int mScanningModeMin, mScanningModeMax, mScanningModeDef;
protected int mExposureModeMin, mExposureModeMax, mExposureModeDef;
protected int mExposurePriorityMin, mExposurePriorityMax, mExposurePriorityDef;
protected int mExposureMin, mExposureMax, mExposureDef;
protected int mAutoFocusMin, mAutoFocusMax, mAutoFocusDef;
protected int mFocusMin, mFocusMax, mFocusDef;
protected int mFocusRelMin, mFocusRelMax, mFocusRelDef;
protected int mFocusSimpleMin, mFocusSimpleMax, mFocusSimpleDef;
protected int mIrisMin, mIrisMax, mIrisDef;
protected int mIrisRelMin, mIrisRelMax, mIrisRelDef;
protected int mPanMin, mPanMax, mPanDef;
protected int mTiltMin, mTiltMax, mTiltDef;
protected int mRollMin, mRollMax, mRollDef;
protected int mPanRelMin, mPanRelMax, mPanRelDef;
protected int mTiltRelMin, mTiltRelMax, mTiltRelDef;
protected int mRollRelMin, mRollRelMax, mRollRelDef;
protected int mPrivacyMin, mPrivacyMax, mPrivacyDef;
protected int mAutoWhiteBlanceMin, mAutoWhiteBlanceMax, mAutoWhiteBlanceDef;
protected int mAutoWhiteBlanceCompoMin, mAutoWhiteBlanceCompoMax, mAutoWhiteBlanceCompoDef;
protected int mWhiteBlanceMin, mWhiteBlanceMax, mWhiteBlanceDef;
protected int mWhiteBlanceCompoMin, mWhiteBlanceCompoMax, mWhiteBlanceCompoDef;
protected int mWhiteBlanceRelMin, mWhiteBlanceRelMax, mWhiteBlanceRelDef;
protected int mBacklightCompMin, mBacklightCompMax, mBacklightCompDef;
protected int mBrightnessMin, mBrightnessMax, mBrightnessDef;
protected int mContrastMin, mContrastMax, mContrastDef;
protected int mSharpnessMin, mSharpnessMax, mSharpnessDef;
protected int mGainMin, mGainMax, mGainDef;
protected int mGammaMin, mGammaMax, mGammaDef;
protected int mSaturationMin, mSaturationMax, mSaturationDef;
protected int mHueMin, mHueMax, mHueDef;
protected int mZoomMin, mZoomMax, mZoomDef;
protected int mZoomRelMin, mZoomRelMax, mZoomRelDef;
protected int mPowerlineFrequencyMin, mPowerlineFrequencyMax, mPowerlineFrequencyDef;
protected int mMultiplierMin, mMultiplierMax, mMultiplierDef;
protected int mMultiplierLimitMin, mMultiplierLimitMax, mMultiplierLimitDef;
protected int mAnalogVideoStandardMin, mAnalogVideoStandardMax, mAnalogVideoStandardDef;
protected int mAnalogVideoLockStateMin, mAnalogVideoLockStateMax, mAnalogVideoLockStateDef;
// until here
/**
* the sonctructor of this class should be call within the thread that has a looper
* (UI thread or a thread that called Looper.prepare)
*/
public UVCCamera() {
mNativePtr = nativeCreate();
mSupportedSize = null;
}
/**
* connect to a UVC camera
* USB permission is necessary before this method is called
* @param ctrlBlock
*/
public synchronized void open(final UsbControlBlock ctrlBlock) {
int result;
try {
mCtrlBlock = ctrlBlock.clone();
result = nativeConnect(mNativePtr,
mCtrlBlock.getVenderId(), mCtrlBlock.getProductId(),
mCtrlBlock.getFileDescriptor(),
mCtrlBlock.getBusNum(),
mCtrlBlock.getDevNum(),
getUSBFSName(mCtrlBlock));
} catch (final Exception e) {
Log.w(TAG, e);
result = -1;
}
if (result != 0) {
throw new UnsupportedOperationException("open failed:result=" + result);
}
if (mNativePtr != 0 && TextUtils.isEmpty(mSupportedSize)) {
mSupportedSize = nativeGetSupportedSize(mNativePtr);
}
nativeSetPreviewSize(mNativePtr, DEFAULT_PREVIEW_WIDTH, DEFAULT_PREVIEW_HEIGHT,
DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, DEFAULT_PREVIEW_MODE, DEFAULT_BANDWIDTH);
}
/**
* set status callback
* @param callback
*/
public void setStatusCallback(final IStatusCallback callback) {
if (mNativePtr != 0) {
nativeSetStatusCallback(mNativePtr, callback);
}
}
/**
* set button callback
* @param callback
*/
public void setButtonCallback(final IButtonCallback callback) {
if (mNativePtr != 0) {
nativeSetButtonCallback(mNativePtr, callback);
}
}
/**
* close and release UVC camera
*/
public synchronized void close() {
stopPreview();
if (mNativePtr != 0) {
nativeRelease(mNativePtr);
// mNativePtr = 0; // nativeDestroyを呼ぶのでここでクリアしちゃダメ
}
if (mCtrlBlock != null) {
mCtrlBlock.close();
mCtrlBlock = null;
}
mControlSupports = mProcSupports = 0;
mCurrentFrameFormat = -1;
mCurrentBandwidthFactor = 0;
mSupportedSize = null;
mCurrentSizeList = null;
if (DEBUG) Log.v(TAG, "close:finished");
}
public UsbDevice getDevice() {
return mCtrlBlock != null ? mCtrlBlock.getDevice() : null;
}
public String getDeviceName(){
return mCtrlBlock != null ? mCtrlBlock.getDeviceName() : null;
}
public UsbControlBlock getUsbControlBlock() {
return mCtrlBlock;
}
public synchronized String getSupportedSize() {
return !TextUtils.isEmpty(mSupportedSize) ? mSupportedSize : (mSupportedSize = nativeGetSupportedSize(mNativePtr));
}
public Size getPreviewSize() {
Size result = null;
final List<Size> list = getSupportedSizeList();
for (final Size sz: list) {
if ((sz.width == mCurrentWidth)
|| (sz.height == mCurrentHeight)) {
result =sz;
break;
}
}
return result;
}
/**
* Set preview size and preview mode
* @param width
@param height
*/
public void setPreviewSize(final int width, final int height) {
setPreviewSize(width, height, DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, mCurrentFrameFormat, mCurrentBandwidthFactor);
}
/**
* Set preview size and preview mode
* @param width
* @param height
* @param frameFormat either FRAME_FORMAT_YUYV(0) or FRAME_FORMAT_MJPEG(1)
*/
public void setPreviewSize(final int width, final int height, final int frameFormat) {
setPreviewSize(width, height, DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, frameFormat, mCurrentBandwidthFactor);
}
/**
* Set preview size and preview mode
* @param width
@param height
@param frameFormat either FRAME_FORMAT_YUYV(0) or FRAME_FORMAT_MJPEG(1)
@param bandwidth [0.0f,1.0f]
*/
public void setPreviewSize(final int width, final int height, final int frameFormat, final float bandwidth) {
setPreviewSize(width, height, DEFAULT_PREVIEW_MIN_FPS, DEFAULT_PREVIEW_MAX_FPS, frameFormat, bandwidth);
}
/**
* Set preview size and preview mode
* @param width
* @param height
* @param min_fps
* @param max_fps
* @param frameFormat either FRAME_FORMAT_YUYV(0) or FRAME_FORMAT_MJPEG(1)
* @param bandwidthFactor
*/
public void setPreviewSize(final int width, final int height, final int min_fps, final int max_fps, final int frameFormat, final float bandwidthFactor) {
if ((width == 0) || (height == 0))
throw new IllegalArgumentException("invalid preview size");
if (mNativePtr != 0) {
final int result = nativeSetPreviewSize(mNativePtr, width, height, min_fps, max_fps, frameFormat, bandwidthFactor);
if (result != 0)
throw new IllegalArgumentException("Failed to set preview size");
mCurrentFrameFormat = frameFormat;
mCurrentWidth = width;
mCurrentHeight = height;
mCurrentBandwidthFactor = bandwidthFactor;
}
}
public List<Size> getSupportedSizeList() {
final int type = (mCurrentFrameFormat > 0) ? 6 : 4;
return getSupportedSize(type, mSupportedSize);
}
public static List<Size> getSupportedSize(final int type, final String supportedSize) {
final List<Size> result = new ArrayList<Size>();
if (!TextUtils.isEmpty(supportedSize))
try {
final JSONObject json = new JSONObject(supportedSize);
final JSONArray formats = json.getJSONArray("formats");
final int format_nums = formats.length();
for (int i = 0; i < format_nums; i++) {
final JSONObject format = formats.getJSONObject(i);
if(format.has("type") && format.has("size")) {
final int format_type = format.getInt("type");
if ((format_type == type) || (type == -1)) {
addSize(format, format_type, 0, result);
}
}
}
} catch (final JSONException e) {
e.printStackTrace();
}
return result;
}
private static final void addSize(final JSONObject format, final int formatType, final int frameType, final List<Size> size_list) throws JSONException {
final JSONArray size = format.getJSONArray("size");
final int size_nums = size.length();
for (int j = 0; j < size_nums; j++) {
final String[] sz = size.getString(j).split("x");
try {
size_list.add(new Size(formatType, frameType, j, Integer.parseInt(sz[0]), Integer.parseInt(sz[1])));
} catch (final Exception e) {
break;
}
}
}
/**
* set preview surface with SurfaceHolder</br>
* you can use SurfaceHolder came from SurfaceView/GLSurfaceView
* @param holder
*/
public synchronized void setPreviewDisplay(final SurfaceHolder holder) {
nativeSetPreviewDisplay(mNativePtr, holder.getSurface());
}
/**
* set preview surface with SurfaceTexture.
* this method require API >= 14
* @param texture
*/
public synchronized void setPreviewTexture(final SurfaceTexture texture) { // API >= 11
final Surface surface = new Surface(texture); // XXX API >= 14
nativeSetPreviewDisplay(mNativePtr, surface);
}
/**
* set preview surface with Surface
* @param surface
*/
public synchronized void setPreviewDisplay(final Surface surface) {
nativeSetPreviewDisplay(mNativePtr, surface);
}
/**
* set frame callback
* @param callback
* @param pixelFormat
*/
public void setFrameCallback(final IFrameCallback callback, final int pixelFormat) {
if (mNativePtr != 0) {
nativeSetFrameCallback(mNativePtr, callback, pixelFormat);
}
}
/**
* start preview
*/
public synchronized void startPreview() {
if (mCtrlBlock != null) {
nativeStartPreview(mNativePtr);
}
}
/**
* stop preview
*/
public synchronized void stopPreview() {
setFrameCallback(null, 0);
if (mCtrlBlock != null) {
nativeStopPreview(mNativePtr);
}
}
/**
* destroy UVCCamera object
*/
public synchronized void destroy() {
close();
if (mNativePtr != 0) {
nativeDestroy(mNativePtr);
mNativePtr = 0;
}
}
// wrong result may return when you call this just after camera open.
// it is better to wait several hundreads millseconds.
public boolean checkSupportFlag(final long flag) {
updateCameraParams();
if ((flag & 0x80000000) == 0x80000000)
return ((mProcSupports & flag) == (flag & 0x7ffffffF));
else
return (mControlSupports & flag) == flag;
}
//================================================================================
public synchronized void setAutoFocus(final boolean autoFocus) {
if (mNativePtr != 0) {
nativeSetAutoFocus(mNativePtr, autoFocus);
}
}
public synchronized boolean getAutoFocus() {
boolean result = true;
if (mNativePtr != 0) {
result = nativeGetAutoFocus(mNativePtr) > 0;
}
return result;
}
//================================================================================
/**
* @param focus [%]
*/
public synchronized void setFocus(final int focus) {
if (mNativePtr != 0) {
final float range = Math.abs(mFocusMax - mFocusMin);
if (range > 0)
nativeSetFocus(mNativePtr, (int)(focus / 100.f * range) + mFocusMin);
}
}
/**
* @param focus_abs
* @return focus[%]
*/
public synchronized int getFocus(final int focus_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateFocusLimit(mNativePtr);
final float range = Math.abs(mFocusMax - mFocusMin);
if (range > 0) {
result = (int)((focus_abs - mFocusMin) * 100.f / range);
}
}
return result;
}
/**
* @return focus[%]
*/
public synchronized int getFocus() {
return getFocus(nativeGetFocus(mNativePtr));
}
public synchronized void resetFocus() {
if (mNativePtr != 0) {
nativeSetFocus(mNativePtr, mFocusDef);
}
}
//================================================================================
public synchronized void setAutoWhiteBlance(final boolean autoWhiteBlance) {
if (mNativePtr != 0) {
nativeSetAutoWhiteBlance(mNativePtr, autoWhiteBlance);
}
}
public synchronized boolean getAutoWhiteBlance() {
boolean result = true;
if (mNativePtr != 0) {
result = nativeGetAutoWhiteBlance(mNativePtr) > 0;
}
return result;
}
//================================================================================
/**
* @param whiteBlance [%]
*/
public synchronized void setWhiteBlance(final int whiteBlance) {
if (mNativePtr != 0) {
final float range = Math.abs(mWhiteBlanceMax - mWhiteBlanceMin);
if (range > 0)
nativeSetWhiteBlance(mNativePtr, (int)(whiteBlance / 100.f * range) + mWhiteBlanceMin);
}
}
/**
* @param whiteBlance_abs
* @return whiteBlance[%]
*/
public synchronized int getWhiteBlance(final int whiteBlance_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateWhiteBlanceLimit(mNativePtr);
final float range = Math.abs(mWhiteBlanceMax - mWhiteBlanceMin);
if (range > 0) {
result = (int)((whiteBlance_abs - mWhiteBlanceMin) * 100.f / range);
}
}
return result;
}
/**
* @return white blance[%]
*/
public synchronized int getWhiteBlance() {
return getFocus(nativeGetWhiteBlance(mNativePtr));
}
public synchronized void resetWhiteBlance() {
if (mNativePtr != 0) {
nativeSetWhiteBlance(mNativePtr, mWhiteBlanceDef);
}
}
//================================================================================
/**
* @param brightness [%]
*/
public synchronized void setBrightness(final int brightness) {
if (mNativePtr != 0) {
final float range = Math.abs(mBrightnessMax - mBrightnessMin);
if (range > 0)
nativeSetBrightness(mNativePtr, (int)(brightness / 100.f * range) + mBrightnessMin);
}
}
/**
* @param brightness_abs
* @return brightness[%]
*/
public synchronized int getBrightness(final int brightness_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateBrightnessLimit(mNativePtr);
final float range = Math.abs(mBrightnessMax - mBrightnessMin);
if (range > 0) {
result = (int)((brightness_abs - mBrightnessMin) * 100.f / range);
}
}
return result;
}
/**
* @return brightness[%]
*/
public synchronized int getBrightness() {
return getBrightness(nativeGetBrightness(mNativePtr));
}
public synchronized void resetBrightness() {
if (mNativePtr != 0) {
nativeSetBrightness(mNativePtr, mBrightnessDef);
}
}
//================================================================================
/**
* @param contrast [%]
*/
public synchronized void setContrast(final int contrast) {
if (mNativePtr != 0) {
nativeUpdateContrastLimit(mNativePtr);
final float range = Math.abs(mContrastMax - mContrastMin);
if (range > 0)
nativeSetContrast(mNativePtr, (int)(contrast / 100.f * range) + mContrastMin);
}
}
/**
* @param contrast_abs
* @return contrast[%]
*/
public synchronized int getContrast(final int contrast_abs) {
int result = 0;
if (mNativePtr != 0) {
final float range = Math.abs(mContrastMax - mContrastMin);
if (range > 0) {
result = (int)((contrast_abs - mContrastMin) * 100.f / range);
}
}
return result;
}
/**
* @return contrast[%]
*/
public synchronized int getContrast() {
return getContrast(nativeGetContrast(mNativePtr));
}
public synchronized void resetContrast() {
if (mNativePtr != 0) {
nativeSetContrast(mNativePtr, mContrastDef);
}
}
//================================================================================
/**
* @param sharpness [%]
*/
public synchronized void setSharpness(final int sharpness) {
if (mNativePtr != 0) {
final float range = Math.abs(mSharpnessMax - mSharpnessMin);
if (range > 0)
nativeSetSharpness(mNativePtr, (int)(sharpness / 100.f * range) + mSharpnessMin);
}
}
/**
* @param sharpness_abs
* @return sharpness[%]
*/
public synchronized int getSharpness(final int sharpness_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateSharpnessLimit(mNativePtr);
final float range = Math.abs(mSharpnessMax - mSharpnessMin);
if (range > 0) {
result = (int)((sharpness_abs - mSharpnessMin) * 100.f / range);
}
}
return result;
}
/**
* @return sharpness[%]
*/
public synchronized int getSharpness() {
return getSharpness(nativeGetSharpness(mNativePtr));
}
public synchronized void resetSharpness() {
if (mNativePtr != 0) {
nativeSetSharpness(mNativePtr, mSharpnessDef);
}
}
//================================================================================
/**
* @param gain [%]
*/
public synchronized void setGain(final int gain) {
if (mNativePtr != 0) {
final float range = Math.abs(mGainMax - mGainMin);
if (range > 0)
nativeSetGain(mNativePtr, (int)(gain / 100.f * range) + mGainMin);
}
}
/**
* @param gain_abs
* @return gain[%]
*/
public synchronized int getGain(final int gain_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateGainLimit(mNativePtr);
final float range = Math.abs(mGainMax - mGainMin);
if (range > 0) {
result = (int)((gain_abs - mGainMin) * 100.f / range);
}
}
return result;
}
/**
* @return gain[%]
*/
public synchronized int getGain() {
return getGain(nativeGetGain(mNativePtr));
}
public synchronized void resetGain() {
if (mNativePtr != 0) {
nativeSetGain(mNativePtr, mGainDef);
}
}
//================================================================================
/**
* @param gamma [%]
*/
public synchronized void setGamma(final int gamma) {
if (mNativePtr != 0) {
final float range = Math.abs(mGammaMax - mGammaMin);
if (range > 0)
nativeSetGamma(mNativePtr, (int)(gamma / 100.f * range) + mGammaMin);
}
}
/**
* @param gamma_abs
* @return gamma[%]
*/
public synchronized int getGamma(final int gamma_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateGammaLimit(mNativePtr);
final float range = Math.abs(mGammaMax - mGammaMin);
if (range > 0) {
result = (int)((gamma_abs - mGammaMin) * 100.f / range);
}
}
return result;
}
/**
* @return gamma[%]
*/
public synchronized int getGamma() {
return getGamma(nativeGetGamma(mNativePtr));
}
public synchronized void resetGamma() {
if (mNativePtr != 0) {
nativeSetGamma(mNativePtr, mGammaDef);
}
}
//================================================================================
/**
* @param saturation [%]
*/
public synchronized void setSaturation(final int saturation) {
if (mNativePtr != 0) {
final float range = Math.abs(mSaturationMax - mSaturationMin);
if (range > 0)
nativeSetSaturation(mNativePtr, (int)(saturation / 100.f * range) + mSaturationMin);
}
}
/**
* @param saturation_abs
* @return saturation[%]
*/
public synchronized int getSaturation(final int saturation_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateSaturationLimit(mNativePtr);
final float range = Math.abs(mSaturationMax - mSaturationMin);
if (range > 0) {
result = (int)((saturation_abs - mSaturationMin) * 100.f / range);
}
}
return result;
}
/**
* @return saturation[%]
*/
public synchronized int getSaturation() {
return getSaturation(nativeGetSaturation(mNativePtr));
}
public synchronized void resetSaturation() {
if (mNativePtr != 0) {
nativeSetSaturation(mNativePtr, mSaturationDef);
}
}
//================================================================================
/**
* @param hue [%]
*/
public synchronized void setHue(final int hue) {
if (mNativePtr != 0) {
final float range = Math.abs(mHueMax - mHueMin);
if (range > 0)
nativeSetHue(mNativePtr, (int)(hue / 100.f * range) + mHueMin);
}
}
/**
* @param hue_abs
* @return hue[%]
*/
public synchronized int getHue(final int hue_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateHueLimit(mNativePtr);
final float range = Math.abs(mHueMax - mHueMin);
if (range > 0) {
result = (int)((hue_abs - mHueMin) * 100.f / range);
}
}
return result;
}
/**
* @return hue[%]
*/
public synchronized int getHue() {
return getHue(nativeGetHue(mNativePtr));
}
public synchronized void resetHue() {
if (mNativePtr != 0) {
nativeSetHue(mNativePtr, mSaturationDef);
}
}
//================================================================================
public void setPowerlineFrequency(final int frequency) {
if (mNativePtr != 0)
nativeSetPowerlineFrequency(mNativePtr, frequency);
}
public int getPowerlineFrequency() {
return nativeGetPowerlineFrequency(mNativePtr);
}
//================================================================================
/**
* this may not work well with some combination of camera and device
* @param zoom [%]
*/
public synchronized void setZoom(final int zoom) {
if (mNativePtr != 0) {
final float range = Math.abs(mZoomMax - mZoomMin);
if (range > 0) {
final int z = (int)(zoom / 100.f * range) + mZoomMin;
// Log.d(TAG, "setZoom:zoom=" + zoom + " ,value=" + z);
nativeSetZoom(mNativePtr, z);
}
}
}
/**
* @param zoom_abs
* @return zoom[%]
*/
public synchronized int getZoom(final int zoom_abs) {
int result = 0;
if (mNativePtr != 0) {
nativeUpdateZoomLimit(mNativePtr);
final float range = Math.abs(mZoomMax - mZoomMin);
if (range > 0) {
result = (int)((zoom_abs - mZoomMin) * 100.f / range);
}
}
return result;
}
/**
* @return zoom[%]
*/
public synchronized int getZoom() {
return getZoom(nativeGetZoom(mNativePtr));
}
public synchronized void resetZoom() {
if (mNativePtr != 0) {
nativeSetZoom(mNativePtr, mZoomDef);
}
}
//================================================================================
public synchronized void updateCameraParams() {
if (mNativePtr != 0) {
if ((mControlSupports == 0) || (mProcSupports == 0)) {
// サポートしている機能フラグを取得
if (mControlSupports == 0)
mControlSupports = nativeGetCtrlSupports(mNativePtr);
if (mProcSupports == 0)
mProcSupports = nativeGetProcSupports(mNativePtr);
// 設定値を取得
if ((mControlSupports != 0) && (mProcSupports != 0)) {
nativeUpdateBrightnessLimit(mNativePtr);
nativeUpdateContrastLimit(mNativePtr);
nativeUpdateSharpnessLimit(mNativePtr);
nativeUpdateGainLimit(mNativePtr);
nativeUpdateGammaLimit(mNativePtr);
nativeUpdateSaturationLimit(mNativePtr);
nativeUpdateHueLimit(mNativePtr);
nativeUpdateZoomLimit(mNativePtr);
nativeUpdateWhiteBlanceLimit(mNativePtr);
nativeUpdateFocusLimit(mNativePtr);
}
if (DEBUG) {
dumpControls(mControlSupports);
dumpProc(mProcSupports);
Log.v(TAG, String.format("Brightness:min=%d,max=%d,def=%d", mBrightnessMin, mBrightnessMax, mBrightnessDef));
Log.v(TAG, String.format("Contrast:min=%d,max=%d,def=%d", mContrastMin, mContrastMax, mContrastDef));
Log.v(TAG, String.format("Sharpness:min=%d,max=%d,def=%d", mSharpnessMin, mSharpnessMax, mSharpnessDef));
Log.v(TAG, String.format("Gain:min=%d,max=%d,def=%d", mGainMin, mGainMax, mGainDef));
Log.v(TAG, String.format("Gamma:min=%d,max=%d,def=%d", mGammaMin, mGammaMax, mGammaDef));
Log.v(TAG, String.format("Saturation:min=%d,max=%d,def=%d", mSaturationMin, mSaturationMax, mSaturationDef));
Log.v(TAG, String.format("Hue:min=%d,max=%d,def=%d", mHueMin, mHueMax, mHueDef));
Log.v(TAG, String.format("Zoom:min=%d,max=%d,def=%d", mZoomMin, mZoomMax, mZoomDef));
Log.v(TAG, String.format("WhiteBlance:min=%d,max=%d,def=%d", mWhiteBlanceMin, mWhiteBlanceMax, mWhiteBlanceDef));
Log.v(TAG, String.format("Focus:min=%d,max=%d,def=%d", mFocusMin, mFocusMax, mFocusDef));
}
}
} else {
mControlSupports = mProcSupports = 0;
}
}
private static final String[] SUPPORTS_CTRL = {
"D0: Scanning Mode",
"D1: Auto-Exposure Mode",
"D2: Auto-Exposure Priority",
"D3: Exposure Time (Absolute)",
"D4: Exposure Time (Relative)",
"D5: Focus (Absolute)",
"D6: Focus (Relative)",
"D7: Iris (Absolute)",
"D8: Iris (Relative)",
"D9: Zoom (Absolute)",
"D10: Zoom (Relative)",
"D11: PanTilt (Absolute)",
"D12: PanTilt (Relative)",
"D13: Roll (Absolute)",
"D14: Roll (Relative)",
"D15: Reserved",
"D16: Reserved",
"D17: Focus, Auto",
"D18: Privacy",
"D19: Focus, Simple",
"D20: Window",
"D21: Region of Interest",
"D22: Reserved, set to zero",
"D23: Reserved, set to zero",
};
private static final String[] SUPPORTS_PROC = {
"D0: Brightness",
"D1: Contrast",
"D2: Hue",
"D3: Saturation",
"D4: Sharpness",
"D5: Gamma",
"D6: White Balance Temperature",
"D7: White Balance Component",
"D8: Backlight Compensation",
"D9: Gain",
"D10: Power Line Frequency",
"D11: Hue, Auto",
"D12: White Balance Temperature, Auto",
"D13: White Balance Component, Auto",
"D14: Digital Multiplier",
"D15: Digital Multiplier Limit",
"D16: Analog Video Standard",
"D17: Analog Video Lock Status",
"D18: Contrast, Auto",
"D19: Reserved. Set to zero",
"D20: Reserved. Set to zero",
"D21: Reserved. Set to zero",
"D22: Reserved. Set to zero",
"D23: Reserved. Set to zero",
};
private static final void dumpControls(final long controlSupports) {
Log.i(TAG, String.format("controlSupports=%x", controlSupports));
for (int i = 0; i < SUPPORTS_CTRL.length; i++) {
Log.i(TAG, SUPPORTS_CTRL[i] + ((controlSupports & (0x1 << i)) != 0 ? "=enabled" : "=disabled"));
}
}
private static final void dumpProc(final long procSupports) {
Log.i(TAG, String.format("procSupports=%x", procSupports));
for (int i = 0; i < SUPPORTS_PROC.length; i++) {
Log.i(TAG, SUPPORTS_PROC[i] + ((procSupports & (0x1 << i)) != 0 ? "=enabled" : "=disabled"));
}
}
private final String getUSBFSName(final UsbControlBlock ctrlBlock) {
String result = null;
final String name = ctrlBlock.getDeviceName();
final String[] v = !TextUtils.isEmpty(name) ? name.split("/") : null;
if ((v != null) && (v.length > 2)) {
final StringBuilder sb = new StringBuilder(v[0]);
for (int i = 1; i < v.length - 2; i++)
sb.append("/").append(v[i]);
result = sb.toString();
}
if (TextUtils.isEmpty(result)) {
Log.w(TAG, "failed to get USBFS path, try to use default path:" + name);
result = DEFAULT_USBFS;
}
return result;
}
// #nativeCreate and #nativeDestroy are not static methods.
private final native long nativeCreate();
private final native void nativeDestroy(final long id_camera);
private final native int nativeConnect(long id_camera, int venderId, int productId, int fileDescriptor, int busNum, int devAddr, String usbfs);
private static final native int nativeRelease(final long id_camera);
private static final native int nativeSetStatusCallback(final long mNativePtr, final IStatusCallback callback);
private static final native int nativeSetButtonCallback(final long mNativePtr, final IButtonCallback callback);
private static final native int nativeSetPreviewSize(final long id_camera, final int width, final int height, final int min_fps, final int max_fps, final int mode, final float bandwidth);
private static final native String nativeGetSupportedSize(final long id_camera);
private static final native int nativeStartPreview(final long id_camera);
private static final native int nativeStopPreview(final long id_camera);
private static final native int nativeSetPreviewDisplay(final long id_camera, final Surface surface);
private static final native int nativeSetFrameCallback(final long mNativePtr, final IFrameCallback callback, final int pixelFormat);
//**********************************************************************
/**
* start movie capturing(this should call while previewing)
* @param surface
*/
public void startCapture(final Surface surface) {
if (mCtrlBlock != null && surface != null) {
nativeSetCaptureDisplay(mNativePtr, surface);
} else
throw new NullPointerException("startCapture");
}
/**
* stop movie capturing
*/
public void stopCapture() {
if (mCtrlBlock != null) {
nativeSetCaptureDisplay(mNativePtr, null);
}
}
private static final native int nativeSetCaptureDisplay(final long id_camera, final Surface surface);
private static final native long nativeGetCtrlSupports(final long id_camera);
private static final native long nativeGetProcSupports(final long id_camera);
private final native int nativeUpdateScanningModeLimit(final long id_camera);
private static final native int nativeSetScanningMode(final long id_camera, final int scanning_mode);
private static final native int nativeGetScanningMode(final long id_camera);
private final native int nativeUpdateExposureModeLimit(final long id_camera);
private static final native int nativeSetExposureMode(final long id_camera, final int exposureMode);
private static final native int nativeGetExposureMode(final long id_camera);
private final native int nativeUpdateExposurePriorityLimit(final long id_camera);
private static final native int nativeSetExposurePriority(final long id_camera, final int priority);
private static final native int nativeGetExposurePriority(final long id_camera);
private final native int nativeUpdateExposureLimit(final long id_camera);
private static final native int nativeSetExposure(final long id_camera, final int exposure);
private static final native int nativeGetExposure(final long id_camera);
private final native int nativeUpdateExposureRelLimit(final long id_camera);
private static final native int nativeSetExposureRel(final long id_camera, final int exposure_rel);
private static final native int nativeGetExposureRel(final long id_camera);
private final native int nativeUpdateAutoFocusLimit(final long id_camera);
private static final native int nativeSetAutoFocus(final long id_camera, final boolean autofocus);
private static final native int nativeGetAutoFocus(final long id_camera);
private final native int nativeUpdateFocusLimit(final long id_camera);
private static final native int nativeSetFocus(final long id_camera, final int focus);
private static final native int nativeGetFocus(final long id_camera);
private final native int nativeUpdateFocusRelLimit(final long id_camera);
private static final native int nativeSetFocusRel(final long id_camera, final int focus_rel);
private static final native int nativeGetFocusRel(final long id_camera);
private final native int nativeUpdateIrisLimit(final long id_camera);
private static final native int nativeSetIris(final long id_camera, final int iris);
private static final native int nativeGetIris(final long id_camera);
private final native int nativeUpdateIrisRelLimit(final long id_camera);
private static final native int nativeSetIrisRel(final long id_camera, final int iris_rel);
private static final native int nativeGetIrisRel(final long id_camera);
private final native int nativeUpdatePanLimit(final long id_camera);
private static final native int nativeSetPan(final long id_camera, final int pan);
private static final native int nativeGetPan(final long id_camera);
private final native int nativeUpdatePanRelLimit(final long id_camera);
private static final native int nativeSetPanRel(final long id_camera, final int pan_rel);
private static final native int nativeGetPanRel(final long id_camera);
private final native int nativeUpdateTiltLimit(final long id_camera);
private static final native int nativeSetTilt(final long id_camera, final int tilt);
private static final native int nativeGetTilt(final long id_camera);
private final native int nativeUpdateTiltRelLimit(final long id_camera);
private static final native int nativeSetTiltRel(final long id_camera, final int tilt_rel);
private static final native int nativeGetTiltRel(final long id_camera);
private final native int nativeUpdateRollLimit(final long id_camera);
private static final native int nativeSetRoll(final long id_camera, final int roll);
private static final native int nativeGetRoll(final long id_camera);
private final native int nativeUpdateRollRelLimit(final long id_camera);
private static final native int nativeSetRollRel(final long id_camera, final int roll_rel);
private static final native int nativeGetRollRel(final long id_camera);
private final native int nativeUpdateAutoWhiteBlanceLimit(final long id_camera);
private static final native int nativeSetAutoWhiteBlance(final long id_camera, final boolean autoWhiteBlance);
private static final native int nativeGetAutoWhiteBlance(final long id_camera);
private final native int nativeUpdateAutoWhiteBlanceCompoLimit(final long id_camera);
private static final native int nativeSetAutoWhiteBlanceCompo(final long id_camera, final boolean autoWhiteBlanceCompo);
private static final native int nativeGetAutoWhiteBlanceCompo(final long id_camera);
private final native int nativeUpdateWhiteBlanceLimit(final long id_camera);
private static final native int nativeSetWhiteBlance(final long id_camera, final int whiteBlance);
private static final native int nativeGetWhiteBlance(final long id_camera);
private final native int nativeUpdateWhiteBlanceCompoLimit(final long id_camera);
private static final native int nativeSetWhiteBlanceCompo(final long id_camera, final int whiteBlance_compo);
private static final native int nativeGetWhiteBlanceCompo(final long id_camera);
private final native int nativeUpdateBacklightCompLimit(final long id_camera);
private static final native int nativeSetBacklightComp(final long id_camera, final int backlight_comp);
private static final native int nativeGetBacklightComp(final long id_camera);
private final native int nativeUpdateBrightnessLimit(final long id_camera);
private static final native int nativeSetBrightness(final long id_camera, final int brightness);
private static final native int nativeGetBrightness(final long id_camera);
private final native int nativeUpdateContrastLimit(final long id_camera);
private static final native int nativeSetContrast(final long id_camera, final int contrast);
private static final native int nativeGetContrast(final long id_camera);
private final native int nativeUpdateAutoContrastLimit(final long id_camera);
private static final native int nativeSetAutoContrast(final long id_camera, final boolean autocontrast);
private static final native int nativeGetAutoContrast(final long id_camera);
private final native int nativeUpdateSharpnessLimit(final long id_camera);
private static final native int nativeSetSharpness(final long id_camera, final int sharpness);
private static final native int nativeGetSharpness(final long id_camera);
private final native int nativeUpdateGainLimit(final long id_camera);
private static final native int nativeSetGain(final long id_camera, final int gain);
private static final native int nativeGetGain(final long id_camera);
private final native int nativeUpdateGammaLimit(final long id_camera);
private static final native int nativeSetGamma(final long id_camera, final int gamma);
private static final native int nativeGetGamma(final long id_camera);
private final native int nativeUpdateSaturationLimit(final long id_camera);
private static final native int nativeSetSaturation(final long id_camera, final int saturation);
private static final native int nativeGetSaturation(final long id_camera);
private final native int nativeUpdateHueLimit(final long id_camera);
private static final native int nativeSetHue(final long id_camera, final int hue);
private static final native int nativeGetHue(final long id_camera);
private final native int nativeUpdateAutoHueLimit(final long id_camera);
private static final native int nativeSetAutoHue(final long id_camera, final boolean autohue);
private static final native int nativeGetAutoHue(final long id_camera);
private final native int nativeUpdatePowerlineFrequencyLimit(final long id_camera);
private static final native int nativeSetPowerlineFrequency(final long id_camera, final int frequency);
private static final native int nativeGetPowerlineFrequency(final long id_camera);
private final native int nativeUpdateZoomLimit(final long id_camera);
private static final native int nativeSetZoom(final long id_camera, final int zoom);
private static final native int nativeGetZoom(final long id_camera);
private final native int nativeUpdateZoomRelLimit(final long id_camera);
private static final native int nativeSetZoomRel(final long id_camera, final int zoom_rel);
private static final native int nativeGetZoomRel(final long id_camera);
private final native int nativeUpdateDigitalMultiplierLimit(final long id_camera);
private static final native int nativeSetDigitalMultiplier(final long id_camera, final int multiplier);
private static final native int nativeGetDigitalMultiplier(final long id_camera);
private final native int nativeUpdateDigitalMultiplierLimitLimit(final long id_camera);
private static final native int nativeSetDigitalMultiplierLimit(final long id_camera, final int multiplier_limit);
private static final native int nativeGetDigitalMultiplierLimit(final long id_camera);
private final native int nativeUpdateAnalogVideoStandardLimit(final long id_camera);
private static final native int nativeSetAnalogVideoStandard(final long id_camera, final int standard);
private static final native int nativeGetAnalogVideoStandard(final long id_camera);
private final native int nativeUpdateAnalogVideoLockStateLimit(final long id_camera);
private static final native int nativeSetAnalogVideoLoackState(final long id_camera, final int state);
private static final native int nativeGetAnalogVideoLoackState(final long id_camera);
private final native int nativeUpdatePrivacyLimit(final long id_camera);
private static final native int nativeSetPrivacy(final long id_camera, final boolean privacy);
private static final native int nativeGetPrivacy(final long id_camera);
}
|
924255a6af505387ec5cfa3a351fa8b0088ddf7a
| 727 |
java
|
Java
|
src/main/java/ru/r2cloud/jradio/strand1/SwitchBoard.java
|
dernasherbrezon/jradio
|
ec86db80ab6b36b6222bb0d3978abba89f555ac4
|
[
"Apache-2.0"
] | 40 |
2017-04-11T06:25:22.000Z
|
2022-03-24T17:44:20.000Z
|
src/main/java/ru/r2cloud/jradio/strand1/SwitchBoard.java
|
dernasherbrezon/jradio
|
ec86db80ab6b36b6222bb0d3978abba89f555ac4
|
[
"Apache-2.0"
] | 6 |
2019-01-24T13:53:53.000Z
|
2021-04-26T16:54:33.000Z
|
src/main/java/ru/r2cloud/jradio/strand1/SwitchBoard.java
|
dernasherbrezon/jradio
|
ec86db80ab6b36b6222bb0d3978abba89f555ac4
|
[
"Apache-2.0"
] | 10 |
2017-04-11T06:25:26.000Z
|
2022-02-05T16:50:44.000Z
| 16.155556 | 72 | 0.709766 | 1,002,221 |
package ru.r2cloud.jradio.strand1;
public class SwitchBoard {
private SwitchStatus status;
private float current;
private float voltage;
public SwitchBoard() {
// do nothing
}
public SwitchBoard(SwitchStatus status, float current, float voltage) {
super();
this.status = status;
this.current = current;
this.voltage = voltage;
}
public SwitchStatus getStatus() {
return status;
}
public void setStatus(SwitchStatus status) {
this.status = status;
}
public float getCurrent() {
return current;
}
public void setCurrent(float current) {
this.current = current;
}
public float getVoltage() {
return voltage;
}
public void setVoltage(float voltage) {
this.voltage = voltage;
}
}
|
924255f7c6aaf084af3b9c39c39833261f46077e
| 3,102 |
java
|
Java
|
mysql-server/storage/ndb/clusterj/clusterj-test/src/main/java/testsuite/clusterj/model/DateAsUtilDateTypes.java
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/storage/ndb/clusterj/clusterj-test/src/main/java/testsuite/clusterj/model/DateAsUtilDateTypes.java
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null |
mysql-server/storage/ndb/clusterj/clusterj-test/src/main/java/testsuite/clusterj/model/DateAsUtilDateTypes.java
|
silenc3502/MYSQL-Arch-Doc-Summary
|
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
|
[
"MIT"
] | null | null | null | 33.717391 | 87 | 0.781109 | 1,002,222 |
/*
Copyright 2010 Sun Microsystems, Inc.
Use is subject to license terms.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package testsuite.clusterj.model;
import com.mysql.clusterj.annotation.Column;
import com.mysql.clusterj.annotation.Index;
import com.mysql.clusterj.annotation.Indices;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;
import java.util.Date;
/** Schema
*
drop table if exists datetypes;
create table datetypes (
id int not null primary key,
date_null_hash date,
date_null_btree date,
date_null_both date,
date_null_none date,
date_not_null_hash date,
date_not_null_btree date,
date_not_null_both date,
date_not_null_none date
) ENGINE=ndbcluster DEFAULT CHARSET=latin1;
create unique index idx_date_null_hash using hash on datetypes(date_null_hash);
create index idx_date_null_btree on datetypes(date_null_btree);
create unique index idx_date_null_both on datetypes(date_null_both);
create unique index idx_date_not_null_hash using hash on datetypes(date_not_null_hash);
create index idx_date_not_null_btree on datetypes(date_not_null_btree);
create unique index idx_date_not_null_both on datetypes(date_not_null_both);
*/
@Indices({
@Index(name="idx_date_not_null_both", columns=@Column(name="date_not_null_both"))
})
@PersistenceCapable(table="datetypes")
@PrimaryKey(column="id")
public interface DateAsUtilDateTypes extends IdBase {
int getId();
void setId(int id);
// Date
@Column(name="date_not_null_hash")
@Index(name="idx_date_not_null_hash")
Date getDate_not_null_hash();
void setDate_not_null_hash(Date value);
@Column(name="date_not_null_btree")
@Index(name="idx_date_not_null_btree")
Date getDate_not_null_btree();
void setDate_not_null_btree(Date value);
@Column(name="date_not_null_both")
Date getDate_not_null_both();
void setDate_not_null_both(Date value);
@Column(name="date_not_null_none")
Date getDate_not_null_none();
void setDate_not_null_none(Date value);
}
|
924255f9a9c8f72d91e61e6bb0bd71c8eeb2e952
| 4,110 |
java
|
Java
|
CompilerGenerator/src/Back/LLVMGenerator.java
|
GeckoDev/simple-compiler
|
a120630dd81209ac0a68f38c06d5973edc695a1d
|
[
"MIT"
] | null | null | null |
CompilerGenerator/src/Back/LLVMGenerator.java
|
GeckoDev/simple-compiler
|
a120630dd81209ac0a68f38c06d5973edc695a1d
|
[
"MIT"
] | null | null | null |
CompilerGenerator/src/Back/LLVMGenerator.java
|
GeckoDev/simple-compiler
|
a120630dd81209ac0a68f38c06d5973edc695a1d
|
[
"MIT"
] | null | null | null | 33.145161 | 168 | 0.486131 | 1,002,223 |
package Back;
class LLVMGenerator {
static String header_text = "";
static String main_text = "";
static int reg = 1;
static void printf_i32(String id) {
main_text += "%" + reg + " = load i32, i32* %" + id + "\n";
reg++;
main_text += "%" + reg + " = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @strpi, i32 0, i32 0), i32 %" + (reg - 1) + ")\n";
reg++;
}
static void printf_double(String id) {
main_text += "%" + reg + " = load double, double* %" + id + "\n";
reg++;
main_text += "%" + reg + " = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @strpd, i32 0, i32 0), double %" + (reg - 1) + ")\n";
reg++;
}
static void declare_i32(String id) {
main_text += "%" + id + " = alloca i32\n";
}
static void declare_double(String id) {
main_text += "%" + id + " = alloca double\n";
}
static void assign_i32(String id, String value) {
main_text += "store i32 " + value + ", i32* %" + id + "\n";
}
static void assign_double(String id, String value) {
main_text += "store double " + value + ", double* %" + id + "\n";
}
static void load_i32(String id) {
main_text += "%" + reg + " = load i32, i32* %" + id + "\n";
reg++;
}
static void load_double(String id) {
main_text += "%" + reg + " = load double, double* %" + id + "\n";
reg++;
}
static void add_i32(String val1, String val2) {
main_text += "%" + reg + " = add i32 " + val1 + ", " + val2 + "\n";
reg++;
}
static void add_double(String val1, String val2) {
main_text += "%" + reg + " = fadd double " + val1 + ", " + val2 + "\n";
reg++;
}
static void mult_i32(String val1, String val2) {
main_text += "%" + reg + " = mul i32 " + val1 + ", " + val2 + "\n";
reg++;
}
static void mult_double(String val1, String val2) {
main_text += "%" + reg + " = fmul double " + val1 + ", " + val2 + "\n";
reg++;
}
static void sitofp(String id) {
main_text += "%" + reg + " = sitofp i32 " + id + " to double\n";
reg++;
}
static void fptosi(String id) {
main_text += "%" + reg + " = fptosi double " + id + " to i32\n";
reg++;
}
public static void readInt32(String id) {
main_text += "%" + reg + " = call i32 (i8*, ...) @__isoc99_scanf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @strs, i32 0, i32 0), i32* %" + id + ")\n";
reg++;
}
public static void readDouble(String id) {
main_text += "%" + reg + " = call i32 (i8*, ...) @__isoc99_scanf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @strsd, i32 0, i32 0), double* %" + id + ")\n";
reg++;
}
static String generate() {
String text = "";
text += "declare i32 @printf(i8*, ...)\n";
text += "declare i32 @__isoc99_scanf(i8*, ...)\n";
text += "@strpi = constant [4 x i8] c\"%d\\0A\\00\"\n";
text += "@strpd = constant [4 x i8] c\"%f\\0A\\00\"\n";
text += "@strs = constant [3 x i8] c\"%d\\00\"\n";
text += "@strsd = constant [4 x i8] c\"%lf\\00\"\n";
text += header_text;
text += "define i32 @main() nounwind{\n";
text += main_text;
text += "ret i32 0 }\n";
return text;
}
public static void substract_i32(String value, String value1) {
main_text += "%" + reg + " = sub i32 " + value + ", " + value1 + "\n";
reg++;
}
public static void substract_double(String value, String value1) {
main_text += "%" + reg + " = fsub double " + value + ", " + value1 + "\n";
reg++;
}
public static void div_i32(String value, String value1) {
main_text += "%" + reg + " = sdiv i32 " + value + ", " + value1 + "\n";
reg++;
}
public static void div_double(String value, String value1) {
main_text += "%" + reg + " = fdiv double " + value + ", " + value1 + "\n";
reg++;
}
}
|
924256cc2b3e3df6c508cdfb5d1d4611d11c147a
| 1,612 |
java
|
Java
|
src/main/java/com/servioticy/api/identity/Identity.java
|
servioticy/servioticy-api-identity
|
2607c9eb323fd5f93ed8d94a246f383cb1ef128d
|
[
"Artistic-2.0"
] | null | null | null |
src/main/java/com/servioticy/api/identity/Identity.java
|
servioticy/servioticy-api-identity
|
2607c9eb323fd5f93ed8d94a246f383cb1ef128d
|
[
"Artistic-2.0"
] | null | null | null |
src/main/java/com/servioticy/api/identity/Identity.java
|
servioticy/servioticy-api-identity
|
2607c9eb323fd5f93ed8d94a246f383cb1ef128d
|
[
"Artistic-2.0"
] | null | null | null | 31.607843 | 110 | 0.630893 | 1,002,224 |
package com.servioticy.api.identity;
import java.sql.SQLException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import com.servioticy.api.identity.exceptions.IdentityWebApplicationException;
import com.servioticy.api.identity.utils.Config;
@Path("/")
public class Identity {
@Path("/{userMail}")
@GET
public Response getOrpostAuthToken(@Context HttpHeaders hh, @PathParam("userMail") String userMail) {
String response = null;
try {
response = Config.mySQL.portalGetToken(userMail);
} catch (SQLException e) {
throw new IdentityWebApplicationException(Response.Status.BAD_REQUEST,
"SQLException: " + e.getMessage());
}
return Response.ok(response).build();
}
@Path("/auth/{userId}")
@GET
public Response getAuthToken(@Context HttpHeaders hh, @PathParam("userId") String userId, String body) {
String response = null;
try {
response = Config.mySQL.userIdGetToken(userId);
if (response == null)
throw new IdentityWebApplicationException(Response.Status.BAD_REQUEST, "User does not exist");
} catch (SQLException e) {
throw new IdentityWebApplicationException(Response.Status.BAD_REQUEST,
"SQLException: " + e.getMessage());
}
return Response.ok(response).build();
}
}
|
92425701193434bb3effe155d99f8b25dfd3ddc2
| 1,868 |
java
|
Java
|
src/Input.java
|
TUO-V/Grade_Calculator
|
99d0c61b8acec5b15e632326fa2d07d6261d8f76
|
[
"MIT"
] | 1 |
2022-03-21T21:07:00.000Z
|
2022-03-21T21:07:00.000Z
|
src/Input.java
|
TUO-V/Grade_Calculator
|
99d0c61b8acec5b15e632326fa2d07d6261d8f76
|
[
"MIT"
] | null | null | null |
src/Input.java
|
TUO-V/Grade_Calculator
|
99d0c61b8acec5b15e632326fa2d07d6261d8f76
|
[
"MIT"
] | null | null | null | 29.1875 | 99 | 0.544968 | 1,002,225 |
import java.util.InputMismatchException;
import java.util.Scanner;
public class Input {
private static int Subject_Number = 0;
public Input(String Subject, String Subject_Type) {
Subject_Number++;
System.out.print(Subject + " Grade: ");
int Grade = Input_Grade();
Data.Add_Grade("Unweighted_Aggregate_Grade", Grade);
switch (Subject_Type) {
case "AP" -> Data.Add_Grade("Weighted_Aggregate_Grade", Grade * 1.1);
case "Honor" -> Data.Add_Grade("Weighted_Aggregate_Grade", Grade * 1.05);
default -> Data.Add_Grade("Weighted_Aggregate_Grade", Grade);
}
}
public static double Get_Number() {
return Subject_Number;
}
public static void Reset_Number() {
Subject_Number = 0;
}
/*
Title: Java判断输入的是不是数字?
Author: 99 little bugs in the code..
Date: 2021-11-27
Availability: https://blog.csdn.net/weixin_53731984/article/details/121580502
*/
public static int Input_Grade() {
//初始化变量
int result = 0;
//循环判断
boolean is1 = true;
//循环
while (is1) {
//循环创建扫描仪对象
Scanner sc = new Scanner(System.in);
//try catch块
try {
//写入预测会报错的代码块
result = sc.nextInt();
//如果控制台没有报错,将终结循环,否则执行catch块,循环录入
is1 = false;
if (result < 0 || result > 100) {
System.out.println("Grade out of boundary, please type your grade correctly.");
is1 = true;
}
//捕获报错
} catch (InputMismatchException e) {
//如果捕获到此报错类型,则执行以下代码
System.out.println("Illegal grade, please type your grade correctly.");
}
}
return result;
}
}
|
9242571ba2cb347d0bd00a77c2060175b6922934
| 804 |
java
|
Java
|
src/com/littlechoc/leetcode/algorithms/best_time_to_buy_and_sell_stock_with_cooldown/Solution.java
|
junhaozhou/leetcode
|
e814431dc90a3e96a83a5e2aa18f935ade4cd127
|
[
"MIT"
] | null | null | null |
src/com/littlechoc/leetcode/algorithms/best_time_to_buy_and_sell_stock_with_cooldown/Solution.java
|
junhaozhou/leetcode
|
e814431dc90a3e96a83a5e2aa18f935ade4cd127
|
[
"MIT"
] | null | null | null |
src/com/littlechoc/leetcode/algorithms/best_time_to_buy_and_sell_stock_with_cooldown/Solution.java
|
junhaozhou/leetcode
|
e814431dc90a3e96a83a5e2aa18f935ade4cd127
|
[
"MIT"
] | null | null | null | 25.125 | 122 | 0.631841 | 1,002,226 |
package com.littlechoc.leetcode.algorithms.best_time_to_buy_and_sell_stock_with_cooldown;
/**
* Problem 309. See in <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/">LeetCode</a>
*
* @author 周俊皓.
* 2016-08-04 14:24
*/
public class Solution {
public int maxProfit(int[] prices) {
int state_1, state_2, state_3;
if (prices.length == 0) {
return 0;
}
// init
state_1 = 0;
state_2 = -prices[0];
state_3 = Integer.MIN_VALUE;
// begin
for (int day = 1; day < prices.length; day++) {
int state_1_tmp = state_1;
state_1 = Math.max(state_1, state_3);
state_2 = Math.max(state_2, state_1_tmp - prices[day]);
state_3 = state_2 + prices[day];
}
return Math.max(state_1, state_3);
}
}
|
924257493592e46b78602fdaf20311efffe4747d
| 2,335 |
java
|
Java
|
hoodie-client/src/main/java/com/uber/hoodie/metrics/Metrics.java
|
arw357/hudi_hive_2
|
42744fff38f9ab498638d3444c4378359369844d
|
[
"Apache-2.0"
] | 1 |
2020-04-28T09:44:36.000Z
|
2020-04-28T09:44:36.000Z
|
hoodie-client/src/main/java/com/uber/hoodie/metrics/Metrics.java
|
arw357/hudi_hive_2
|
42744fff38f9ab498638d3444c4378359369844d
|
[
"Apache-2.0"
] | 4 |
2021-01-21T01:43:11.000Z
|
2021-12-09T22:52:22.000Z
|
hoodie-client/src/main/java/com/uber/hoodie/metrics/Metrics.java
|
arw357/hudi_hive_2
|
42744fff38f9ab498638d3444c4378359369844d
|
[
"Apache-2.0"
] | 1 |
2019-02-08T04:47:24.000Z
|
2019-02-08T04:47:24.000Z
| 28.228916 | 81 | 0.702518 | 1,002,227 |
/*
* Copyright (c) 2016 Uber Technologies, Inc. ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uber.hoodie.metrics;
import com.codahale.metrics.MetricRegistry;
import com.google.common.io.Closeables;
import com.uber.hoodie.config.HoodieWriteConfig;
import com.uber.hoodie.exception.HoodieException;
import java.io.Closeable;
import org.apache.commons.configuration.ConfigurationException;
/**
* This is the main class of the metrics system.
*/
public class Metrics {
private static volatile boolean initialized = false;
private static Metrics metrics = null;
private final MetricRegistry registry;
private MetricsReporter reporter = null;
private Metrics(HoodieWriteConfig metricConfig) throws ConfigurationException {
registry = new MetricRegistry();
reporter = MetricsReporterFactory.createReporter(metricConfig, registry);
if (reporter == null) {
throw new RuntimeException("Cannot initialize Reporter.");
}
// reporter.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
reporter.report();
Closeables.close(reporter.getReporter(), true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static Metrics getInstance() {
assert initialized;
return metrics;
}
public static synchronized void init(HoodieWriteConfig metricConfig) {
if (initialized) {
return;
}
try {
metrics = new Metrics(metricConfig);
} catch (ConfigurationException e) {
throw new HoodieException(e);
}
initialized = true;
}
public MetricRegistry getRegistry() {
return registry;
}
public Closeable getReporter() {
return reporter.getReporter();
}
}
|
924258ad097d759e17f5648a786090d6fcf9d88d
| 326 |
java
|
Java
|
Apollo/src/com/apollo/Message.java
|
egyware/fp4g
|
60ebb5bde0c52ea60b62bcf3e87aa5e799d7f49b
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
Apollo/src/com/apollo/Message.java
|
egyware/fp4g
|
60ebb5bde0c52ea60b62bcf3e87aa5e799d7f49b
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
Apollo/src/com/apollo/Message.java
|
egyware/fp4g
|
60ebb5bde0c52ea60b62bcf3e87aa5e799d7f49b
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 14.173913 | 52 | 0.687117 | 1,002,228 |
package com.apollo;
/**
* Interface for Messages
* @author egyware
*
*/
public abstract class Message
{
private boolean isConsumed = false;
public abstract Class<? extends Message> getType();
public final boolean isConsumed()
{
return isConsumed;
}
public final void consume()
{
isConsumed = true;
}
}
|
924259346573f9af4d68b73e484518e99d34e4ec
| 4,558 |
java
|
Java
|
menu/api/src/main/java/team/unnamed/gui/menu/type/PaginatedMenuInventory.java
|
MineAqua/gui
|
5ca841a620132b7761cd53e9b57e5ed0f235eaf8
|
[
"MIT"
] | null | null | null |
menu/api/src/main/java/team/unnamed/gui/menu/type/PaginatedMenuInventory.java
|
MineAqua/gui
|
5ca841a620132b7761cd53e9b57e5ed0f235eaf8
|
[
"MIT"
] | null | null | null |
menu/api/src/main/java/team/unnamed/gui/menu/type/PaginatedMenuInventory.java
|
MineAqua/gui
|
5ca841a620132b7761cd53e9b57e5ed0f235eaf8
|
[
"MIT"
] | null | null | null | 35.609375 | 89 | 0.637999 | 1,002,229 |
package team.unnamed.gui.menu.type;
import org.bukkit.inventory.Inventory;
import team.unnamed.gui.menu.item.ItemClickable;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
public class PaginatedMenuInventory<E> extends DefaultMenuInventory {
private final int entitySlotFrom;
private final int availableEntitySlots;
private final List<Integer> availableSlots;
private final int maxPages;
private final List<E> entities;
private final int currentPage;
private final List<String> layoutLines;
private final Map<Character, ItemClickable> layoutItems;
private final Function<E, ItemClickable> entityParser;
private final Function<Integer, ItemClickable> previousPageItem;
private final Function<Integer, ItemClickable> nextPageItem;
private final ItemClickable itemIfNoEntities;
private final ItemClickable itemIfNoPreviousPage;
private final ItemClickable itemIfNoNextPage;
protected PaginatedMenuInventory(String title, int slots,
List<ItemClickable> items,
Predicate<Inventory> openAction,
Predicate<Inventory> closeAction,
boolean canIntroduceItems,
int entitySlotFrom, int availableEntitySlots,
List<Integer> availableSlots, List<E> entities,
int currentPage, List<String> layoutLines,
Map<Character, ItemClickable> layoutItems,
Function<E, ItemClickable> entityParser,
Function<Integer, ItemClickable> previousPageItem,
Function<Integer, ItemClickable> nextPageItem,
ItemClickable itemIfNoEntities,
ItemClickable itemIfNoPreviousPage,
ItemClickable itemIfNoNextPage) {
super(title, slots, items, openAction, closeAction, canIntroduceItems);
this.entitySlotFrom = entitySlotFrom;
this.availableEntitySlots = availableEntitySlots;
this.availableSlots = availableSlots;
this.maxPages = (int) Math.ceil(entities.size() / (double) availableEntitySlots);
this.entities = entities;
this.currentPage = currentPage;
this.layoutLines = layoutLines;
this.layoutItems = layoutItems;
this.entityParser = entityParser;
this.previousPageItem = previousPageItem;
this.nextPageItem = nextPageItem;
this.itemIfNoEntities = itemIfNoEntities;
this.itemIfNoPreviousPage = itemIfNoPreviousPage;
this.itemIfNoNextPage = itemIfNoNextPage;
}
public int getEntitySlotFrom() {
return entitySlotFrom;
}
public List<Integer> getAvailableSlots() {
return availableSlots;
}
public int getAvailableEntitySlots() {
return availableEntitySlots;
}
public int getMaxPages() {
return maxPages;
}
public int getCurrentPage() {
return currentPage;
}
public List<E> getEntities() {
return entities;
}
public List<String> getLayoutLines() {
return layoutLines;
}
public Map<Character, ItemClickable> getLayoutItems() {
return layoutItems;
}
public Function<E, ItemClickable> getEntityParser() {
return entityParser;
}
public Function<Integer, ItemClickable> getPreviousPageItem() {
return previousPageItem;
}
public Function<Integer, ItemClickable> getNextPageItem() {
return nextPageItem;
}
public ItemClickable getItemIfNoEntities() {
return itemIfNoEntities;
}
public ItemClickable getItemIfNoPreviousPage() {
return itemIfNoPreviousPage;
}
public ItemClickable getItemIfNoNextPage() {
return itemIfNoNextPage;
}
public PaginatedMenuInventory<E> clone(int page) {
return new PaginatedMenuInventory<>(
title, slots, items, openAction, closeAction, canIntroduceItems,
entitySlotFrom, availableEntitySlots, availableSlots,
entities, page, layoutLines, layoutItems, entityParser,
previousPageItem, nextPageItem, itemIfNoEntities,
itemIfNoPreviousPage, itemIfNoNextPage
);
}
}
|
924259f21f73778902f68b307f6df48aa691289e
| 416 |
java
|
Java
|
arena/src/main/java/ch/bfh/aspfb/arena/ArenaApplication.java
|
peroxid/aspfb
|
6535d4ebc2ed119ef508d834b9a6173448fc38fd
|
[
"BSD-2-Clause"
] | null | null | null |
arena/src/main/java/ch/bfh/aspfb/arena/ArenaApplication.java
|
peroxid/aspfb
|
6535d4ebc2ed119ef508d834b9a6173448fc38fd
|
[
"BSD-2-Clause"
] | null | null | null |
arena/src/main/java/ch/bfh/aspfb/arena/ArenaApplication.java
|
peroxid/aspfb
|
6535d4ebc2ed119ef508d834b9a6173448fc38fd
|
[
"BSD-2-Clause"
] | null | null | null | 27.733333 | 72 | 0.8125 | 1,002,230 |
package ch.bfh.aspfb.arena;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ArenaApplication {
public static void main(String[] args) {
SpringApplication.run(ArenaApplication.class, args);
}
}
|
92425aa3f72465cd3c7ef7ba4ab3ffa85af3bf59
| 1,765 |
java
|
Java
|
Application/src/main/java/com/example/android/bluetoothlegatt/DeleteLogFiles.java
|
thegofar/Carb-Scan-App
|
5bdfadea5b8e047f1b3a4675c6d301f04323fe07
|
[
"Apache-2.0"
] | null | null | null |
Application/src/main/java/com/example/android/bluetoothlegatt/DeleteLogFiles.java
|
thegofar/Carb-Scan-App
|
5bdfadea5b8e047f1b3a4675c6d301f04323fe07
|
[
"Apache-2.0"
] | null | null | null |
Application/src/main/java/com/example/android/bluetoothlegatt/DeleteLogFiles.java
|
thegofar/Carb-Scan-App
|
5bdfadea5b8e047f1b3a4675c6d301f04323fe07
|
[
"Apache-2.0"
] | null | null | null | 34.607843 | 85 | 0.550708 | 1,002,231 |
package com.example.android.bluetoothlegatt;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import java.io.File;
public class DeleteLogFiles extends Activity {
Intent intent = getIntent();
File f =(File) intent.getExtras().get("FILE_PATH");
//boolean callEmailLogsProcess = intent.getBooleanExtra("FILES_REMAINING",false);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_delete_log_files);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle("Delete File")
.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Delete", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// delete code lives here
f.delete();
dialog.dismiss();
//finishActivity(Activity.RESULT_OK);
finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
finishActivity(Activity.RESULT_OK);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
|
92425b0ccd307b4e639240470a0f7190399b3662
| 6,433 |
java
|
Java
|
Server/src/main/java/com/studiowannabe/trafalert/control/MainController.java
|
Tombio/Trafalert
|
531e1f291132853ff5bc01475faf9ce2bf67e9eb
|
[
"MIT"
] | 1 |
2016-04-08T16:19:25.000Z
|
2016-04-08T16:19:25.000Z
|
Server/src/main/java/com/studiowannabe/trafalert/control/MainController.java
|
Tombio/Trafalert
|
531e1f291132853ff5bc01475faf9ce2bf67e9eb
|
[
"MIT"
] | 1 |
2016-02-17T07:41:51.000Z
|
2016-02-26T07:27:35.000Z
|
Server/src/main/java/com/studiowannabe/trafalert/control/MainController.java
|
Tombio/Trafalert
|
531e1f291132853ff5bc01475faf9ce2bf67e9eb
|
[
"MIT"
] | null | null | null | 46.280576 | 118 | 0.71413 | 1,002,232 |
package com.studiowannabe.trafalert.control;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.studiowannabe.trafalert.domain.StationInfo;
import com.studiowannabe.trafalert.domain.json.GrouppedStations;
import com.studiowannabe.trafalert.domain.warning.Warning;
import com.studiowannabe.trafalert.domain.WeatherInfo;
import com.studiowannabe.trafalert.domain.WeatherStationData;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by Tomi on 30/01/16.
*/
@RestController
@CommonsLog
public class MainController {
private final WeatherDataCache cache;
private final WarningCache warningCache;
private final ObjectMapper objectMapper;
private final StationGroupping stationGroupping;
private final WeatherCalculator calculator;
@Autowired
public MainController(final WeatherDataCache cache, final WarningCache warningCache,
final ObjectMapper objectMapper, final StationGroupping stationGroupping,
final WeatherCalculator calculator) {
this.cache = cache;
this.warningCache = warningCache;
this.objectMapper = objectMapper;
this.stationGroupping = stationGroupping;
this.calculator = calculator;
}
@RequestMapping(value = "/warning/{region}/{version}", method = RequestMethod.POST, produces = "application/json")
public String warningsForRegion(@PathVariable(value = "region") final Long region,
@PathVariable(value = "version") final Long version) throws Exception {
final List<Warning> warnings = getWarningsForRegion(region);
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(warnings);
}
@RequestMapping(value = "/warning", method = RequestMethod.POST, produces = "application/json")
public String warningsForRegion() throws Exception {
final List<WeatherInfo> infos = getAllStationsWithWarnings();
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(infos);
}
@RequestMapping(value = "/warning/stations", method = RequestMethod.POST, produces = "application/json")
public String stationsWithWarning() throws Exception {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(getStationIdsWithWarning());
}
@RequestMapping(value = "/weather/{region}", method = RequestMethod.POST, produces = "application/json")
public String weatherForRegion(@PathVariable(value = "region") final Long region) throws Exception {
final WeatherStationData wsd = getWeatherForRegion(region);
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(wsd);
}
@RequestMapping(value = "/info/{region}", method = RequestMethod.POST, produces = "application/json")
public String fullInfoForRegion(@PathVariable(value = "region") final Long region) throws Exception {
final WeatherStationData wsd = getWeatherForRegion(region);
final List<Warning> warnings = warningCache.getCacheData().get(region);
final WeatherInfo wi = new WeatherInfo(wsd.getStationId(), wsd, warnings);
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(wi);
}
@RequestMapping(value = "/info", method = RequestMethod.POST, produces = "application/json")
public String allRegions() throws Exception {
final List<WeatherInfo> infos = getAllStationsAndWarnings();
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(infos);
}
@Cacheable
@RequestMapping(value = "/meta/station", method = RequestMethod.POST, produces = "application/json")
public String metaStations() throws Exception {
final GrouppedStations stations = new GrouppedStations();
for(final HashMap.Entry<Long, List<StationInfo>> entry : stationGroupping.getStationGroups().entrySet()) {
stations.addGroup(new GrouppedStations.StationGroup(entry.getKey(), entry.getValue()));
}
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(stations.getStationGroup());
}
private List<Warning> getWarningsForRegion(final long region) {
return warningCache.getCacheData().get(region);
}
private WeatherStationData getWeatherForRegion(final long region) {
return calculator.calculateData(region);
}
private List<WeatherInfo> getAllStationsAndWarnings() {
final List<WeatherInfo> infos = new ArrayList<WeatherInfo>();
for(final Long id : stationGroupping.getStationGroups().keySet()) {
final StationInfo info = stationGroupping.getStationGroups().get(id).get(0); // Ugly, yeah :p
final List<Warning> warnings = warningCache.getCacheData().get(id);
final WeatherInfo wi = new WeatherInfo(id, cache.getCacheData().get(info.getId()).getLeft(), warnings);
infos.add(wi);
}
return infos;
}
private List<WeatherInfo> getAllStationsWithWarnings() {
try {
final List<WeatherInfo> infos = new ArrayList<WeatherInfo>();
for (final Long id : stationGroupping.getStationGroups().keySet()) {
final List<Warning> warnings = warningCache.getCacheData().get(id);
if (!CollectionUtils.isEmpty(warnings)) {
final WeatherInfo wi = new WeatherInfo(id, null, warnings);
infos.add(wi);
}
}
return infos;
}
catch (Exception e) {
log.info("Error fetching warnings", e);
throw e;
}
}
private List<Long> getStationIdsWithWarning() {
final List<WeatherInfo> warningStations = getAllStationsWithWarnings();
return warningStations.stream().map(station -> station.getStationId()).collect(Collectors.toList());
}
}
|
92425b8a08d67169d0c4d223eb5aecae8014cb79
| 2,124 |
java
|
Java
|
spring-cloud-gcp-autoconfigure/src/test/java/org/springframework/cloud/gcp/autoconfigure/logging/extractors/XCloudTraceIdExtractorTests.java
|
danielmenezesbr/spring-cloud-gcp
|
abcc909898b53575ff8dfc2387b557a4a2d7ff19
|
[
"Apache-2.0"
] | null | null | null |
spring-cloud-gcp-autoconfigure/src/test/java/org/springframework/cloud/gcp/autoconfigure/logging/extractors/XCloudTraceIdExtractorTests.java
|
danielmenezesbr/spring-cloud-gcp
|
abcc909898b53575ff8dfc2387b557a4a2d7ff19
|
[
"Apache-2.0"
] | null | null | null |
spring-cloud-gcp-autoconfigure/src/test/java/org/springframework/cloud/gcp/autoconfigure/logging/extractors/XCloudTraceIdExtractorTests.java
|
danielmenezesbr/spring-cloud-gcp
|
abcc909898b53575ff8dfc2387b557a4a2d7ff19
|
[
"Apache-2.0"
] | null | null | null | 30.342857 | 94 | 0.788136 | 1,002,233 |
/*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.gcp.autoconfigure.logging.extractors;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Mike Eltsufin
* @author Chengyuan Zhao
*/
public class XCloudTraceIdExtractorTests {
private static final String TEST_TRACE_ID = "105445aa7843bc8bf206b120001000";
private static final String TEST_TRACE_ID_WITH_SPAN = "105445aa7843bc8bf206b120001000/0;o=1";
private static final String TRACE_ID_HEADER = "X-CLOUD-TRACE-CONTEXT";
private XCloudTraceIdExtractor extractor = new XCloudTraceIdExtractor();
@Test
public void testExtractTraceIdFromRequest_valid() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(TRACE_ID_HEADER, TEST_TRACE_ID_WITH_SPAN);
String traceId = this.extractor.extractTraceIdFromRequest(request);
assertThat(traceId).isEqualTo(TEST_TRACE_ID);
}
@Test
public void testExtractTraceIdFromRequest_missing() {
MockHttpServletRequest request = new MockHttpServletRequest();
String traceId = this.extractor.extractTraceIdFromRequest(request);
assertThat(traceId).isNull();
}
@Test
public void testExtractTraceIdFromRequest_missingSpan() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(TRACE_ID_HEADER, TEST_TRACE_ID);
String traceId = this.extractor.extractTraceIdFromRequest(request);
assertThat(traceId).isEqualTo(TEST_TRACE_ID);
}
}
|
92425bac0cbd556228e0fee2cb47bdadee4fa13e
| 9,749 |
java
|
Java
|
server/src/test/java/com/decathlon/ara/web/rest/FunctionalityResourceMoveIT.java
|
youaxa/ara-poc-open
|
ebec1e751f34bf56930230c2476fbc536b7303a5
|
[
"Apache-2.0"
] | null | null | null |
server/src/test/java/com/decathlon/ara/web/rest/FunctionalityResourceMoveIT.java
|
youaxa/ara-poc-open
|
ebec1e751f34bf56930230c2476fbc536b7303a5
|
[
"Apache-2.0"
] | 1 |
2022-03-02T05:08:06.000Z
|
2022-03-02T05:08:06.000Z
|
server/src/test/java/com/decathlon/ara/web/rest/FunctionalityResourceMoveIT.java
|
youaxa/ara-poc-open
|
ebec1e751f34bf56930230c2476fbc536b7303a5
|
[
"Apache-2.0"
] | null | null | null | 49.48731 | 159 | 0.729613 | 1,002,234 |
package com.decathlon.ara.web.rest;
import com.decathlon.ara.domain.Functionality;
import com.decathlon.ara.repository.FunctionalityRepository;
import com.decathlon.ara.service.dto.functionality.FunctionalityDTO;
import com.decathlon.ara.service.dto.request.FunctionalityPosition;
import com.decathlon.ara.service.dto.request.MoveFunctionalityDTO;
import com.decathlon.ara.util.TransactionalSpringIntegrationTest;
import com.decathlon.ara.web.rest.util.HeaderUtil;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import static com.decathlon.ara.util.TestUtil.NONEXISTENT;
import static com.decathlon.ara.util.TestUtil.header;
import static com.decathlon.ara.util.TestUtil.longs;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@TransactionalSpringIntegrationTest
@DatabaseSetup("/dbunit/functionality.xml")
public class FunctionalityResourceMoveIT {
private static final String PROJECT_CODE = "p";
@Autowired
private FunctionalityRepository functionalityRepository;
@Autowired
private FunctionalityResource cut;
@Test
public void testMoveNonexistentSource() {
ResponseEntity<FunctionalityDTO> response = move(NONEXISTENT.longValue(), Long.valueOf(1), FunctionalityPosition.LAST_CHILD);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(header(response, HeaderUtil.ERROR)).isEqualTo("error.not_found");
assertThat(header(response, HeaderUtil.MESSAGE)).isEqualTo("The functionality or folder to move does not exist: it has perhaps been removed.");
assertThat(header(response, HeaderUtil.PARAMS)).isEqualTo("functionality");
}
@Test
public void testMoveNonexistentDestination() {
ResponseEntity<FunctionalityDTO> response = move(1, NONEXISTENT, FunctionalityPosition.LAST_CHILD);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(header(response, HeaderUtil.ERROR)).isEqualTo("error.not_found");
assertThat(header(response, HeaderUtil.MESSAGE)).isEqualTo("The functionality or folder where to insert does not exist: it has perhaps been removed.");
assertThat(header(response, HeaderUtil.PARAMS)).isEqualTo("functionality");
}
@Test
public void testMoveIntoAFunctionality() {
ResponseEntity<FunctionalityDTO> response = move(1, Long.valueOf(31), FunctionalityPosition.LAST_CHILD);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(header(response, HeaderUtil.ERROR)).isEqualTo("error.functionalities_cannot_have_children");
assertThat(header(response, HeaderUtil.MESSAGE)).isEqualTo("Functionality cannot have children.");
assertThat(header(response, HeaderUtil.PARAMS)).isEqualTo("functionality");
}
@Test
public void testMoveIntoItself() {
ResponseEntity<FunctionalityDTO> response = move(1, Long.valueOf(1), FunctionalityPosition.LAST_CHILD);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(header(response, HeaderUtil.ERROR)).isEqualTo("error.cannot_move_to_itself_or_sub_folder");
assertThat(header(response, HeaderUtil.MESSAGE)).isEqualTo("You cannot move a folder or functionality to itself or a sub-folder.");
assertThat(header(response, HeaderUtil.PARAMS)).isEqualTo("functionality");
}
@Test
public void testMoveIntoASubFolderOfItself() {
ResponseEntity<FunctionalityDTO> response = move(1, Long.valueOf(11), FunctionalityPosition.LAST_CHILD);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(header(response, HeaderUtil.ERROR)).isEqualTo("error.cannot_move_to_itself_or_sub_folder");
assertThat(header(response, HeaderUtil.MESSAGE)).isEqualTo("You cannot move a folder or functionality to itself or a sub-folder.");
assertThat(header(response, HeaderUtil.PARAMS)).isEqualTo("functionality");
}
@Test
public void testMoveToTopOfFolder() {
final long id = 113;
ResponseEntity<FunctionalityDTO> response = move(id, Long.valueOf(111), FunctionalityPosition.ABOVE);
assertMoved(response, id, Long.valueOf(11), 500);
assertChildren(Long.valueOf(11), longs(113, 111, 112));
}
@Test
public void testMoveBelowFirstOfFolder() {
final long id = 113;
ResponseEntity<FunctionalityDTO> response = move(id, Long.valueOf(111), FunctionalityPosition.BELOW);
assertMoved(response, id, Long.valueOf(11), 1500);
assertChildren(Long.valueOf(11), longs(111, 113, 112));
}
@Test
public void testMoveAboveLastOfFolder() {
final long id = 111;
ResponseEntity<FunctionalityDTO> response = move(id, Long.valueOf(113), FunctionalityPosition.ABOVE);
assertMoved(response, id, Long.valueOf(11), 2500);
assertChildren(Long.valueOf(11), longs(112, 111, 113));
}
@Test
public void testMoveToBottomOfFolder() {
final long id = 111;
ResponseEntity<FunctionalityDTO> response = move(id, Long.valueOf(113), FunctionalityPosition.BELOW);
assertMoved(response, id, Long.valueOf(11), 1500 + Double.MAX_VALUE / 2);
assertChildren(Long.valueOf(11), longs(112, 113, 111));
}
@Test
public void testMoveFunctionalityIntoAnotherFolder() {
final long id = 111;
ResponseEntity<FunctionalityDTO> response = move(id, Long.valueOf(21), FunctionalityPosition.LAST_CHILD);
assertMoved(response, id, Long.valueOf(21), Double.MAX_VALUE / 2);
assertChildren(Long.valueOf(11), longs(112, 113));
assertChildren(Long.valueOf(21), longs(111));
}
@Test
public void testMoveFunctionalityNextToAnotherFolderInRoot() {
final long id = 112;
ResponseEntity<FunctionalityDTO> response = move(id, Long.valueOf(2), FunctionalityPosition.ABOVE);
assertMoved(response, id, null, 1500);
assertChildren(Long.valueOf(11), longs(111, 113));
assertChildren(null, longs(1, 112, 2, 3));
}
@Test
public void testMoveFunctionalityAppendingItToRoot() {
final long id = 112;
ResponseEntity<FunctionalityDTO> response = move(id, null, FunctionalityPosition.LAST_CHILD);
assertMoved(response, id, null, 1500 + Double.MAX_VALUE / 2);
assertChildren(Long.valueOf(11), longs(111, 113));
assertChildren(null, longs(1, 2, 3, 112));
}
@Test
public void testPositionNullIsLastChild() {
final long id = 112;
ResponseEntity<FunctionalityDTO> response = move(id, null, null);
assertMoved(response, id, null, 1500 + Double.MAX_VALUE / 2);
assertChildren(Long.valueOf(11), longs(111, 113));
assertChildren(null, longs(1, 2, 3, 112));
}
@Test
public void testMoveFolderWithItsChildren() {
final long id = 1;
ResponseEntity<FunctionalityDTO> response = move(id, Long.valueOf(31), FunctionalityPosition.BELOW);
assertMoved(response, id, Long.valueOf(3), 500 + Double.MAX_VALUE / 2);
assertChildren(null, longs(2, 3));
assertChildren(Long.valueOf(3), longs(31, 1));
assertChildren(Long.valueOf(1), longs(11, 12));
assertChildren(Long.valueOf(11), longs(111, 112, 113));
}
@Test
public void testMoveAboveWithNullReference() {
ResponseEntity<FunctionalityDTO> response = move(1, null, FunctionalityPosition.ABOVE);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(header(response, HeaderUtil.ERROR)).isEqualTo("error.no_reference");
assertThat(header(response, HeaderUtil.PARAMS)).isEqualTo("functionality");
assertThat(header(response, HeaderUtil.MESSAGE)).isEqualTo("Attempting to insert above or below no functionality nor folder.");
}
@Test
public void testMoveBelowWithNullReference() {
ResponseEntity<FunctionalityDTO> response = move(1, null, FunctionalityPosition.BELOW);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(header(response, HeaderUtil.ERROR)).isEqualTo("error.no_reference");
assertThat(header(response, HeaderUtil.PARAMS)).isEqualTo("functionality");
assertThat(header(response, HeaderUtil.MESSAGE)).isEqualTo("Attempting to insert above or below no functionality nor folder.");
}
private ResponseEntity<FunctionalityDTO> move(long sourceId, Long referenceId, FunctionalityPosition relativePosition) {
return cut.move(PROJECT_CODE, new MoveFunctionalityDTO(sourceId, referenceId, relativePosition));
}
private void assertMoved(ResponseEntity<FunctionalityDTO> response, long id, Long parentId, double newOrder) {
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().getId()).isEqualTo(id);
assertThat(response.getBody().getParentId()).isEqualTo(parentId);
assertThat(response.getBody().getOrder()).isEqualTo(newOrder);
assertThat(response.getBody().getName()).isNotEmpty();
}
private void assertChildren(Long parentId, Long[] expectedSiblings) {
List<Functionality> siblings = functionalityRepository.findAllByProjectIdAndParentIdOrderByOrder(1, parentId);
assertThat(siblings.stream().map(Functionality::getId)).containsExactly(expectedSiblings);
}
}
|
92425bd68b4b357982ac148586af016ac4cb59f5
| 135 |
java
|
Java
|
18.springboot-redisson/src/main/java/com/demo/redisson/controller/TestController.java
|
NekoChips/SpringDemo
|
47bab4bf8622a98adab65abacc926a002c806029
|
[
"MIT"
] | 13 |
2020-03-25T14:40:47.000Z
|
2022-03-01T06:35:24.000Z
|
18.springboot-redisson/src/main/java/com/demo/redisson/controller/TestController.java
|
jjj2501/SpringDemo
|
47bab4bf8622a98adab65abacc926a002c806029
|
[
"MIT"
] | 1 |
2020-05-28T23:39:52.000Z
|
2020-05-28T23:39:52.000Z
|
18.springboot-redisson/src/main/java/com/demo/redisson/controller/TestController.java
|
jjj2501/SpringDemo
|
47bab4bf8622a98adab65abacc926a002c806029
|
[
"MIT"
] | 10 |
2020-04-12T18:13:31.000Z
|
2022-03-09T07:07:42.000Z
| 13.5 | 37 | 0.696296 | 1,002,235 |
package com.demo.redisson.controller;
/**
* @author NekoChips
* @description
* @date 2020/3/27
*/
public class TestController {
}
|
92425c7a52759ad6d7720bd910c0b5e437999a9d
| 1,899 |
java
|
Java
|
src/test/java/com/bst/CurrencyYahooTest.java
|
fierascu/etl_v1
|
81d0de3aa2538455ec9ae636c9ebb30b0a5e4d7d
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/bst/CurrencyYahooTest.java
|
fierascu/etl_v1
|
81d0de3aa2538455ec9ae636c9ebb30b0a5e4d7d
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/bst/CurrencyYahooTest.java
|
fierascu/etl_v1
|
81d0de3aa2538455ec9ae636c9ebb30b0a5e4d7d
|
[
"Apache-2.0"
] | null | null | null | 27.521739 | 97 | 0.630332 | 1,002,236 |
package com.bst;
import com.bst.utils.Utils;
import com.bst.utils.currency.CurrencyYahoo;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.log4j.Logger;
import static com.bst.utils.currency.CurrencyYahoo.urlBegin;
public class CurrencyYahooTest extends TestCase {
public static final String USED_YQL_XML = "Used/yql.xml";
static Logger log = Logger.getLogger(CurrencyYahooTest.class.getName());
/**
* Create the test case
*
* @param testName name of the test case
*/
public CurrencyYahooTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(CurrencyYahooTest.class);
}
/**
* Rigourous Test :-)
*/
public void testCurrencyYahooGet() {
CurrencyYahoo cy = new CurrencyYahoo();
assertTrue(cy.getEur() == 4.5499);
}
public void testReadXml() {
try {
String xmlTestFile = Utils.getFileWithUtil(USED_YQL_XML);
log.trace(xmlTestFile);
assertTrue(xmlTestFile.startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
} catch (Exception e) {
System.out.println(e);
}
}
public void testParseXml() {
try {
String withXPath = Utils.class.getClassLoader().getResource(USED_YQL_XML).toString();
CurrencyYahoo cy = new CurrencyYahoo(withXPath);
Boolean xmlTestParseFile = cy.setWithXPath(withXPath);
log.trace(xmlTestParseFile);
assertTrue(xmlTestParseFile);
} catch (Exception e) {
System.out.println(e);
}
}
public void testSetWithXPath() {
CurrencyYahoo cy = new CurrencyYahoo();
assertTrue(cy.setWithXPath(urlBegin));
}
}
|
92425cdb6ee687ff34e8973456f037fb30e5cb73
| 460 |
java
|
Java
|
app/src/main/java/ashwani/in/volleyeventbus/utils/Json.java
|
ashwanikumar04/volleyeventbus
|
4b74f6a2b88a557e587086f40e73e304dfde4dbd
|
[
"Apache-2.0"
] | 4 |
2016-05-29T13:43:21.000Z
|
2017-12-01T04:11:56.000Z
|
app/src/main/java/ashwani/in/volleyeventbus/utils/Json.java
|
ashwanikumar04/volleyeventbus
|
4b74f6a2b88a557e587086f40e73e304dfde4dbd
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/ashwani/in/volleyeventbus/utils/Json.java
|
ashwanikumar04/volleyeventbus
|
4b74f6a2b88a557e587086f40e73e304dfde4dbd
|
[
"Apache-2.0"
] | null | null | null | 24.210526 | 103 | 0.678261 | 1,002,237 |
package ashwani.in.volleyeventbus.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Json {
public static <T> String serialize(T obj) {
Gson gson = new Gson();
return gson.toJson(obj);
}
public static <T> T deSerialize(String jsonString, Class<T> tClass) throws ClassNotFoundException {
Gson gson = new GsonBuilder().create();
return gson.fromJson(jsonString, tClass);
}
}
|
92425cecd2fe6e92de4026b0626fd37059a3c35b
| 1,067 |
java
|
Java
|
system-tests/fixtures/api-impl-native/ern-movie-api-impl/android/lib/src/main/java/com/walmartlabs/electrode/reactnative/bridge/ConstantsProvider.java
|
friederbluemle/electrode-native
|
0e1c3c3d1d9a6c9489150dd280861bf49a08b2f4
|
[
"Apache-2.0"
] | 688 |
2017-09-26T19:41:46.000Z
|
2022-03-31T14:45:40.000Z
|
system-tests/fixtures/api-impl-native/ern-movie-api-impl/android/lib/src/main/java/com/walmartlabs/electrode/reactnative/bridge/ConstantsProvider.java
|
friederbluemle/electrode-native
|
0e1c3c3d1d9a6c9489150dd280861bf49a08b2f4
|
[
"Apache-2.0"
] | 727 |
2017-09-26T17:01:45.000Z
|
2022-03-28T07:24:29.000Z
|
system-tests/fixtures/api-impl-native/ern-movie-api-impl/android/lib/src/main/java/com/walmartlabs/electrode/reactnative/bridge/ConstantsProvider.java
|
friederbluemle/electrode-native
|
0e1c3c3d1d9a6c9489150dd280861bf49a08b2f4
|
[
"Apache-2.0"
] | 129 |
2017-09-25T18:47:36.000Z
|
2022-03-08T20:11:42.000Z
| 31.382353 | 147 | 0.729147 | 1,002,238 |
/*
* Copyright 2017 WalmartLabs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.walmartlabs.electrode.reactnative.bridge;
import android.support.annotation.Nullable;
import java.util.Map;
public interface ConstantsProvider {
/**
* Returns the constant values exposed to JavaScript.
* <p>
* Its implementation is not required but is very useful to key pre-defined values that need to be communicated from JavaScript to Java in sync
*
* @return Map
*/
@Nullable
Map<String, Object> getConstants();
}
|
92425cfd1bf62f5fe63dc6670ed9045df7b0ba2d
| 766 |
java
|
Java
|
src/main/java/com/kwpugh/gobber2/items/tools/endtools/PickaxeEnd.java
|
ttcchhmm/gobber-fabric-origins-patch
|
ee40f199c8e61e20647759b28e9230cae34b6d16
|
[
"CC0-1.0"
] | 1 |
2021-12-14T16:41:42.000Z
|
2021-12-14T16:41:42.000Z
|
src/main/java/com/kwpugh/gobber2/items/tools/endtools/PickaxeEnd.java
|
ttcchhmm/gobber-fabric-origins-patch
|
ee40f199c8e61e20647759b28e9230cae34b6d16
|
[
"CC0-1.0"
] | null | null | null |
src/main/java/com/kwpugh/gobber2/items/tools/endtools/PickaxeEnd.java
|
ttcchhmm/gobber-fabric-origins-patch
|
ee40f199c8e61e20647759b28e9230cae34b6d16
|
[
"CC0-1.0"
] | 1 |
2021-06-30T01:13:26.000Z
|
2021-06-30T01:13:26.000Z
| 27.357143 | 97 | 0.793734 | 1,002,239 |
package com.kwpugh.gobber2.items.tools.endtools;
import com.kwpugh.gobber2.Gobber2;
import com.kwpugh.gobber2.items.tools.basetools.ModPickaxe;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolMaterial;
import net.minecraft.world.World;
public class PickaxeEnd extends ModPickaxe
{
public PickaxeEnd(ToolMaterial material, int attackDamage, float attackSpeed, Settings settings)
{
super(material, attackDamage, attackSpeed, settings);
}
static boolean unbreakable = Gobber2.CONFIG.GENERAL.unbreakableEndTools;
@Override
public void onCraft(ItemStack stack, World world, PlayerEntity player)
{
if(unbreakable)
{
stack.getOrCreateTag().putBoolean("Unbreakable", true);
}
}
}
|
92425d973aec3437a729fb09f1202d2b012fd918
| 2,396 |
java
|
Java
|
core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/callbacks/LoadingCallbackFacetViaMethod.java
|
kshithijiyer/isis
|
b99a6a9057fdcd4af25b0a2f36f7b32efa6f137c
|
[
"ECL-2.0",
"Apache-2.0"
] | 1 |
2019-03-17T03:19:33.000Z
|
2019-03-17T03:19:33.000Z
|
core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/callbacks/LoadingCallbackFacetViaMethod.java
|
DalavanCloud/isis
|
2af2ef3e2edcb807d742f089839e0571d8132bd9
|
[
"Apache-2.0"
] | null | null | null |
core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/callbacks/LoadingCallbackFacetViaMethod.java
|
DalavanCloud/isis
|
2af2ef3e2edcb807d742f089839e0571d8132bd9
|
[
"Apache-2.0"
] | 1 |
2018-11-23T11:05:36.000Z
|
2018-11-23T11:05:36.000Z
| 31.526316 | 108 | 0.729132 | 1,002,240 |
/*
* 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.isis.core.metamodel.facets.object.callbacks;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.ImperativeFacet;
/**
* @deprecated - THIS CAN NEVER BE CALLED (BY JDO OBJECTSTORE AT LEAST)
*/
@Deprecated
public class LoadingCallbackFacetViaMethod extends LoadingCallbackFacetAbstract implements ImperativeFacet {
private final List<Method> methods = new ArrayList<Method>();
public LoadingCallbackFacetViaMethod(final Method method, final FacetHolder holder) {
super(holder);
addMethod(method);
}
@Override
public void addMethod(final Method method) {
methods.add(method);
}
@Override
public List<Method> getMethods() {
return Collections.unmodifiableList(methods);
}
@Override
public Intent getIntent(final Method method) {
return Intent.LIFECYCLE;
}
@Override
public void invoke(final ObjectAdapter adapter) {
ObjectAdapter.InvokeUtils.invokeAll(methods, adapter);
}
@Override
protected String toStringValues() {
return "methods=" + methods;
}
@Override public void appendAttributesTo(final Map<String, Object> attributeMap) {
super.appendAttributesTo(attributeMap);
ImperativeFacet.Util.appendAttributesTo(this, attributeMap);
}
}
|
92425dbd1fdfd64fe4e1d5581be13b4c9bcc29d1
| 400 |
java
|
Java
|
ForthForLoopLab/EvenPowersof2.java
|
LjuArn/ProgrammingBasics_Java_2020
|
9db7dfa2ba5caae5c673fa27a3d30097dc0a9882
|
[
"MIT"
] | null | null | null |
ForthForLoopLab/EvenPowersof2.java
|
LjuArn/ProgrammingBasics_Java_2020
|
9db7dfa2ba5caae5c673fa27a3d30097dc0a9882
|
[
"MIT"
] | null | null | null |
ForthForLoopLab/EvenPowersof2.java
|
LjuArn/ProgrammingBasics_Java_2020
|
9db7dfa2ba5caae5c673fa27a3d30097dc0a9882
|
[
"MIT"
] | null | null | null | 20 | 54 | 0.5175 | 1,002,241 |
package forCicle;
import java.util.Scanner;
public class EvenPowersof2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
for (int i = 0; i <= n; i+=2) {
double sum = Math.pow(2,i);
System.out.printf("%.0f%n", sum);
}
}
}
|
92425e774b702e5ad5ba4ec683f8592bbf5cd2bd
| 5,282 |
java
|
Java
|
pinot-server/src/main/java/org/apache/pinot/server/starter/helix/AdminApiApplication.java
|
briggsw/incubator-pinot
|
f7af79888c2bfc65275324b19edd700c1d8d1ff8
|
[
"Apache-2.0"
] | 2 |
2019-10-21T18:33:43.000Z
|
2019-12-21T19:57:16.000Z
|
pinot-server/src/main/java/org/apache/pinot/server/starter/helix/AdminApiApplication.java
|
IronOnet/incubator-pinot
|
bb835df5f903d55c08ab263d81b1db4d61e44ff2
|
[
"Apache-2.0"
] | 12 |
2020-10-29T01:37:11.000Z
|
2021-12-14T22:00:18.000Z
|
pinot-server/src/main/java/org/apache/pinot/server/starter/helix/AdminApiApplication.java
|
IronOnet/incubator-pinot
|
bb835df5f903d55c08ab263d81b1db4d61e44ff2
|
[
"Apache-2.0"
] | 1 |
2021-01-18T12:38:18.000Z
|
2021-01-18T12:38:18.000Z
| 40.015152 | 114 | 0.758803 | 1,002,242 |
/**
* 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.pinot.server.starter.helix;
import io.swagger.jaxrs.config.BeanConfig;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.UnknownHostException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import org.apache.pinot.common.utils.CommonConstants;
import org.apache.pinot.server.api.access.AccessControlFactory;
import org.apache.pinot.server.starter.ServerInstance;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdminApiApplication extends ResourceConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AdminApiApplication.class);
private final ServerInstance serverInstance;
private final AccessControlFactory accessControlFactory;
private URI baseUri;
private boolean started = false;
private HttpServer httpServer;
public static final String RESOURCE_PACKAGE = "org.apache.pinot.server.api.resources";
public AdminApiApplication(ServerInstance instance, AccessControlFactory accessControlFactory) {
this.serverInstance = instance;
this.accessControlFactory = accessControlFactory;
packages(RESOURCE_PACKAGE);
register(new AbstractBinder() {
@Override
protected void configure() {
bind(serverInstance).to(ServerInstance.class);
bind(accessControlFactory).to(AccessControlFactory.class);
}
});
register(JacksonFeature.class);
registerClasses(io.swagger.jaxrs.listing.ApiListingResource.class);
registerClasses(io.swagger.jaxrs.listing.SwaggerSerializers.class);
register(new ContainerResponseFilter() {
@Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext)
throws IOException {
containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
}
});
}
public boolean start(int httpPort) {
if (httpPort <= 0) {
LOGGER.warn("Invalid admin API port: {}. Not starting admin service", httpPort);
return false;
}
baseUri = URI.create("http://0.0.0.0:" + Integer.toString(httpPort) + "/");
httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, this);
setupSwagger(httpServer);
started = true;
return true;
}
public URI getBaseUri() {
return baseUri;
}
private void setupSwagger(HttpServer httpServer) {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("Pinot Server API");
beanConfig.setDescription("APIs for accessing Pinot server information");
beanConfig.setContact("https://github.com/apache/incubator-pinot");
beanConfig.setVersion("1.0");
beanConfig.setSchemes(new String[]{CommonConstants.HTTP_PROTOCOL, CommonConstants.HTTPS_PROTOCOL});
beanConfig.setBasePath(baseUri.getPath());
beanConfig.setResourcePackage(RESOURCE_PACKAGE);
beanConfig.setScan(true);
try {
beanConfig.setHost(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
throw new RuntimeException("Cannot get localhost name");
}
CLStaticHttpHandler staticHttpHandler =
new CLStaticHttpHandler(AdminApiApplication.class.getClassLoader(), "/api/");
// map both /api and /help to swagger docs. /api because it looks nice. /help for backward compatibility
httpServer.getServerConfiguration().addHttpHandler(staticHttpHandler, "/api/");
httpServer.getServerConfiguration().addHttpHandler(staticHttpHandler, "/help/");
URL swaggerDistLocation =
AdminApiApplication.class.getClassLoader().getResource("META-INF/resources/webjars/swagger-ui/3.18.2/");
CLStaticHttpHandler swaggerDist = new CLStaticHttpHandler(new URLClassLoader(new URL[]{swaggerDistLocation}));
httpServer.getServerConfiguration().addHttpHandler(swaggerDist, "/swaggerui-dist/");
}
public void stop() {
if (!started) {
return;
}
httpServer.shutdownNow();
}
}
|
92425f7a209797a3422a046f5d04a155f0359e91
| 871 |
java
|
Java
|
src/main/java/com/cities/restcities/CityMessageListener.java
|
ahmed-belhadj/java-cities
|
cecdca414e46659d10852018748681156c41b30e
|
[
"MIT"
] | null | null | null |
src/main/java/com/cities/restcities/CityMessageListener.java
|
ahmed-belhadj/java-cities
|
cecdca414e46659d10852018748681156c41b30e
|
[
"MIT"
] | 1 |
2019-02-18T23:43:12.000Z
|
2019-02-18T23:43:12.000Z
|
src/main/java/com/cities/restcities/CityMessageListener.java
|
ahmed-belhadj/java-cities
|
cecdca414e46659d10852018748681156c41b30e
|
[
"MIT"
] | null | null | null | 30.034483 | 71 | 0.741676 | 1,002,243 |
package com.cities.restcities;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class CityMessageListener
{
@RabbitListener(queues = RestCitiesApplication.QUEUE_NAME_SECRET)
public void receiveSecretMessage(CityMessage message)
{
log.info("Received Secret Message: {} ", message.toString());
}
@RabbitListener(queues = RestCitiesApplication.QUEUE_NAME_CITY_ONE)
public void receiveCityOneMessage(CityMessage message)
{
log.info("Received City 1 Message: {} ", message.toString());
}
@RabbitListener(queues = RestCitiesApplication.QUEUE_NAME_CITY_TWO)
public void receiveCityTwoMessage(CityMessage message)
{
log.info("Received City 2 Message: {} ", message.toString());
}
}
|
92425f7f880bc725e7c11012a8f6b170a4b0a8f7
| 7,303 |
java
|
Java
|
engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java
|
GavinRay97/teiid
|
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
|
[
"Apache-2.0"
] | 249 |
2015-01-04T12:32:56.000Z
|
2022-03-22T07:00:46.000Z
|
engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java
|
GavinRay97/teiid
|
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
|
[
"Apache-2.0"
] | 312 |
2015-01-06T19:01:51.000Z
|
2022-03-10T17:49:37.000Z
|
engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java
|
GavinRay97/teiid
|
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
|
[
"Apache-2.0"
] | 256 |
2015-01-06T18:14:39.000Z
|
2022-03-23T17:55:42.000Z
| 48.046053 | 166 | 0.656579 | 1,002,244 |
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* 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.teiid.query.parser;
import static org.teiid.query.parser.TestParser.*;
import java.util.Arrays;
import org.junit.Test;
import org.teiid.query.sql.lang.From;
import org.teiid.query.sql.lang.Limit;
import org.teiid.query.sql.lang.Query;
import org.teiid.query.sql.lang.Select;
import org.teiid.query.sql.lang.SetQuery;
import org.teiid.query.sql.lang.SetQuery.Operation;
import org.teiid.query.sql.lang.UnaryFromClause;
import org.teiid.query.sql.symbol.Constant;
import org.teiid.query.sql.symbol.GroupSymbol;
import org.teiid.query.sql.symbol.MultipleElementSymbol;
import org.teiid.query.sql.symbol.Reference;
public class TestLimitParsing {
@Test public void testLimit() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(null, new Constant(new Integer(100))));
helpTest("Select * from a limit 100", "SELECT * FROM a LIMIT 100", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testLimitWithOffset() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(new Constant(new Integer(50)), new Constant(new Integer(100))));
helpTest("Select * from a limit 50,100", "SELECT * FROM a LIMIT 50, 100", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testLimitWithReferences1() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(new Reference(0), new Constant(new Integer(100))));
helpTest("Select * from a limit ?,100", "SELECT * FROM a LIMIT ?, 100", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testLimitWithReferences2() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(new Constant(new Integer(50)), new Reference(0)));
helpTest("Select * from a limit 50,?", "SELECT * FROM a LIMIT 50, ?", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testLimitWithReferences3() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(new Reference(0), new Reference(1)));
helpTest("Select * from a limit ?,?", "SELECT * FROM a LIMIT ?, ?", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testSetQueryLimit() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
SetQuery setQuery = new SetQuery(Operation.UNION, true, query, query);
setQuery.setLimit(new Limit(new Reference(0), new Reference(1)));
helpTest("Select * from a union all Select * from a limit ?,?", "SELECT * FROM a UNION ALL SELECT * FROM a LIMIT ?, ?", setQuery); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testOffset() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(new Reference(0), null));
helpTest("Select * from a offset ? rows", "SELECT * FROM a OFFSET ? ROWS", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testFetchFirst() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(null, new Constant(2)));
helpTest("Select * from a fetch first 2 rows only", "SELECT * FROM a LIMIT 2", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testFetchFirstRow() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(null, new Constant(1)));
helpTest("Select * from a fetch first row only", "SELECT * FROM a LIMIT 1", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testOffsetFetch() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(new Constant(2), new Constant(5)));
helpTest("Select * from a offset 2 rows fetch first 5 rows only", "SELECT * FROM a LIMIT 2, 5", query); //$NON-NLS-1$ //$NON-NLS-2$
}
@Test public void testLimitWithOffsetKeyword() {
Query query = new Query();
Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
query.setSelect(select);
query.setFrom(from);
query.setLimit(new Limit(new Constant(new Integer(50)), new Constant(new Integer(100))));
helpTest("Select * from a limit 100 offset 50", "SELECT * FROM a LIMIT 50, 100", query); //$NON-NLS-1$ //$NON-NLS-2$
}
}
|
924260c0619b4694ff7d0e536efff1ad3f4dd109
| 66,559 |
java
|
Java
|
Corpus/ecf/1187.java
|
masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018
|
72aee638779aef7a56295c784a9bcbd902e41593
|
[
"MIT"
] | 15 |
2018-07-10T09:38:31.000Z
|
2021-11-29T08:28:07.000Z
|
Corpus/ecf/1187.java
|
JamesCao2048/BlizzardData
|
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
|
[
"MIT"
] | 3 |
2018-11-16T02:58:59.000Z
|
2021-01-20T16:03:51.000Z
|
Corpus/ecf/1187.java
|
JamesCao2048/BlizzardData
|
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
|
[
"MIT"
] | 6 |
2018-06-27T20:19:00.000Z
|
2022-02-19T02:29:53.000Z
| 41.11118 | 173 | 0.573401 | 1,002,245 |
/* Copyright (c) 2006-2009 Jan S. Rellermeyer
* Systems Group,
* Department of Computer Science, ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of ETH Zurich 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 OWNER 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.
*/
package ch.ethz.iks.r_osgi.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotSerializableException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.osgi.service.log.LogService;
import ch.ethz.iks.r_osgi.AsyncRemoteCallCallback;
import ch.ethz.iks.r_osgi.RemoteOSGiException;
import ch.ethz.iks.r_osgi.RemoteOSGiService;
import ch.ethz.iks.r_osgi.RemoteServiceEvent;
import ch.ethz.iks.r_osgi.RemoteServiceReference;
import ch.ethz.iks.r_osgi.URI;
import ch.ethz.iks.r_osgi.channels.ChannelEndpoint;
import ch.ethz.iks.r_osgi.channels.NetworkChannel;
import ch.ethz.iks.r_osgi.channels.NetworkChannelFactory;
import ch.ethz.iks.r_osgi.messages.DeliverBundlesMessage;
import ch.ethz.iks.r_osgi.messages.DeliverServiceMessage;
import ch.ethz.iks.r_osgi.messages.LeaseMessage;
import ch.ethz.iks.r_osgi.messages.LeaseUpdateMessage;
import ch.ethz.iks.r_osgi.messages.RemoteCallMessage;
import ch.ethz.iks.r_osgi.messages.RemoteCallResultMessage;
import ch.ethz.iks.r_osgi.messages.RemoteEventMessage;
import ch.ethz.iks.r_osgi.messages.RemoteOSGiMessage;
import ch.ethz.iks.r_osgi.messages.RequestBundleMessage;
import ch.ethz.iks.r_osgi.messages.RequestDependenciesMessage;
import ch.ethz.iks.r_osgi.messages.RequestServiceMessage;
import ch.ethz.iks.r_osgi.messages.StreamRequestMessage;
import ch.ethz.iks.r_osgi.messages.StreamResultMessage;
import ch.ethz.iks.r_osgi.messages.TimeOffsetMessage;
import ch.ethz.iks.r_osgi.streams.InputStreamHandle;
import ch.ethz.iks.r_osgi.streams.InputStreamProxy;
import ch.ethz.iks.r_osgi.streams.OutputStreamHandle;
import ch.ethz.iks.r_osgi.streams.OutputStreamProxy;
import ch.ethz.iks.util.CollectionUtils;
import ch.ethz.iks.util.StringUtils;
/**
* <p>
* The endpoint of a network channel encapsulates most of the communication
* logic like sending of messages, service method invocation, timestamp
* synchronization, and event delivery.
* </p>
* <p>
* Endpoints exchange symmetric leases when they are established. These leases
* contain the statements of supply and demand. The peer states the services it
* offers and the event topics it is interested in. Whenever one of these
* statements undergo a change, a lease update has to be sent. Leases expire
* with the closing of the network channel and the two endpoints.
* </p>
* <p>
* The network transport of channels is modular and exchangeable. Services can
* state the supported protocols in their service uri. R-OSGi maintains a list
* of network channel factories and the protocols they support. Each channel
* uses exactly one protocol.
* <p>
* <p>
* When the network channel breaks down, the channel endpoint tries to reconnect
* and to restore the connection. If this is not possible (for instance, because
* the other endpoint is not available any more, the endpoint is unregistered.
* </p>
*
* @author Jan S. Rellermeyer, ETH Zurich
*/
public final class ChannelEndpointImpl implements ChannelEndpoint {
int usageCounter = 1;
/**
* the channel.
*/
protected NetworkChannel networkChannel;
/**
* the services provided by the OSGi framework holding the remote channel
* endpoint. Map of service URI -> RemoteServiceReferences
*/
private Map remoteServices = new HashMap(0);
/**
* the topics of interest of the OSGi framework holding the remote channel
* endpoint. List of topic strings
*/
private List remoteTopics = new ArrayList(0);
/**
* the time offset between this peer's local time and the local time of the
* remote channel endpoint.
*/
private TimeOffset timeOffset;
/**
* Timeout.
*/
private static final int TIMEOUT = new Integer(System.getProperty("ch.ethz.iks.r_osgi.channelEndpointImpl.timeout", "120000")).intValue();
/**
* the callback register
*/
protected final Map callbacks = new HashMap(0);
/**
* map of service uri -> RemoteServiceRegistration.
*/
private final HashMap localServices = new HashMap(2);
/**
* map of service uri -> service registration.
*/
private final HashMap proxiedServices = new HashMap(0);
/**
* map of service uri -> proxy bundle. If the endpoint is closed, the
* proxies are unregistered.
*/
protected final HashMap proxyBundles = new HashMap(0);
/**
* map of stream id -> stream instance.
*/
private final HashMap streams = new HashMap(0);
/**
* next stream id.
*/
private short nextStreamID = 0;
/**
* the handler registration, if the remote topic space is not empty.
*/
private ServiceRegistration handlerReg = null;
/**
* filter for events to prevent loops in the remote delivery if the peers
* connected by this channel have non-disjoint topic spaces.
*/
private static final String NO_LOOPS = //$NON-NLS-1$
"(&(!(" + RemoteEventMessage.EVENT_SENDER_URI + //$NON-NLS-1$
"=*))" + // https://bugs.eclipse.org/418740
"(!(" + EventConstants.EVENT_TOPIC + "=org/osgi/service/remoteserviceadmin/*))" + //$NON-NLS-1$
")";
private ArrayList workQueue = new ArrayList();
/**
* used by the multiplexer and serves as a marker whether or not the channel
* may dispose itself when the connection went down.
*/
boolean hasRedundantLinks = false;
boolean traceChannelEndpoint = new Boolean(System.getProperty("ch.ethz.iks.r_osgi.impl.traceChannelEndpoint", "false")).booleanValue();
void trace(String message) {
trace(message, null);
}
void trace(String message, Throwable t) {
if (!traceChannelEndpoint)
return;
if (message != null)
System.out.println("ChannelEndpoint;" + message);
if (t != null)
t.printStackTrace();
}
/**
* create a new channel endpoint.
*
* @param factory
* the transport channel factory.
* @param endpointAddress
* the address of the remote endpoint.
* @throws RemoteOSGiException
* if something goes wrong in R-OSGi.
* @throws IOException
* if something goes wrong on the network layer.
*/
ChannelEndpointImpl(final NetworkChannelFactory factory, final URI endpointAddress) throws RemoteOSGiException, IOException {
trace("<init>(factory=" + factory + ",endpointAddress=" + endpointAddress + ")");
networkChannel = factory.getConnection(this, endpointAddress);
if (RemoteOSGiServiceImpl.DEBUG) {
RemoteOSGiServiceImpl.log.log(LogService.LOG_DEBUG, "opening new channel " + getRemoteAddress());
}
initThreadPool();
RemoteOSGiServiceImpl.registerChannelEndpoint(this);
}
/**
* create a new channel endpoint from an incoming connection.
*
* @param channel
* the network channel of the incoming connection.
*/
ChannelEndpointImpl(final NetworkChannel channel) {
trace("<init>(channel=" + channel + ";remoteAddress=" + channel.getRemoteAddress() + ";localAddress=" + channel.getLocalAddress() + ")");
networkChannel = channel;
channel.bind(this);
initThreadPool();
RemoteOSGiServiceImpl.registerChannelEndpoint(this);
}
/**
* initialize the thread pool
*/
private void initThreadPool() {
// TODO: tradeoff, could as well be central for all endpoints...
final ThreadGroup threadPool = new ThreadGroup("WorkerThreads" + toString());
// Set this thread pool to be daemon threads
threadPool.setDaemon(true);
for (int i = 0; i < RemoteOSGiServiceImpl.MAX_THREADS_PER_ENDPOINT; i++) {
final Thread t = new Thread(threadPool, "r-OSGi ChannelWorkerThread" + i) {
public void run() {
try {
while (!isInterrupted()) {
final Runnable r;
synchronized (workQueue) {
while (workQueue.isEmpty()) {
workQueue.wait();
}
r = (Runnable) workQueue.remove(0);
}
r.run();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
};
t.start();
}
}
/**
* process a recieved message. Called by the channel.
*
* @param msg
* the received message.
* @see ch.ethz.iks.r_osgi.channels.ChannelEndpoint#receivedMessage(ch.ethz.iks.r_osgi.messages.RemoteOSGiMessage)
* @category ChannelEndpoint
*/
public void receivedMessage(final RemoteOSGiMessage msg) {
if (msg == null) {
dispose();
return;
}
final Integer xid = new Integer(msg.getXID());
final WaitingCallback callback;
synchronized (callbacks) {
callback = (WaitingCallback) callbacks.remove(xid);
}
if (callback != null) {
callback.result(msg);
return;
} else {
final Runnable r = new Runnable() {
public void run() {
final RemoteOSGiMessage reply = handleMessage(msg);
if (reply != null) {
try {
trace("reply(msg=" + reply + ";remoteAddress=" + networkChannel.getRemoteAddress() + ")");
networkChannel.sendMessage(reply);
} catch (final NotSerializableException nse) {
throw new RemoteOSGiException("Error sending " + reply, nse);
} catch (NullPointerException npe) {
} catch (final IOException e) {
dispose();
}
}
}
};
synchronized (workQueue) {
workQueue.add(r);
workQueue.notify();
}
}
}
/**
* invoke a method on the remote host. This function is used by all proxy
* bundles.
*
* @param service
* the service uri.
* @param methodSignature
* the method signature.
* @param args
* the method parameter.
* @throws Throwable
* can throw any exception that the original method can throw,
* plus RemoteOSGiException.
* @return the result of the remote method invocation.
* @see ch.ethz.iks.r_osgi.channels.ChannelEndpoint#invokeMethod(java.lang.String,
* java.lang.String, java.lang.Object[])
* @category ChannelEndpoint
*/
public Object invokeMethod(final String service, final String methodSignature, final Object[] args) throws Throwable {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed");
}
// check arguments for streams and replace with placeholder
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof InputStream) {
args[i] = getInputStreamPlaceholder((InputStream) args[i]);
} else if (args[i] instanceof OutputStream) {
args[i] = getOutputStreamPlaceholder((OutputStream) args[i]);
}
}
final RemoteCallMessage invokeMsg = new RemoteCallMessage();
invokeMsg.setServiceID(URI.create(service).getFragment());
invokeMsg.setMethodSignature(methodSignature);
invokeMsg.setArgs(args);
try {
// send the message and get a MethodResultMessage in return
final RemoteCallResultMessage resultMsg = (RemoteCallResultMessage) sendAndWait(invokeMsg);
if (resultMsg.causedException()) {
throw resultMsg.getException();
}
final Object result = resultMsg.getResult();
if (result instanceof InputStreamHandle) {
return getInputStreamProxy((InputStreamHandle) result);
} else if (result instanceof OutputStreamHandle) {
return getOutputStreamProxy((OutputStreamHandle) result);
} else {
return result;
}
} catch (final RemoteOSGiException e) {
throw new RemoteOSGiException("Method invocation of " + service + " " + methodSignature + " failed.", e);
}
}
void asyncRemoteCall(final String fragment, final String methodSignature, final Object[] args, final AsyncRemoteCallCallback callback) {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed");
}
// check arguments for streams and replace with placeholder
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof InputStream) {
args[i] = getInputStreamPlaceholder((InputStream) args[i]);
} else if (args[i] instanceof OutputStream) {
args[i] = getOutputStreamPlaceholder((OutputStream) args[i]);
}
}
final Integer xid = new Integer(RemoteOSGiServiceImpl.nextXid());
synchronized (callbacks) {
callbacks.put(xid, new AsyncCallback() {
public void result(final RemoteOSGiMessage msg) {
final RemoteCallResultMessage resultMsg = (RemoteCallResultMessage) msg;
if (resultMsg.causedException()) {
callback.remoteCallResult(false, resultMsg.getException());
}
final Object result = resultMsg.getResult();
final Object res;
if (result instanceof InputStreamHandle) {
res = getInputStreamProxy((InputStreamHandle) result);
} else if (result instanceof OutputStreamHandle) {
res = getOutputStreamProxy((OutputStreamHandle) result);
} else {
res = result;
}
callback.remoteCallResult(true, res);
}
});
}
final RemoteCallMessage invokeMsg = new RemoteCallMessage();
invokeMsg.setServiceID(fragment);
invokeMsg.setMethodSignature(methodSignature);
invokeMsg.setArgs(args);
invokeMsg.setXID(xid.shortValue());
try {
send(invokeMsg);
} catch (final RemoteOSGiException e) {
callbacks.remove(xid);
callback.remoteCallResult(false, new RemoteOSGiException("Method invocation of " + getRemoteAddress() + "#" + fragment + " " + methodSignature + " failed.", e));
}
}
/**
* get the attributes of a service. This function is used to simplify proxy
* bundle generation.
*
* @param serviceID
* the serviceID of the remote service.
* @return the service attributes.
* @category ChannelEndpoint
*/
public Dictionary getProperties(final String serviceID) {
return getRemoteReference(serviceID).getProperties();
}
/**
* get the attributes for the presentation of the service. This function is
* used by proxies that support ServiceUI presentations.
*
* @param serviceID
* the serviceID of the remote service.
* @return the presentation attributes.
* @category ChannelEndpoint
*/
public Dictionary getPresentationProperties(final String serviceID) {
final Dictionary attribs = new Hashtable();
attribs.put(RemoteOSGiService.SERVICE_URI, serviceID);
attribs.put(RemoteOSGiService.PRESENTATION, getRemoteReference(serviceID).getProperty(RemoteOSGiService.PRESENTATION));
return attribs;
}
/**
* track the registration of a proxy service.
*
* @param serviceID
* the service ID.
* @param reg
* the service registration.
* @category ChannelEndpoint
*/
public void trackRegistration(final String serviceID, final ServiceRegistration reg) {
proxiedServices.put(serviceID, reg);
}
/**
* untrack the registration of a proxy service.
*
* @param serviceID
* the service ID.
* @category ChannelEndpoint
*/
public void untrackRegistration(final String serviceID) {
proxiedServices.remove(serviceID);
}
/**
* get the temporal offset of a remote peer.
*
* @return the TimeOffset.
* @throws RemoteOSGiException
* in case of network errors.
*/
public TimeOffset getOffset() throws RemoteOSGiException {
if (timeOffset == null) {
// if unknown, perform a initial offset measurement round of 4
// messages
TimeOffsetMessage timeMsg = new TimeOffsetMessage();
for (int i = 0; i < 4; i++) {
timeMsg.timestamp();
timeMsg = (TimeOffsetMessage) sendAndWait(timeMsg);
}
timeOffset = new TimeOffset(timeMsg.getTimeSeries());
} else if (timeOffset.isExpired()) {
// if offset has expired, start a new measurement round
TimeOffsetMessage timeMsg = new TimeOffsetMessage();
for (int i = 0; i < timeOffset.seriesLength(); i += 2) {
timeMsg.timestamp();
timeMsg = (TimeOffsetMessage) sendAndWait(timeMsg);
}
timeOffset.update(timeMsg.getTimeSeries());
}
return timeOffset;
}
/**
* dispose the channel.
*
* @category ChannelEndpoint
*/
public void dispose() {
if (networkChannel == null) {
return;
}
if (RemoteOSGiServiceImpl.DEBUG) {
RemoteOSGiServiceImpl.log.log(LogService.LOG_DEBUG, "DISPOSING ENDPOINT " + getRemoteAddress());
}
RemoteOSGiServiceImpl.unregisterChannelEndpoint(getRemoteAddress().toString());
if (handlerReg != null) {
handlerReg.unregister();
}
final NetworkChannel oldchannel = networkChannel;
networkChannel = null;
try {
oldchannel.close();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
if (!hasRedundantLinks) {
// inform all listeners about all services
final RemoteServiceReference[] refs = (RemoteServiceReference[]) remoteServices.values().toArray(new RemoteServiceReference[remoteServices.size()]);
for (int i = 0; i < refs.length; i++) {
RemoteOSGiServiceImpl.notifyRemoteServiceListeners(new RemoteServiceEvent(RemoteServiceEvent.UNREGISTERING, refs[i]));
}
// uninstall the proxy bundle
final Bundle[] proxies = (Bundle[]) proxyBundles.values().toArray(new Bundle[proxyBundles.size()]);
for (int i = 0; i < proxies.length; i++) {
try {
if (proxies[i].getState() != Bundle.UNINSTALLED) {
proxies[i].uninstall();
}
} catch (final Throwable t) {
}
}
}
remoteServices = null;
remoteTopics = null;
timeOffset = null;
callbacks.clear();
localServices.clear();
proxiedServices.clear();
closeStreams();
streams.clear();
handlerReg = null;
synchronized (callbacks) {
callbacks.notifyAll();
}
}
public boolean isConnected() {
return networkChannel != null;
}
public String toString() {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed");
}
//$NON-NLS-1$ //$NON-NLS-2$
return "ChannelEndpoint(" + networkChannel.toString() + ")";
}
/**
* read a byte from the input stream on the peer identified by id.
*
* @param streamID
* the ID of the stream.
* @return result of the read operation.
* @throws IOException
* when an IOException occurs.
*/
public int readStream(final short streamID) throws IOException {
final StreamRequestMessage requestMsg = new StreamRequestMessage();
requestMsg.setOp(StreamRequestMessage.READ);
requestMsg.setStreamID(streamID);
final StreamResultMessage resultMsg = doStreamOp(requestMsg);
return resultMsg.getResult();
}
/**
* read to an array from the input stream on the peer identified by id.
*
* @param streamID
* the ID of the stream.
* @param b
* the array to write the result to.
* @param off
* the offset for the destination array.
* @param len
* the number of bytes to read.
* @return number of bytes actually read.
* @throws IOException
* when an IOException occurs.
*/
public int readStream(final short streamID, final byte[] b, final int off, final int len) throws IOException {
// handle special cases as defined in InputStream
if (b == null) {
throw new NullPointerException();
}
if ((off < 0) || (len < 0) || (len + off > b.length)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return 0;
}
final StreamRequestMessage requestMsg = new StreamRequestMessage();
requestMsg.setOp(StreamRequestMessage.READ_ARRAY);
requestMsg.setStreamID(streamID);
requestMsg.setLenOrVal(len);
final StreamResultMessage resultMsg = doStreamOp(requestMsg);
final int length = resultMsg.getLen();
// check the length first, could be -1 indicating EOF
if (length > 0) {
final byte[] readdata = resultMsg.getData();
// copy result to byte array at correct offset
System.arraycopy(readdata, 0, b, off, length);
}
return length;
}
/**
* write a byte to the output stream on the peer identified by id.
*
* @param streamID
* the ID of the stream.
* @param b
* the value.
* @throws IOException
* when an IOException occurs.
*/
public void writeStream(final short streamID, final int b) throws IOException {
final StreamRequestMessage requestMsg = new StreamRequestMessage();
requestMsg.setOp(StreamRequestMessage.WRITE);
requestMsg.setStreamID(streamID);
requestMsg.setLenOrVal(b);
// wait for the stream operation to finish
doStreamOp(requestMsg);
}
/**
* write bytes from array to output stream on the peer identified by id.
*
* @param streamID
* the ID of the stream.
* @param b
* the source array.
* @param off
* offset into the source array.
* @param len
* number of bytes to copy.
* @throws IOException
* when an IOException occurs.
*/
public void writeStream(final short streamID, final byte[] b, final int off, final int len) throws IOException {
// handle special cases as defined in OutputStream
if (b == null) {
throw new NullPointerException();
}
if ((off < 0) || (len < 0) || (len + off > b.length)) {
throw new IndexOutOfBoundsException();
}
final byte[] data = new byte[len];
System.arraycopy(b, off, data, 0, len);
final StreamRequestMessage requestMsg = new StreamRequestMessage();
requestMsg.setOp(StreamRequestMessage.WRITE_ARRAY);
requestMsg.setStreamID(streamID);
requestMsg.setData(data);
requestMsg.setLenOrVal(len);
// wait for the stream operation to finish
doStreamOp(requestMsg);
}
/**
* get the channel URI.
*
* @return the channel ID.
* @category ChannelEndpoint
*/
public URI getRemoteAddress() {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed");
}
return networkChannel.getRemoteAddress();
}
/**
* get hte local address.
*
* @return
*/
URI getLocalAddress() {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed");
}
return networkChannel.getLocalAddress();
}
/**
* send a lease.
*
* @param myServices
* the services of this peer.
* @param myTopics
* the topics of this peer.
* @return the remote service references of the other peer.
*/
RemoteServiceReference[] sendLease(final RemoteServiceRegistration[] myServices, final String[] myTopics) {
final LeaseMessage l = new LeaseMessage();
populateLease(l, myServices, myTopics);
final LeaseMessage lease = (LeaseMessage) sendAndWait(l);
return processLease(lease);
}
/**
* send a lease update.
*
* @param msg
* a lease update message.
*/
void sendLeaseUpdate(final LeaseUpdateMessage msg) {
send(msg);
}
/**
* is the other side still reachable?
*
* @param uri
* the remote endpoint address.
* @return true if the other side is reachable.
*/
boolean isActive(final String uri) {
return remoteServices.get(uri) != null;
}
/**
* fetch the service from the remote peer.
*
* @param ref
* the remote service reference.
* @throws IOException
* in case of network errors.
*/
void getProxyBundle(final RemoteServiceReference ref) throws IOException, RemoteOSGiException {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed.");
}
// build the RequestServiceMessage
final RequestServiceMessage req = new RequestServiceMessage();
req.setServiceID(ref.getURI().getFragment());
// send the RequestServiceMessage and get a DeliverServiceMessage in
// return. The DeliverServiceMessage contains a minimal description of
// the resources
// of a proxy bundle. This is the service interface plus type injections
// plus import/export
// declarations for the bundle.
final DeliverServiceMessage deliv = (DeliverServiceMessage) sendAndWait(req);
// generate a proxy bundle for the service
final InputStream in = new ProxyGenerator().generateProxyBundle(ref.getURI(), deliv);
installResolveAndStartBundle(ref, in, true);
}
private void installResolveAndStartBundle(final RemoteServiceReference ref, final InputStream in, final boolean isProxy) {
try {
final Bundle bundle = RemoteOSGiActivator.getActivator().getContext().installBundle(ref.getURI().toString(), in);
retrieveDependencies((String) bundle.getHeaders().get(Constants.IMPORT_PACKAGE), (String) bundle.getHeaders().get(Constants.EXPORT_PACKAGE));
if (isProxy) {
// store the bundle for state updates and cleanup
proxyBundles.put(ref.getURI().getFragment(), bundle);
}
// start the bundle
bundle.start();
} catch (final BundleException e) {
final Throwable nested = e.getNestedException() == null ? e : e.getNestedException();
throw new RemoteOSGiException("Could not install the generated bundle " + ref.toString(), nested);
}
}
/**
* get a clone of a remote bundle
*
* @param ref
* the remote service reference to the service for which the
* bundle clone is requested.
*/
void getCloneBundle(final RemoteServiceReference ref) {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed.");
}
// build the RequestBundleMessage
final RequestBundleMessage req = new RequestBundleMessage();
req.setServiceID(ref.getURI().getFragment());
final DeliverBundlesMessage deliv = (DeliverBundlesMessage) sendAndWait(req);
final byte[] bundleBytes = deliv.getDependencies()[0];
installResolveAndStartBundle(ref, new ByteArrayInputStream(bundleBytes), false);
}
/**
* tokenize a package import/export string
*
* @param str
* the string
* @return the tokens
*/
private String[] getTokens(final String str) {
final ArrayList result = new ArrayList();
//final StringTokenizer tokenizer = new StringTokenizer(str, ",");
final String[] tokens = StringUtils.stringToArray(str, ",");
for (int i = 0; i < tokens.length; i++) {
final int pos;
// TODO: handle versions for R4!
final String pkg = (pos = tokens[i].indexOf(";")) > -1 ? tokens[i].substring(0, pos).trim() : tokens[i].trim();
if (!RemoteOSGiServiceImpl.checkPackageImport(pkg)) {
result.add(pkg);
}
}
return (String[]) result.toArray(new String[result.size()]);
}
/**
* get the missing dependencies from remote for a given bundle defined by
* its declared package import and exports.
*
* @param importString
* the declared package imports
* @param exportString
* the declared package exports
*/
private void retrieveDependencies(final String importString, final String exportString) {
final Set exports = new HashSet(Arrays.asList(getTokens(exportString)));
final Set imports = new HashSet(Arrays.asList(getTokens(importString)));
final String[] missing = (String[]) CollectionUtils.rightDifference(imports, exports).toArray(new String[0]);
if (missing.length > 0) {
final RequestDependenciesMessage req = new RequestDependenciesMessage();
req.setPackages(missing);
final DeliverBundlesMessage deps = (DeliverBundlesMessage) sendAndWait(req);
final byte[][] depBytes = deps.getDependencies();
for (int i = 0; i < depBytes.length; i++) {
try {
RemoteOSGiActivator.getActivator().getContext().installBundle("r-osgi://dep/" + missing[i], new ByteArrayInputStream(depBytes[i]));
} catch (BundleException be) {
be.printStackTrace();
}
}
}
}
/**
* get the remote reference for a given serviceID.
*
* @param serviceID
* the uri.
* @return the remote service reference, or <code>null</code>.
*/
RemoteServiceReferenceImpl getRemoteReference(final String uri) {
return (RemoteServiceReferenceImpl) remoteServices.get(uri);
}
/**
* Get the remote references.
*
* @param filter
* a filter, or <code>null</code>.
* @return all remote service references which match the filter.
*/
RemoteServiceReference[] getAllRemoteReferences(final Filter filter) {
final List result = new ArrayList();
final RemoteServiceReferenceImpl[] refs = (RemoteServiceReferenceImpl[]) remoteServices.values().toArray(new RemoteServiceReferenceImpl[remoteServices.size()]);
if (filter == null) {
return refs.length > 0 ? refs : null;
} else {
for (int i = 0; i < refs.length; i++) {
if (filter.match(refs[i].getProperties())) {
result.add(refs[i]);
}
}
final RemoteServiceReference[] refs2 = (RemoteServiceReference[]) result.toArray(new RemoteServiceReferenceImpl[result.size()]);
return refs2.length > 0 ? refs2 : null;
}
}
/**
* release the remote service. This leads to an uninstallation of the proxy
* bundle.
*
* @param uri
* the uri of the service.
*/
void ungetRemoteService(final URI uri) {
try {
Bundle bundle = (Bundle) proxyBundles.remove(uri.getFragment());
// see https://bugs.eclipse.org/420897
if (bundle != null) {
bundle.uninstall();
} else {
RemoteOSGiServiceImpl.log.log(LogService.LOG_WARNING, //$NON-NLS-1$
"failed to uninstall non-existant bundle " + //$NON-NLS-1$
uri.getFragment());
}
} catch (final BundleException be) {
}
}
private long startTime;
public static final String TRACE_TIME_PROP = System.getProperty("ch.ethz.iks.r_osgi.traceSendMessageTime");
private static boolean TRACE_TIME = false;
private static boolean USE_LOG_SERVICE = true;
static {
if (TRACE_TIME_PROP != null) {
if (TRACE_TIME_PROP.equalsIgnoreCase("logservice") || TRACE_TIME_PROP.equalsIgnoreCase("true")) {
TRACE_TIME = true;
} else if (TRACE_TIME_PROP.equalsIgnoreCase("systemout")) {
TRACE_TIME = true;
USE_LOG_SERVICE = false;
}
}
}
private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
void startTiming(String message) {
if (TRACE_TIME) {
startTime = System.currentTimeMillis();
StringBuffer buf = new StringBuffer("TIMING.START;");
buf.append(sdf.format(new Date(startTime))).append(";");
buf.append((message == null ? "" : message));
LogService logService = RemoteOSGiServiceImpl.log;
if (logService != null && USE_LOG_SERVICE)
logService.log(LogService.LOG_INFO, buf.toString());
else
System.out.println(buf.toString());
}
}
void stopTiming(String message, Throwable exception) {
if (TRACE_TIME) {
StringBuffer buf = new StringBuffer("TIMING.END;");
buf.append(sdf.format(new Date(startTime))).append(";");
buf.append((message == null ? "" : message));
buf.append(";duration(ms)=").append((System.currentTimeMillis() - startTime));
LogService logService = RemoteOSGiServiceImpl.log;
if (logService != null && USE_LOG_SERVICE) {
if (exception != null)
logService.log(LogService.LOG_ERROR, buf.toString(), exception);
else
logService.log(LogService.LOG_INFO, buf.toString());
} else {
System.out.println(buf.toString());
if (exception != null)
exception.printStackTrace();
}
startTime = 0;
}
}
/**
* send a message.
*
* @param msg
* a message.
*/
void send(final RemoteOSGiMessage msg) {
if (networkChannel == null) {
//$NON-NLS-1$
throw new RemoteOSGiException("Channel is closed");
}
if (msg.getXID() == 0) {
msg.setXID(RemoteOSGiServiceImpl.nextXid());
}
Throwable t = null;
String timingMsg = "sendMessage;funcId=" + msg.getFuncID() + ";xid=" + msg.getXID();
startTiming(timingMsg);
try {
try {
trace("send(msg=" + msg + ";remoteAddress=" + networkChannel.getRemoteAddress() + ")");
networkChannel.sendMessage(msg);
return;
} catch (final IOException ioe) {
if (msg instanceof TimeOffsetMessage) {
((TimeOffsetMessage) msg).restamp(RemoteOSGiServiceImpl.nextXid());
networkChannel.sendMessage(msg);
} else {
networkChannel.sendMessage(msg);
}
}
} catch (final NotSerializableException nse) {
t = new RemoteOSGiException("Error sending " + msg, nse);
throw ((RemoteOSGiException) t);
} catch (final IOException ioe) {
dispose();
t = new RemoteOSGiException("Network error", ioe);
throw ((RemoteOSGiException) t);
} finally {
stopTiming(timingMsg, t);
}
}
/**
* message handler method.
*
* @param msg
* the incoming message.
* @return if reply is created, null otherwise.
* @throws RemoteOSGiException
* if something goes wrong.
*/
RemoteOSGiMessage handleMessage(final RemoteOSGiMessage msg) throws RemoteOSGiException {
trace("handleMessage(msg=" + msg + ";remoteAddress=" + networkChannel.getRemoteAddress() + ")");
switch(msg.getFuncID()) {
// requests
case RemoteOSGiMessage.LEASE:
{
final LeaseMessage lease = (LeaseMessage) msg;
processLease(lease);
populateLease(lease, RemoteOSGiServiceImpl.getServices(networkChannel.getProtocol()), RemoteOSGiServiceImpl.getTopics());
return lease;
}
case RemoteOSGiMessage.REQUEST_SERVICE:
{
final RequestServiceMessage reqSrv = (RequestServiceMessage) msg;
final String serviceID = reqSrv.getServiceID();
final RemoteServiceRegistration reg = getServiceRegistration(serviceID);
final DeliverServiceMessage m = reg.getDeliverServiceMessage();
m.setXID(reqSrv.getXID());
m.setServiceID(reqSrv.getServiceID());
return m;
}
case RemoteOSGiMessage.LEASE_UPDATE:
{
final LeaseUpdateMessage suMsg = (LeaseUpdateMessage) msg;
final String serviceID = suMsg.getServiceID();
final short stateUpdate = suMsg.getType();
final String serviceURI = getRemoteAddress().resolve("#" + serviceID).toString();
switch(stateUpdate) {
case LeaseUpdateMessage.TOPIC_UPDATE:
{
// There is an older r-OSGi version that incorrectly sends an ArrayList
// (1.0.0.RC4_v20131016-1848)
Object topicsAdded = suMsg.getPayload()[0];
if (topicsAdded instanceof List) {
topicsAdded = ((List) topicsAdded).toArray(new String[0]);
}
Object topicsRemoved = suMsg.getPayload()[1];
if (topicsRemoved instanceof List) {
topicsRemoved = ((List) topicsRemoved).toArray(new String[0]);
}
updateTopics((String[]) topicsAdded, (String[]) topicsRemoved);
return null;
}
case LeaseUpdateMessage.SERVICE_ADDED:
{
final Dictionary properties = (Dictionary) suMsg.getPayload()[1];
sanitizeServiceProperties(properties, serviceURI);
final RemoteServiceReferenceImpl ref = new RemoteServiceReferenceImpl((String[]) suMsg.getPayload()[0], serviceID, properties, this);
remoteServices.put(serviceURI, ref);
RemoteOSGiServiceImpl.notifyRemoteServiceListeners(new RemoteServiceEvent(RemoteServiceEvent.REGISTERED, ref));
return null;
}
case LeaseUpdateMessage.SERVICE_MODIFIED:
{
final Dictionary properties = (Dictionary) suMsg.getPayload()[1];
sanitizeServiceProperties(properties, serviceURI);
final ServiceRegistration reg = (ServiceRegistration) proxiedServices.get(serviceID);
if (reg != null) {
reg.setProperties(properties);
}
final RemoteServiceReferenceImpl ref = getRemoteReference(//$NON-NLS-1$
serviceURI);
// (see https://bugs.eclipse.org/420433)
if (ref == null && reg == null) {
return null;
}
ref.setProperties(properties);
RemoteOSGiServiceImpl.notifyRemoteServiceListeners(new RemoteServiceEvent(RemoteServiceEvent.MODIFIED, ref));
return null;
}
case LeaseUpdateMessage.SERVICE_REMOVED:
{
if (networkChannel == null) {
return null;
}
final RemoteServiceReference ref = (RemoteServiceReference) remoteServices.remove(serviceURI);
if (ref != null) {
RemoteOSGiServiceImpl.notifyRemoteServiceListeners(new RemoteServiceEvent(RemoteServiceEvent.UNREGISTERING, ref));
}
final Bundle bundle = (Bundle) proxyBundles.remove(serviceID);
if (bundle != null) {
try {
bundle.uninstall();
} catch (final BundleException be) {
be.printStackTrace();
}
proxiedServices.remove(serviceID);
//$NON-NLS-1$
remoteServices.remove(//$NON-NLS-1$
serviceURI);
}
return null;
}
}
return null;
}
case RemoteOSGiMessage.REMOTE_CALL:
{
final RemoteCallMessage invMsg = (RemoteCallMessage) msg;
try {
RemoteServiceRegistration serv = (RemoteServiceRegistration) localServices.get(invMsg.getServiceID());
if (serv == null) {
final RemoteServiceRegistration reg = getServiceRegistration(invMsg.getServiceID());
if (reg == null) {
throw new IllegalStateException(toString() + //$NON-NLS-1$
"Could not get " + //$NON-NLS-1$
invMsg.getServiceID() + //$NON-NLS-1$
", known services " + //$NON-NLS-1$
localServices);
} else {
serv = reg;
}
}
// get the invocation arguments and the local method
final Object[] arguments = invMsg.getArgs();
for (int i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof InputStreamHandle) {
arguments[i] = getInputStreamProxy((InputStreamHandle) arguments[i]);
} else if (arguments[i] instanceof OutputStreamHandle) {
arguments[i] = getOutputStreamProxy((OutputStreamHandle) arguments[i]);
}
}
final Method method = serv.getMethod(invMsg.getMethodSignature());
// invoke method
try {
Object result = method.invoke(serv.getServiceObject(), arguments);
final RemoteCallResultMessage m = new RemoteCallResultMessage();
m.setXID(invMsg.getXID());
if (result instanceof InputStream) {
m.setResult(getInputStreamPlaceholder((InputStream) result));
} else if (result instanceof OutputStream) {
m.setResult(getOutputStreamPlaceholder((OutputStream) result));
} else {
m.setResult(result);
}
return m;
} catch (final InvocationTargetException t) {
t.printStackTrace();
throw t.getTargetException();
}
} catch (final Throwable t) {
t.printStackTrace();
final RemoteCallResultMessage m = new RemoteCallResultMessage();
m.setXID(invMsg.getXID());
m.setException(t);
return m;
}
}
case RemoteOSGiMessage.REMOTE_EVENT:
{
final RemoteEventMessage eventMsg = (RemoteEventMessage) msg;
final Dictionary properties = eventMsg.getProperties();
// transform the event timestamps
final Long remoteTs;
if ((remoteTs = (Long) properties.get(EventConstants.TIMESTAMP)) != null) {
properties.put(EventConstants.TIMESTAMP, getOffset().transform(remoteTs));
}
final Event event = new Event(eventMsg.getTopic(), properties);
// and deliver the event to the local framework
if (RemoteOSGiServiceImpl.eventAdminTracker.getTrackingCount() > 0) {
((EventAdmin) RemoteOSGiServiceImpl.eventAdminTracker.getService()).postEvent(event);
} else {
// TODO: to log
System.err.println(//$NON-NLS-1$
"Could not deliver received event: " + //$NON-NLS-1$
event + ". No EventAdmin available.");
}
return null;
}
case RemoteOSGiMessage.TIME_OFFSET:
{
// add timestamp to the message and return the message to sender
((TimeOffsetMessage) msg).timestamp();
return msg;
}
case RemoteOSGiMessage.STREAM_REQUEST:
{
final StreamRequestMessage reqMsg = (StreamRequestMessage) msg;
try {
// fetch stream object
final Object stream = streams.get(new Integer(reqMsg.getStreamID()));
if (stream == null) {
throw new IllegalStateException("Could not get stream with ID " + reqMsg.getStreamID());
}
// invoke operation on stream
switch(reqMsg.getOp()) {
case StreamRequestMessage.READ:
{
final int result = ((InputStream) stream).read();
final StreamResultMessage m = new StreamResultMessage();
m.setXID(reqMsg.getXID());
m.setResult((short) result);
return m;
}
case StreamRequestMessage.READ_ARRAY:
{
final byte[] b = new byte[reqMsg.getLenOrVal()];
final int len = ((InputStream) stream).read(b, 0, reqMsg.getLenOrVal());
final StreamResultMessage m = new StreamResultMessage();
m.setXID(reqMsg.getXID());
m.setResult(StreamResultMessage.RESULT_ARRAY);
m.setLen(len);
if (len > 0) {
m.setData(b);
}
return m;
}
case StreamRequestMessage.WRITE:
{
((OutputStream) stream).write(reqMsg.getLenOrVal());
final StreamResultMessage m = new StreamResultMessage();
m.setXID(reqMsg.getXID());
m.setResult(StreamResultMessage.RESULT_WRITE_OK);
return m;
}
case StreamRequestMessage.WRITE_ARRAY:
{
((OutputStream) stream).write(reqMsg.getData());
final StreamResultMessage m = new StreamResultMessage();
m.setXID(reqMsg.getXID());
m.setResult(StreamResultMessage.RESULT_WRITE_OK);
return m;
}
default:
throw new RemoteOSGiException("Unimplemented op code for stream request " + msg);
}
} catch (final IOException e) {
final StreamResultMessage m = new StreamResultMessage();
m.setXID(reqMsg.getXID());
m.setResult(StreamResultMessage.RESULT_EXCEPTION);
m.setException(e);
return m;
}
}
case RemoteOSGiMessage.REQUEST_BUNDLE:
final RequestBundleMessage reqB = (RequestBundleMessage) msg;
try {
final String serviceID = reqB.getServiceID();
final RemoteServiceRegistration reg = getServiceRegistration(serviceID);
final byte[] bytes = RemoteOSGiServiceImpl.getBundle(reg.getReference().getBundle());
final DeliverBundlesMessage delB = new DeliverBundlesMessage();
delB.setXID(reqB.getXID());
delB.setDependencies(new byte[][] { bytes });
return delB;
} catch (IOException ioe) {
ioe.printStackTrace();
return null;
}
case RemoteOSGiMessage.REQUEST_DEPENDENCIES:
final RequestDependenciesMessage reqDeps = (RequestDependenciesMessage) msg;
try {
final byte[][] bundleBytes = RemoteOSGiServiceImpl.getBundlesForPackages(reqDeps.getPackages());
final DeliverBundlesMessage delDeps = new DeliverBundlesMessage();
delDeps.setXID(reqDeps.getXID());
delDeps.setDependencies(bundleBytes);
return delDeps;
} catch (IOException ioe) {
ioe.printStackTrace();
return null;
}
default:
//$NON-NLS-1$
throw new RemoteOSGiException("Unimplemented message " + msg);
}
}
/**
* send a message and wait for the result.
*
* @param msg
* the message.
* @return the result message.
*/
private RemoteOSGiMessage sendAndWait(final RemoteOSGiMessage msg) {
if (msg.getXID() == 0) {
msg.setXID(RemoteOSGiServiceImpl.nextXid());
}
final Integer xid = new Integer(msg.getXID());
final WaitingCallback blocking = new WaitingCallback();
synchronized (callbacks) {
callbacks.put(xid, blocking);
}
send(msg);
// wait for the reply
synchronized (blocking) {
final long timeout = System.currentTimeMillis() + TIMEOUT;
RemoteOSGiMessage result = blocking.getResult();
try {
while (result == null && networkChannel != null && System.currentTimeMillis() < timeout) {
blocking.wait(TIMEOUT);
result = blocking.getResult();
}
} catch (InterruptedException ie) {
throw new RemoteOSGiException("Interrupted while waiting for callback", ie);
}
if (result != null) {
return result;
} else if (networkChannel == null) {
throw new //$NON-NLS-1$
RemoteOSGiException(//$NON-NLS-1$
"Channel is closed");
} else {
throw new RemoteOSGiException("Method Invocation failed, timeout exceeded.");
}
}
}
/**
* get the remote service registration for a given service ID.
*
* @param serviceID
* the serviceID.
* @return the remote service registration, or <code>null</code>.
*/
private RemoteServiceRegistration getServiceRegistration(final String serviceID) {
final RemoteServiceRegistration reg = RemoteOSGiServiceImpl.getServiceRegistration(serviceID);
localServices.put(serviceID, reg);
return reg;
}
/**
* populate a lease message with values.
*
* @param lease
* the lease message.
* @param regs
* the registrations.
* @param topics
* the topics.
*/
private void populateLease(final LeaseMessage lease, final RemoteServiceRegistration[] regs, final String[] topics) {
final String[] serviceIDs = new String[regs.length];
final String[][] serviceInterfaces = new String[regs.length][];
final Dictionary[] serviceProperties = new Dictionary[regs.length];
for (short i = 0; i < regs.length; i++) {
serviceIDs[i] = String.valueOf(regs[i].getServiceID());
serviceInterfaces[i] = regs[i].getInterfaceNames();
serviceProperties[i] = regs[i].getProperties();
}
lease.setServiceIDs(serviceIDs);
lease.setServiceInterfaces(serviceInterfaces);
lease.setServiceProperties(serviceProperties);
lease.setTopics(topics);
}
/**
* process a lease message.
*
* @param lease
* the lease message.
* @return the remote references.
*/
private RemoteServiceReference[] processLease(final LeaseMessage lease) {
final String[] serviceIDs = lease.getServiceIDs();
final String[][] serviceInterfaces = lease.getServiceInterfaces();
final Dictionary[] serviceProperties = lease.getServiceProperties();
final RemoteServiceReferenceImpl[] refs = new RemoteServiceReferenceImpl[serviceIDs.length];
for (short i = 0; i < serviceIDs.length; i++) {
final String serviceID = serviceIDs[i];
final String serviceURI = getRemoteAddress().resolve("#" + serviceID).toString();
final Dictionary properties = serviceProperties[i];
sanitizeServiceProperties(properties, serviceURI);
refs[i] = new RemoteServiceReferenceImpl(serviceInterfaces[i], serviceID, properties, this);
remoteServices.put(refs[i].getURI().toString(), refs[i]);
RemoteOSGiServiceImpl.notifyRemoteServiceListeners(new RemoteServiceEvent(RemoteServiceEvent.REGISTERED, refs[i]));
}
updateTopics(lease.getTopics(), new String[0]);
return refs;
}
private void sanitizeServiceProperties(final Dictionary properties, final String serviceURI) {
// adjust the properties
properties.put(RemoteOSGiService.SERVICE_URI, serviceURI);
// remove the service PID, if set
properties.remove(Constants.SERVICE_PID);
// remove the R-OSGi registration property
properties.remove(RemoteOSGiService.R_OSGi_REGISTRATION);
// also remote the ECF registration property
//$NON-NLS-1$
properties.remove("org.eclipse.ecf.serviceRegistrationRemote");
}
/**
* perform a stream operation.
*
* @param requestMsg
* the request message.
* @return the result message.
* @throws IOException
*/
private StreamResultMessage doStreamOp(final StreamRequestMessage requestMsg) throws IOException {
try {
// send the message and get a StreamResultMessage in return
final StreamResultMessage result = (StreamResultMessage) sendAndWait(requestMsg);
if (result.causedException()) {
throw result.getException();
}
return result;
} catch (final RemoteOSGiException e) {
throw new RemoteOSGiException("Invocation of operation " + requestMsg.getOp() + " on stream " + requestMsg.getStreamID() + " failed.", e);
}
}
/**
* update the topics
*
* @param topicsAdded
* the topics added.
* @param topicsRemoved
* the topics removed.
*/
private void updateTopics(final String[] topicsAdded, final String[] topicsRemoved) {
if (handlerReg == null) {
// Object)) with null as the topicsAdded list. Thus, ignore null.
if (topicsAdded != null && topicsAdded.length > 0) {
// register handler
final Dictionary properties = new Hashtable();
properties.put(EventConstants.EVENT_TOPIC, topicsAdded);
properties.put(EventConstants.EVENT_FILTER, NO_LOOPS);
properties.put(RemoteOSGiServiceImpl.R_OSGi_INTERNAL, Boolean.TRUE);
handlerReg = RemoteOSGiActivator.getActivator().getContext().registerService(EventHandler.class.getName(), new EventForwarder(), properties);
remoteTopics.addAll(Arrays.asList(topicsAdded));
}
} else {
if (topicsRemoved != null) {
remoteTopics.removeAll(Arrays.asList(topicsRemoved));
}
if (topicsAdded != null) {
remoteTopics.addAll(Arrays.asList(topicsAdded));
}
if (remoteTopics.size() == 0) {
// unregister handler
handlerReg.unregister();
handlerReg = null;
} else {
// update topics
final Dictionary properties = new Hashtable();
properties.put(EventConstants.EVENT_TOPIC, remoteTopics.toArray(new String[remoteTopics.size()]));
properties.put(EventConstants.EVENT_FILTER, NO_LOOPS);
properties.put(RemoteOSGiServiceImpl.R_OSGi_INTERNAL, Boolean.TRUE);
handlerReg.setProperties(properties);
}
}
if (RemoteOSGiServiceImpl.MSG_DEBUG) {
RemoteOSGiServiceImpl.log.log(LogService.LOG_DEBUG, //$NON-NLS-1$ //$NON-NLS-2$
"NEW REMOTE TOPIC SPACE for " + getRemoteAddress() + " is " + remoteTopics);
}
}
/**
* creates a placeholder for an InputStream that can be sent to the other
* party and will be converted to an InputStream proxy there.
*
* @param origIS
* the instance of InputStream that needs to be remoted
* @return the placeholder object that is sent to the actual client
*/
private InputStreamHandle getInputStreamPlaceholder(final InputStream origIS) {
final InputStreamHandle sp = new InputStreamHandle(nextStreamID());
streams.put(new Integer(sp.getStreamID()), origIS);
return sp;
}
/**
* creates a proxy for the input stream that corresponds to the placeholder.
*
* @param placeholder
* the placeholder for the remote input stream
* @return the proxy for the input stream
*/
private InputStream getInputStreamProxy(final InputStreamHandle placeholder) {
return new InputStreamProxy(placeholder.getStreamID(), this);
}
/**
* creates a placeholder for an OutputStream that can be sent to the other
* party and will be converted to an OutputStream proxy there.
*
* @param origOS
* the instance of OutputStream that needs to be remoted
* @return the placeholder object that is sent to the actual client
*/
private OutputStreamHandle getOutputStreamPlaceholder(final OutputStream origOS) {
final OutputStreamHandle sp = new OutputStreamHandle(nextStreamID());
streams.put(new Integer(sp.getStreamID()), origOS);
return sp;
}
/**
* creates a proxy for the output stream that corresponds to the
* placeholder.
*
* @param placeholder
* the placeholder for the remote output stream
* @return the proxy for the output stream
*/
private OutputStream getOutputStreamProxy(final OutputStreamHandle placeholder) {
return new OutputStreamProxy(placeholder.getStreamID(), this);
}
/**
* get the next stream wrapper id.
*
* @return the next stream wrapper id.
*/
private synchronized short nextStreamID() {
if (nextStreamID == -1) {
nextStreamID = 0;
}
return (++nextStreamID);
}
/**
* closes all streams that are still open.
*/
private void closeStreams() {
final Object[] s = streams.values().toArray();
try {
for (int i = 0; i < s.length; i++) {
if (s[i] instanceof InputStream) {
((InputStream) s[i]).close();
} else if (s[i] instanceof OutputStream) {
((OutputStream) s[i]).close();
} else {
RemoteOSGiServiceImpl.log.log(LogService.LOG_WARNING, "Object in input streams map was not an instance of a stream.");
}
}
} catch (final IOException e) {
}
}
/**
* forwards events over the channel to the remote peer.
*
* @author Jan S. Rellermeyer, ETH Zurich
* @category EventHandler
*/
final class EventForwarder implements EventHandler {
/**
* handle an event.
*
* @param event
* the event.
*/
public void handleEvent(final Event event) {
try {
final RemoteEventMessage msg = new RemoteEventMessage();
msg.setTopic(event.getTopic());
final String[] propertyNames = event.getPropertyNames();
final Dictionary props = new Hashtable();
for (int i = 0; i < propertyNames.length; i++) {
props.put(propertyNames[i], event.getProperty(propertyNames[i]));
}
props.put(RemoteEventMessage.EVENT_SENDER_URI, networkChannel.getLocalAddress());
msg.setProperties(props);
send(msg);
if (RemoteOSGiServiceImpl.MSG_DEBUG) {
RemoteOSGiServiceImpl.log.log(LogService.LOG_DEBUG, "Forwarding Event " + event);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}
/**
* callback that signals when the result has become available.
*
* @author Jan S. Rellermeyer
*
*/
class WaitingCallback implements AsyncCallback {
private RemoteOSGiMessage result;
public synchronized void result(RemoteOSGiMessage msg) {
result = msg;
this.notifyAll();
}
synchronized RemoteOSGiMessage getResult() {
return result;
}
}
}
|
9242614b53e7edbdc9cad0222237381411c2485c
| 1,170 |
java
|
Java
|
src/main/java/egger/software/au_streams/StreamConstruction.java
|
eggeral/java-examples
|
165bab9a20c408dd2a3d6ffa0e7d2ce5191ba1b1
|
[
"Apache-2.0"
] | 1 |
2017-07-11T09:16:25.000Z
|
2017-07-11T09:16:25.000Z
|
src/main/java/egger/software/au_streams/StreamConstruction.java
|
eggeral/java-examples
|
165bab9a20c408dd2a3d6ffa0e7d2ce5191ba1b1
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/egger/software/au_streams/StreamConstruction.java
|
eggeral/java-examples
|
165bab9a20c408dd2a3d6ffa0e7d2ce5191ba1b1
|
[
"Apache-2.0"
] | null | null | null | 31.621622 | 103 | 0.675214 | 1,002,246 |
package egger.software.au_streams;
import java.time.Instant;
import java.util.Iterator;
import java.util.stream.Stream;
public class StreamConstruction {
public static void main(String[] args) {
Stream.Builder<Integer> streamBuilder = Stream.builder();
streamBuilder.accept(1);
streamBuilder.add(2).add(3);
streamBuilder.build().forEach(StreamConstruction::printElement);
System.out.println();
Stream.of(1,2,3).forEach(StreamConstruction::printElement);
System.out.println();
Stream.iterate(7, previous -> previous + 2).limit(5).forEach(StreamConstruction::printElement);
System.out.println();
Stream.generate(() -> 10).limit(5).forEach(StreamConstruction::printElement);
System.out.println();
Stream<Instant> timeStampStream = Stream.generate(() -> Instant.now());
Iterator<Instant> timeStampIterator = timeStampStream.iterator();
System.out.println(timeStampIterator.next());
System.out.println(timeStampIterator.next());
}
private static void printElement(Integer element) {
System.out.print(element + ", ");
}
}
|
9242625295f736500ffd8241ea3a88b6db6ed7f7
| 2,427 |
java
|
Java
|
modules/core/src/test/java/org/apache/ignite/internal/processors/query/QueryUtilsTest.java
|
kotari4u/ignite
|
af3e5015ad4d42c38d7b975dbca7abe0f2540884
|
[
"Apache-2.0"
] | null | null | null |
modules/core/src/test/java/org/apache/ignite/internal/processors/query/QueryUtilsTest.java
|
kotari4u/ignite
|
af3e5015ad4d42c38d7b975dbca7abe0f2540884
|
[
"Apache-2.0"
] | null | null | null |
modules/core/src/test/java/org/apache/ignite/internal/processors/query/QueryUtilsTest.java
|
kotari4u/ignite
|
af3e5015ad4d42c38d7b975dbca7abe0f2540884
|
[
"Apache-2.0"
] | null | null | null | 37.921875 | 161 | 0.696333 | 1,002,247 |
package org.apache.ignite.internal.processors.query;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.processors.query.property.QueryBinaryProperty;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class QueryUtilsTest {
@Test
public void testBuildBinaryProperty()
{
GridKernalContext ctx = null;
String pathStr = "user.address.streetName";
Class<?> resType = null;
Map<String, String> aliases = new HashMap<>();
boolean isKeyField = false;
boolean notNull = false;
Object dlftVal = "DEFAULT";
int precision = 10;
int scale = 5;
QueryBinaryProperty queryBinaryProperty = QueryUtils.buildBinaryProperty(ctx, pathStr, resType, aliases, isKeyField, notNull, dlftVal, precision, scale);
Assert.assertNotNull(queryBinaryProperty);
assertEquals(dlftVal, queryBinaryProperty.defaultValue());
assertEquals(precision, queryBinaryProperty.precision());
assertEquals(scale, queryBinaryProperty.scale());
assertEquals(pathStr, queryBinaryProperty.name());
assertEquals(notNull, queryBinaryProperty.notNull());
assertEquals(resType, queryBinaryProperty.type());
}
@Test
public void testBuildBinaryPropertyWithAlias()
{
GridKernalContext ctx = null;
String pathStr = "user.address.streetName";
String alias = "user_address_streetName";
Class<?> resType = null;
Map<String, String> aliases = new HashMap<>();
aliases.put(pathStr, alias);
boolean isKeyField = false;
boolean notNull = false;
Object dlftVal = "DEFAULT";
int precision = 10;
int scale = 5;
QueryBinaryProperty queryBinaryProperty = QueryUtils.buildBinaryProperty(ctx, pathStr, resType, aliases, isKeyField, notNull, dlftVal, precision, scale);
Assert.assertNotNull(queryBinaryProperty);
assertEquals(dlftVal, queryBinaryProperty.defaultValue());
assertEquals(precision, queryBinaryProperty.precision());
assertEquals(scale, queryBinaryProperty.scale());
assertEquals(alias, queryBinaryProperty.name());
assertEquals(notNull, queryBinaryProperty.notNull());
assertEquals(resType, queryBinaryProperty.type());
}
}
|
924262bac18b194872f80fdf4a76a0b3e97378e1
| 2,041 |
java
|
Java
|
src/com/askviky/communityservice/activity/GalleryActivity.java
|
AppOpenSource/CommunityService
|
7d3728cb77ebeacf26a17b684a4a9eeac84a0486
|
[
"Apache-2.0"
] | null | null | null |
src/com/askviky/communityservice/activity/GalleryActivity.java
|
AppOpenSource/CommunityService
|
7d3728cb77ebeacf26a17b684a4a9eeac84a0486
|
[
"Apache-2.0"
] | null | null | null |
src/com/askviky/communityservice/activity/GalleryActivity.java
|
AppOpenSource/CommunityService
|
7d3728cb77ebeacf26a17b684a4a9eeac84a0486
|
[
"Apache-2.0"
] | null | null | null | 29.57971 | 98 | 0.767761 | 1,002,248 |
package com.askviky.communityservice.activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.Toast;
import com.askviky.common.activity.AppBaseActivity;
import com.askviky.communityservice.R;
import com.askviky.communityservice.adapter.GalleryAdapter;
public class GalleryActivity extends AppBaseActivity {
private GalleryAdapter mImgAdapter = null; // 声明图片资源对象
private Gallery mGallery = null;
@Override
protected void initVariables() {
// TODO Auto-generated method stub
}
@Override
protected void initViews(Bundle savedInstanceState) {
setContentView(R.layout.activity_gallery);
mGallery = (Gallery) findViewById(R.id.gallery);
mImgAdapter = new GalleryAdapter(this);
mGallery.setAdapter(mImgAdapter); // 设置图片资源
mGallery.setGravity(Gravity.CENTER_HORIZONTAL); // 设置水平居中显示
mGallery.setSelection(mImgAdapter.mImgs.length * 100); // 设置起始图片显示位置(可以用来制作gallery循环显示效果)
mGallery.setOnItemClickListener(mClickListener); // 设置点击图片的监听事件(需要用手点击才触发,滑动时不触发)
mGallery.setOnItemSelectedListener(mSelectedListener); // 设置选中图片的监听事件(当图片滑到屏幕正中,则视为自动选中)
mGallery.setUnselectedAlpha(0.3f); // 设置未选中图片的透明度
mGallery.setSpacing(40); // 设置图片之间的间距
}
@Override
protected void loadData() {
// TODO Auto-generated method stub
}
// 点击图片的监听事件
AdapterView.OnItemClickListener mClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(GalleryActivity.this, "点击图片 " + (position + 1), 100).show();
}
};
// 选中图片的监听事件
AdapterView.OnItemSelectedListener mSelectedListener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(GalleryActivity.this, "选中图片 " + (position + 1), 20).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
}
|
924263938693727f7675a3049c8398097a33bec9
| 5,855 |
java
|
Java
|
app/src/main/java/WIP/mame056/vidhrdw/commando.java
|
javaemus/ArcoFlexDroid
|
e9ece569f14b65c906612e2574d15dacbf4bfc80
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/WIP/mame056/vidhrdw/commando.java
|
javaemus/ArcoFlexDroid
|
e9ece569f14b65c906612e2574d15dacbf4bfc80
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/WIP/mame056/vidhrdw/commando.java
|
javaemus/ArcoFlexDroid
|
e9ece569f14b65c906612e2574d15dacbf4bfc80
|
[
"Apache-2.0"
] | null | null | null | 28.149038 | 132 | 0.568915 | 1,002,249 |
/***************************************************************************
vidhrdw.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
/*
* ported to v0.56
* using automatic conversion tool v0.01
*/
package WIP.mame056.vidhrdw;
import static arcadeflex056.fucPtr.*;
import static common.ptr.*;
import static mame056.tilemapH.*;
import static mame056.tilemapC.*;
//import static mame037b11.mame.tilemapC.*;
import static mame056.cpuintrfH.*;
import static mame056.cpuintrf.*;
import static mame056.cpuexec.*;
import static mame056.cpuexecH.*;
import static mame056.common.*;
import static mame056.commonH.*;
import static mame056.drawgfxH.*;
import static mame056.drawgfx.*;
import static mame056.mame.*;
import static mame056.vidhrdw.generic.*;
public class commando
{
public static UBytePtr commando_fgvideoram=new UBytePtr(), commando_bgvideoram=new UBytePtr();
static struct_tilemap fg_tilemap;
static struct_tilemap bg_tilemap;
/***************************************************************************
Callbacks for the TileMap code
***************************************************************************/
public static GetTileInfoPtr get_fg_tile_info = new GetTileInfoPtr() {
public void handler(int tile_index) {
int code, color;
code = commando_fgvideoram.read(tile_index);
color = commando_fgvideoram.read(tile_index + 0x400);
SET_TILE_INFO(
0,
code + ((color & 0xc0) << 2),
color & 0x0f
,TILE_FLIPYX((color & 0x30) >> 4)
);
//tile_info.flags = TILE_FLIPYX((color & 0x30) >> 4);
}
};
static GetTileInfoPtr get_bg_tile_info = new GetTileInfoPtr() {
public void handler(int tile_index) {
int code, color;
code = commando_bgvideoram.read(tile_index);
color = commando_bgvideoram.read(tile_index + 0x400);
SET_TILE_INFO(
1,
code + ((color & 0xc0) << 2),
color & 0x0f
,TILE_FLIPYX((color & 0x30) >> 4)
);
}
};
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
public static VhStartPtr commando_vh_start = new VhStartPtr() { public int handler()
{
fg_tilemap = tilemap_create(get_fg_tile_info,tilemap_scan_rows,TILEMAP_TRANSPARENT, 8, 8,32,32);
bg_tilemap = tilemap_create(get_bg_tile_info,tilemap_scan_cols,TILEMAP_OPAQUE, 16,16,32,32);
if (fg_tilemap==null || bg_tilemap==null)
return 1;
tilemap_set_transparent_pen(fg_tilemap,3);
fg_tilemap.transparent_pen = 3;
return 0;
} };
/***************************************************************************
Memory handlers
***************************************************************************/
public static WriteHandlerPtr commando_fgvideoram_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
commando_fgvideoram.write(offset, data);
tilemap_mark_tile_dirty(fg_tilemap,offset & 0x3ff);
} };
public static WriteHandlerPtr commando_bgvideoram_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
commando_bgvideoram.write(offset, data);
tilemap_mark_tile_dirty(bg_tilemap,offset & 0x3ff);
} };
static int[] scroll=new int[2];
public static WriteHandlerPtr commando_scrollx_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
scroll[offset] = data;
tilemap_set_scrollx(bg_tilemap,0,scroll[0] | (scroll[1] << 8));
} };
public static WriteHandlerPtr commando_scrolly_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
scroll[offset] = data;
tilemap_set_scrolly(bg_tilemap,0,scroll[0] | (scroll[1] << 8));
} };
public static WriteHandlerPtr commando_c804_w = new WriteHandlerPtr() {public void handler(int offset, int data)
{
/* bits 0 and 1 are coin counters */
coin_counter_w.handler(0, data & 0x01);
coin_counter_w.handler(1, data & 0x02);
/* bit 4 resets the sound CPU */
cpu_set_reset_line(1,(data & 0x10)!=0 ? ASSERT_LINE : CLEAR_LINE);
/* bit 7 flips screen */
flip_screen_set(~data & 0x80);
} };
/***************************************************************************
Display refresh
***************************************************************************/
static void draw_sprites(mame_bitmap bitmap)
{
int offs;
for (offs = spriteram_size[0] - 4;offs >= 0;offs -= 4)
{
int sx,sy,flipx,flipy,bank,attr;
/* bit 1 of attr is not used */
attr = buffered_spriteram.read(offs + 1);
sx = buffered_spriteram.read(offs + 3) - ((attr & 0x01) << 8);
sy = buffered_spriteram.read(offs + 2);
flipx = attr & 0x04;
flipy = attr & 0x08;
bank = (attr & 0xc0) >> 6;
if (flip_screen() != 0)
{
sx = 240 - sx;
sy = 240 - sy;
flipx = flipx!=0?0:1;
flipy = flipy!=0?0:1;
}
if (bank < 3)
drawgfx(bitmap,Machine.gfx[2],
buffered_spriteram.read(offs) + 256 * bank,
(attr & 0x30) >> 4,
flipx,flipy,
sx,sy,
Machine.visible_area,TRANSPARENCY_PEN,15);
}
}
public static VhUpdatePtr commando_vh_screenrefresh = new VhUpdatePtr() { public void handler(mame_bitmap bitmap,int full_refresh)
{
tilemap_draw(bitmap,bg_tilemap,0,0);
draw_sprites(bitmap);
tilemap_draw(bitmap,fg_tilemap,0,0);
} };
public static VhEofCallbackPtr commando_eof_callback = new VhEofCallbackPtr() {
public void handler() {
buffer_spriteram_w.handler(0,0);
}
};
}
|
9242639e26b8d814e096f168bc2a866dc78b6c13
| 10,211 |
java
|
Java
|
RNAstructure_Source/java_interface/src/ur_rna/RNAstructureUI/utilities/NumberField.java
|
mayc2/PseudoKnot_research
|
33e94b84435d87aff3d89dbad970c438ac173331
|
[
"MIT"
] | null | null | null |
RNAstructure_Source/java_interface/src/ur_rna/RNAstructureUI/utilities/NumberField.java
|
mayc2/PseudoKnot_research
|
33e94b84435d87aff3d89dbad970c438ac173331
|
[
"MIT"
] | null | null | null |
RNAstructure_Source/java_interface/src/ur_rna/RNAstructureUI/utilities/NumberField.java
|
mayc2/PseudoKnot_research
|
33e94b84435d87aff3d89dbad970c438ac173331
|
[
"MIT"
] | null | null | null | 27.375335 | 78 | 0.647635 | 1,002,250 |
/*
* (c) 2011 Mathews Lab, University of Rochester Medical Center.
*
* This software is part of a group specifically designed for the RNAstructure
* secondary structure prediction program and its related applications.
*/
package ur_rna.RNAstructureUI.utilities;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
/**
* A class that creates a text field whose contents may be bounded by a
* minimum or maximum value.
*
* @author Jessica S. Reuter
*/
public abstract class NumberField
extends JTextField {
private static final long serialVersionUID = 20120802;
/**
* The initial default value of the field.
*/
protected Number initial;
/**
* The maximum value of the field.
*/
protected Number maximum;
/**
* The minimum value of the field.
*/
protected Number minimum;
/**
* Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
* @param max The maximum value of the field.
*/
protected NumberField(
String text, Number value, Number min, Number max ) {
// Set the field name and values.
setName( text );
resetField( value, min, max );
// Add a key listener so the field can only accept valid characters.
addKeyListener( new KeyAdapter() {
/**
* Check to see if the next character is valid, and if not,
* consume it.
*
* @param e The key event.
*/
private void checkKey( KeyEvent e ) {
// Get the next character.
char key = e.getKeyChar();
// If the next character is a digit, allow it.
if( Character.isDigit( key ) ) { return; }
// If the next character is a backspace character, allow it.
if( key == KeyEvent.VK_BACK_SPACE ) { return; }
// If the character is a negative sign, and a negative sign is
// acceptable right now, allow it.
boolean negativeSign = ( key == '-' );
boolean isEmptyText = getText().trim().equals( "" );
boolean negativeBound = ( minimum.doubleValue() < 0.0 );
if( negativeSign && isEmptyText && negativeBound ) { return; }
// Do any extra checking specific to a particular field type,
// and if the character was valid by that check, allow it.
boolean valid = doAdditionalCheck( key );
if( valid ) { return; }
// If none of the previous validity checks worked, consume the
// character so it isn't outputted.
e.consume();
}
@Override
public void keyPressed( KeyEvent e ) { checkKey( e ); }
@Override
public void keyTyped( KeyEvent e ) { checkKey( e ); }
});
// Add a focus listener so the field will check itself as soon as the
// focus is lost.
addFocusListener( new FocusAdapter() {
@Override
public void focusLost( FocusEvent e ) {
boolean ok = checkValue();
if( ok == false ) { setText( initial.toString() ); }
}
});
}
/**
* Check the value of a field to make sure it's valid.
*
* @return True if the field value is valid, false if not.
*/
protected abstract boolean checkValue();
/**
* Do any additional necessary checks on a key character to make sure it's
* valid to be output.
*
* @param key The key character.
*/
protected boolean doAdditionalCheck( char key ) { return false; }
/**
* Get the text field's numeric value.
*
* @return The numeric value.
*/
public abstract Number getValue();
/**
* Reset a field value, if it's within bounds.
*
* @param value The initial numeric value of the field.
*/
public void resetField( Number value ) {
// If the range of numbers given isn't valid, return.
boolean goodMin = ( minimum.doubleValue() <= value.doubleValue() );
boolean goodMax = ( maximum.doubleValue() >= value.doubleValue() );
if( !( goodMin && goodMax ) ) { return; }
// Set the field value.
setText( value.toString() );
initial = value;
}
/**
* Reset a field value and bounds.
*
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
* @param max The maximum value of the field.
*/
public void resetField( Number value, Number min, Number max ) {
// If the range of numbers given isn't valid, return.
boolean goodMin = ( min.doubleValue() <= value.doubleValue() );
boolean goodMax = ( max.doubleValue() >= value.doubleValue() );
if( !( goodMin && goodMax ) ) { return; }
// Set the field value and bounds.
setText( value.toString() );
initial = value;
minimum = min;
maximum = max;
}
/**
* An inner class that handles a field which contains a double value.
*
* @author Jessica S. Reuter
*/
public static class DoubleField
extends NumberField {
private static final long serialVersionUID = 20120802;
/**
* Unbounded Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
*/
public DoubleField( String text, Number value ) {
super( text, value, Double.MAX_VALUE * -1, Double.MAX_VALUE );
}
/**
* Minimum Bounds Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
*/
public DoubleField( String text, Number value, Number min ) {
super( text, value, min, Double.MAX_VALUE );
}
/**
* Minimum and Maximum Bounds Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
* @param max The maximum value of the field.
*/
public DoubleField(
String text, Number value, Number min, Number max ) {
super( text, value, min, max );
}
@Override
protected boolean checkValue() {
try {
Double value = Double.parseDouble( getText() );
if( value < minimum.doubleValue() ) { return false; }
if( value > maximum.doubleValue() ) { return false; }
} catch( Exception e ) { return false; }
return true;
}
@Override
protected boolean doAdditionalCheck( char key ) {
boolean decimal = ( key == '.' );
boolean noPreviousDecimal = ( getText().contains( "." ) == false );
return ( decimal && noPreviousDecimal );
}
@Override
public Double getValue() {
Double value = null;
try { value = Double.parseDouble( getText() ); }
catch( NumberFormatException e ) { /* Will never be thrown */ }
return value;
}
}
/**
* An inner class that handles a field which contains a float value.
*
* @author Jessica S. Reuter
*/
public static class FloatField
extends NumberField {
private static final long serialVersionUID = 20120802;
/**
* Unbounded Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
*/
public FloatField( String text, Number value ) {
super( text, value, Float.MAX_VALUE * -1, Float.MAX_VALUE );
}
/**
* Minimum Bounds Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
*/
public FloatField( String text, Number value, Number min ) {
super( text, value, min, Float.MAX_VALUE );
}
/**
* Minimum and Maximum Bounds Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
* @param max The maximum value of the field.
*/
public FloatField(
String text, Number value, Number min, Number max ) {
super( text, value, min, max );
}
@Override
protected boolean checkValue() {
try {
Float value = Float.parseFloat( getText() );
if( value < minimum.floatValue() ) { return false; }
if( value > maximum.floatValue() ) { return false; }
} catch( Exception e ) { return false; }
return true;
}
@Override
protected boolean doAdditionalCheck( char key ) {
boolean decimal = ( key == '.' );
boolean noPreviousDecimal = ( getText().contains( "." ) == false );
return ( decimal && noPreviousDecimal );
}
@Override
public Float getValue() {
Float value = null;
try { value = Float.parseFloat( getText() ); }
catch( NumberFormatException e ) { /* Will never be thrown */ }
return value;
}
}
/**
* An inner class that handles a field which contains an integer value.
*
* @author Jessica S. Reuter
*/
public static class IntegerField
extends NumberField {
private static final long serialVersionUID = 20120802;
/**
* Unbounded Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
*/
public IntegerField( String text, Integer value ) {
super( text, value, Integer.MAX_VALUE * -1, Integer.MAX_VALUE );
}
/**
* Minimum Bounds Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
*/
public IntegerField( String text, Integer value, Integer min ) {
super( text, value, min, Integer.MAX_VALUE );
}
/**
* Minimum and Maximum Bounds Constructor.
*
* @param text The name of the field.
* @param value The initial numeric value of the field.
* @param min The minimum value of the field.
* @param max The maximum value of the field.
*/
public IntegerField(
String text, Integer value, Integer min, Integer max ) {
super( text, value, min, max );
}
@Override
protected boolean checkValue() {
try {
Integer value = Integer.parseInt( getText() );
if( value < minimum.intValue() ) { return false; }
if( value > maximum.intValue() ) { return false; }
} catch( Exception e ) { return false; }
return true;
}
@Override
public Integer getValue() {
Integer value = null;
try { value = Integer.parseInt( getText() ); }
catch( NumberFormatException e ) { /* Will never be thrown */ }
return value;
}
}
}
|
924263c1203698219817db2387914bf3b022aa70
| 2,728 |
java
|
Java
|
NowPlaying/Android/src/org/metasyntactic/utilities/DateUtilities.java
|
avoronchenko/metasyntactic
|
cea5408f8c575aae4f280df983f511b5fa7ed541
|
[
"Apache-2.0"
] | 1 |
2016-01-02T10:37:45.000Z
|
2016-01-02T10:37:45.000Z
|
NowPlaying/Android/src/org/metasyntactic/utilities/DateUtilities.java
|
avoronchenko/metasyntactic
|
cea5408f8c575aae4f280df983f511b5fa7ed541
|
[
"Apache-2.0"
] | 1 |
2016-12-15T12:24:46.000Z
|
2016-12-15T12:24:46.000Z
|
NowPlaying/Android/src/org/metasyntactic/utilities/DateUtilities.java
|
avoronchenko/metasyntactic
|
cea5408f8c575aae4f280df983f511b5fa7ed541
|
[
"Apache-2.0"
] | null | null | null | 29.021277 | 148 | 0.691349 | 1,002,251 |
//Copyright 2008 Cyrus Najmabadi
//
//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.metasyntactic.utilities;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtilities {
private static final Date today;
private static final DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG);
private static final Object lock = new Object();
static {
final Date dt = new Date();
final Calendar c1 = Calendar.getInstance();
c1.setTime(dt);
final Calendar c2 = Calendar.getInstance();
c2.clear();
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
c2.set(Calendar.HOUR_OF_DAY, 12);
today = c2.getTime();
}
private DateUtilities() {
}
public static Date getToday() {
return today;
}
public static boolean use24HourTime() {
return false;
}
public static boolean isToday(final Date date) {
return isSameDay(getToday(), date);
}
public static boolean isSameDay(final Date d1, final Date d2) {
final Calendar c1 = Calendar.getInstance();
final Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.DAY_OF_MONTH) == c2
.get(Calendar.DAY_OF_MONTH);
}
public static String formatLongDate(final Date date) {
synchronized (lock) {
return longFormat.format(date);
}
}
public static Date parseISO8601Date(final String string) {
if (string.length() == 10) {
try {
final int year = Integer.parseInt(string.substring(0, 4));
final int month = Integer.parseInt(string.substring(5, 7));
final int day = Integer.parseInt(string.substring(8, 10));
final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
} catch (NumberFormatException ignored) {
}
}
return null;
}
}
|
9242642bc9ea414620876135b0171121f31d0820
| 1,462 |
java
|
Java
|
library/src/main/java/com/appandweb/multimoduleapp/library/common/LibActivity.java
|
appandweb/MultiModuleApp
|
99287172a405228f263737d9c0faf6751691bfda
|
[
"Apache-2.0"
] | null | null | null |
library/src/main/java/com/appandweb/multimoduleapp/library/common/LibActivity.java
|
appandweb/MultiModuleApp
|
99287172a405228f263737d9c0faf6751691bfda
|
[
"Apache-2.0"
] | null | null | null |
library/src/main/java/com/appandweb/multimoduleapp/library/common/LibActivity.java
|
appandweb/MultiModuleApp
|
99287172a405228f263737d9c0faf6751691bfda
|
[
"Apache-2.0"
] | 1 |
2019-06-05T11:34:41.000Z
|
2019-06-05T11:34:41.000Z
| 36.55 | 71 | 0.703146 | 1,002,252 |
package com.appandweb.multimoduleapp.library.common;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.appandweb.multimoduleapp.library.BuildConfig;
import com.appandweb.multimoduleapp.library.R;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.iid.FirebaseInstanceId;
import java.util.List;
public class LibActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lib);
boolean hasBeenInitialized = false;
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId(BuildConfig.LibraryFirebaseId)
.setApiKey(BuildConfig.LibraryFirebaseApiKey)
.setDatabaseUrl(BuildConfig.LibraryFirebaseDatabaseUrl)
.build();
List<FirebaseApp> firebaseApps = FirebaseApp.getApps(this);
for (FirebaseApp app : firebaseApps) {
if (app.getName().equals(FirebaseApp.DEFAULT_APP_NAME)) {
hasBeenInitialized = true;
}
}
if (!hasBeenInitialized) {
FirebaseApp.initializeApp(this, options);
}
String token = FirebaseInstanceId.getInstance().getToken();
Toast.makeText(this, token, Toast.LENGTH_LONG).show();
}
}
|
9242652770c155e721becaa782af8d17904145c5
| 5,491 |
java
|
Java
|
freeipa/src/test/java/com/sequenceiq/freeipa/service/freeipa/user/ums/UmsUsersStateProviderDispatcherTest.java
|
Beast2709/cloudbreak
|
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
|
[
"Apache-2.0"
] | 174 |
2017-07-14T03:20:42.000Z
|
2022-03-25T05:03:18.000Z
|
freeipa/src/test/java/com/sequenceiq/freeipa/service/freeipa/user/ums/UmsUsersStateProviderDispatcherTest.java
|
Beast2709/cloudbreak
|
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
|
[
"Apache-2.0"
] | 2,242 |
2017-07-12T05:52:01.000Z
|
2022-03-31T15:50:08.000Z
|
freeipa/src/test/java/com/sequenceiq/freeipa/service/freeipa/user/ums/UmsUsersStateProviderDispatcherTest.java
|
Beast2709/cloudbreak
|
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
|
[
"Apache-2.0"
] | 172 |
2017-07-12T08:53:48.000Z
|
2022-03-24T12:16:33.000Z
| 41.916031 | 104 | 0.69623 | 1,002,253 |
package com.sequenceiq.freeipa.service.freeipa.user.ums;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.sequenceiq.cloudbreak.auth.crn.CrnResourceDescriptor;
import com.sequenceiq.cloudbreak.auth.crn.CrnTestUtil;
import com.sequenceiq.freeipa.service.freeipa.user.model.UmsUsersState;
import com.sequenceiq.freeipa.service.freeipa.user.model.UsersState;
import io.grpc.StatusRuntimeException;
@ExtendWith(MockitoExtension.class)
class UmsUsersStateProviderDispatcherTest {
private static final String ACCOUNT_ID = UUID.randomUUID().toString();
private static final Set<String> ENVIRONMENT_CRNS = Set.of(
CrnTestUtil.getEnvironmentCrnBuilder()
.setAccountId(ACCOUNT_ID)
.setResource(UUID.randomUUID().toString())
.build()
.toString()
);
@Mock
private DefaultUmsUsersStateProvider defaultUmsUsersStateProvider;
@Mock
private BulkUmsUsersStateProvider bulkUmsUsersStateProvider;
@InjectMocks
private UmsUsersStateProviderDispatcher underTest;
@Test
void testFullSync() {
Set<String> userCrns = Set.of();
Set<String> machineUserCrns = Set.of();
Map<String, UmsUsersState> expected = createExpectedResponse();
when(bulkUmsUsersStateProvider.get(anyString(), any(Set.class), any(Optional.class)))
.thenReturn(expected);
Optional<String> requestIdOptional = Optional.of(UUID.randomUUID().toString());
Map<String, UmsUsersState> response = underTest.getEnvToUmsUsersStateMap(
ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional);
assertEquals(expected, response);
verify(bulkUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS, requestIdOptional);
verify(defaultUmsUsersStateProvider, never()).get(anyString(), any(Set.class),
any(Set.class), any(Set.class), any(Optional.class), anyBoolean());
}
@Test
void testBulkFallsBackToDefault() {
Set<String> userCrns = Set.of();
Set<String> machineUserCrns = Set.of();
when(bulkUmsUsersStateProvider.get(anyString(), any(Set.class), any(Optional.class)))
.thenThrow(StatusRuntimeException.class);
Map<String, UmsUsersState> expected = createExpectedResponse();
when(defaultUmsUsersStateProvider.get(anyString(), any(Set.class),
any(Set.class), any(Set.class), any(Optional.class), anyBoolean()))
.thenReturn(expected);
Optional<String> requestIdOptional = Optional.of(UUID.randomUUID().toString());
Map<String, UmsUsersState> response = underTest.getEnvToUmsUsersStateMap(
ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional);
assertEquals(expected, response);
verify(bulkUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS, requestIdOptional);
verify(defaultUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional, true);
}
@Test
void testPartialSync() {
Set<String> userCrns = Set.of(createActorCrn(CrnResourceDescriptor.USER));
Set<String> machineUserCrns = Set.of(createActorCrn(CrnResourceDescriptor.MACHINE_USER));
Map<String, UmsUsersState> expected = createExpectedResponse();
when(defaultUmsUsersStateProvider.get(anyString(), any(Set.class),
any(Set.class), any(Set.class), any(Optional.class), anyBoolean()))
.thenReturn(expected);
Optional<String> requestIdOptional = Optional.of(UUID.randomUUID().toString());
Map<String, UmsUsersState> response = underTest.getEnvToUmsUsersStateMap(
ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional);
assertEquals(expected, response);
verify(bulkUmsUsersStateProvider, never()).get(ACCOUNT_ID, ENVIRONMENT_CRNS, requestIdOptional);
verify(defaultUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional, false);
}
private Map<String, UmsUsersState> createExpectedResponse() {
return ENVIRONMENT_CRNS.stream()
.collect(Collectors.toMap(Function.identity(),
env -> UmsUsersState.newBuilder()
.setUsersState(UsersState.newBuilder().build())
.build()));
}
private String createActorCrn(CrnResourceDescriptor resourceDescriptor) {
return CrnTestUtil.getCustomCrnBuilder(resourceDescriptor)
.setAccountId(ACCOUNT_ID)
.build()
.toString();
}
}
|
924265b1a1f5e91864f226904850e290c02e3c72
| 1,493 |
java
|
Java
|
api-boot-project/api-boot-maven-plugins/api-boot-mybatis-enhance-maven-codegen/src/main/java/org/minbox/framework/api/boot/maven/plugin/mybatis/enhance/codegen/EnhanceCodegenConstant.java
|
UniqueDong/api-boot
|
7ed6e146bd3b3f0965f7b19e99fd08bb63e4bf93
|
[
"Apache-2.0"
] | 310 |
2019-03-13T09:38:37.000Z
|
2020-10-10T08:33:05.000Z
|
api-boot-project/api-boot-maven-plugins/api-boot-mybatis-enhance-maven-codegen/src/main/java/org/minbox/framework/api/boot/maven/plugin/mybatis/enhance/codegen/EnhanceCodegenConstant.java
|
UniqueDong/api-boot
|
7ed6e146bd3b3f0965f7b19e99fd08bb63e4bf93
|
[
"Apache-2.0"
] | 14 |
2019-03-20T08:06:25.000Z
|
2019-08-20T00:22:36.000Z
|
api-boot-project/api-boot-maven-plugins/api-boot-mybatis-enhance-maven-codegen/src/main/java/org/minbox/framework/api/boot/maven/plugin/mybatis/enhance/codegen/EnhanceCodegenConstant.java
|
UniqueDong/api-boot
|
7ed6e146bd3b3f0965f7b19e99fd08bb63e4bf93
|
[
"Apache-2.0"
] | 95 |
2019-03-14T01:41:34.000Z
|
2021-09-15T03:15:31.000Z
| 26.192982 | 80 | 0.634293 | 1,002,254 |
/*
* Copyright [2019] [恒宇少年 - 于起宇]
*
* 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.minbox.framework.api.boot.maven.plugin.mybatis.enhance.codegen;
/**
* mybatis enhance codegen constant
*
* @author:恒宇少年 - 于起宇
* <p>
* DateTime:2019-05-25 13:50
* Blog:http://blog.yuqiyu.com
* WebSite:http://www.jianshu.com/u/092df3f77bca
* Gitee:https://gitee.com/hengboy
* GitHub:https://github.com/hengboy
*/
public interface EnhanceCodegenConstant {
/**
* point
*/
String POINT = ".";
/**
* empty string
*/
String EMPTY_STRING = "";
/**
* timestamp default value
*/
String CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP";
/**
* classes path
*/
String CLASSES_PATH = ".target.classes.";
/**
* codegen.setting.json
*/
String SETTING_JSON = "codegen.setting.json";
/**
* java file suffix
*/
String JAVA_SUFFIX = ".java";
}
|
924265d7504eaa3bdc38419e5a296d7436ed24af
| 865 |
java
|
Java
|
Juc/src/readwrite/LockDegradation.java
|
CodeWater404/JavaCode
|
03d7bb4091d0beb10189b5e5577239e6ac3b3a48
|
[
"MIT"
] | null | null | null |
Juc/src/readwrite/LockDegradation.java
|
CodeWater404/JavaCode
|
03d7bb4091d0beb10189b5e5577239e6ac3b3a48
|
[
"MIT"
] | null | null | null |
Juc/src/readwrite/LockDegradation.java
|
CodeWater404/JavaCode
|
03d7bb4091d0beb10189b5e5577239e6ac3b3a48
|
[
"MIT"
] | null | null | null | 22.179487 | 72 | 0.553757 | 1,002,255 |
package readwrite;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author : CodeWater
* @create :2022-06-03-18:04
* @Function Description :演示锁降级:写锁变读锁
*
*/
public class LockDegradation {
public static void main( String[] args ) {
//可重入读写锁对象
ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
//读锁
ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
//写锁
ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
//锁降级
//1 获取写锁
writeLock.lock();
System.out.println( "----------codewater-----------" );
//2 获取读锁
readLock.lock();
System.out.println( "-----------read................" );
//3 释放写锁
writeLock.unlock();
//4 释放读锁
readLock.unlock();
}
}
|
924266821f6c82c59c41040373c27aae4a7069e0
| 3,728 |
java
|
Java
|
apps/Messaging/src/com/android/messaging/ui/OrientedBitmapDrawable.java
|
Keneral/apackages
|
af6a7ffde2e52d8d4e073b4030244551246248ad
|
[
"Unlicense"
] | 15 |
2019-12-24T11:01:54.000Z
|
2022-01-26T04:59:36.000Z
|
apps/Messaging/src/com/android/messaging/ui/OrientedBitmapDrawable.java
|
Keneral/apackages
|
af6a7ffde2e52d8d4e073b4030244551246248ad
|
[
"Unlicense"
] | 7 |
2019-03-22T12:12:23.000Z
|
2019-08-15T05:15:43.000Z
|
apps/Messaging/src/com/android/messaging/ui/OrientedBitmapDrawable.java
|
Keneral/apackages
|
af6a7ffde2e52d8d4e073b4030244551246248ad
|
[
"Unlicense"
] | 14 |
2019-11-17T05:13:16.000Z
|
2022-01-18T19:17:47.000Z
| 35.504762 | 100 | 0.674356 | 1,002,256 |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.messaging.ui;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import com.android.messaging.util.exif.ExifInterface;
/**
* A drawable that draws a bitmap in a flipped or rotated orientation without having to adjust the
* bitmap
*/
public class OrientedBitmapDrawable extends BitmapDrawable {
private final ExifInterface.OrientationParams mOrientationParams;
private final Rect mDstRect;
private int mCenterX;
private int mCenterY;
private boolean mApplyGravity;
public static BitmapDrawable create(final int orientation, Resources res, Bitmap bitmap) {
if (orientation <= ExifInterface.Orientation.TOP_LEFT) {
// No need to adjust the bitmap, so just use a regular BitmapDrawable
return new BitmapDrawable(res, bitmap);
} else {
// Create an oriented bitmap drawable
return new OrientedBitmapDrawable(orientation, res, bitmap);
}
}
private OrientedBitmapDrawable(final int orientation, Resources res, Bitmap bitmap) {
super(res, bitmap);
mOrientationParams = ExifInterface.getOrientationParams(orientation);
mApplyGravity = true;
mDstRect = new Rect();
}
@Override
public int getIntrinsicWidth() {
if (mOrientationParams.invertDimensions) {
return super.getIntrinsicHeight();
}
return super.getIntrinsicWidth();
}
@Override
public int getIntrinsicHeight() {
if (mOrientationParams.invertDimensions) {
return super.getIntrinsicWidth();
}
return super.getIntrinsicHeight();
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mApplyGravity = true;
}
@Override
public void draw(Canvas canvas) {
if (mApplyGravity) {
Gravity.apply(getGravity(), getIntrinsicWidth(), getIntrinsicHeight(), getBounds(),
mDstRect);
mCenterX = mDstRect.centerX();
mCenterY = mDstRect.centerY();
if (mOrientationParams.invertDimensions) {
final Matrix matrix = new Matrix();
matrix.setRotate(mOrientationParams.rotation, mCenterX, mCenterY);
final RectF rotatedRect = new RectF(mDstRect);
matrix.mapRect(rotatedRect);
mDstRect.set((int) rotatedRect.left, (int) rotatedRect.top, (int) rotatedRect.right,
(int) rotatedRect.bottom);
}
mApplyGravity = false;
}
canvas.save();
canvas.scale(mOrientationParams.scaleX, mOrientationParams.scaleY, mCenterX, mCenterY);
canvas.rotate(mOrientationParams.rotation, mCenterX, mCenterY);
canvas.drawBitmap(getBitmap(), (Rect) null, mDstRect, getPaint());
canvas.restore();
}
}
|
92426845f75eb780d3ac0735be6c16e4aadaaa58
| 1,385 |
java
|
Java
|
chess/src/test/java/ru/job4j/chess/firuges/black/BishopBlackTest.java
|
Dm-JVL/games_oop_javafx
|
4ecfb69e4b935d634438e12b0d6cfe2b6348873d
|
[
"Apache-2.0"
] | null | null | null |
chess/src/test/java/ru/job4j/chess/firuges/black/BishopBlackTest.java
|
Dm-JVL/games_oop_javafx
|
4ecfb69e4b935d634438e12b0d6cfe2b6348873d
|
[
"Apache-2.0"
] | null | null | null |
chess/src/test/java/ru/job4j/chess/firuges/black/BishopBlackTest.java
|
Dm-JVL/games_oop_javafx
|
4ecfb69e4b935d634438e12b0d6cfe2b6348873d
|
[
"Apache-2.0"
] | null | null | null | 28.265306 | 110 | 0.690975 | 1,002,257 |
package ru.job4j.chess.firuges.black;
import junit.framework.TestCase;
import org.junit.Test;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import ru.job4j.chess.ImpossibleMoveException;
import ru.job4j.chess.firuges.Cell;
import ru.job4j.chess.firuges.Figure;
import static org.junit.Assert.assertThat;
import static ru.job4j.chess.firuges.Cell.findBy;
public class BishopBlackTest extends TestCase {
@Test
public void testPosition() {
Cell C1 = Cell.C1;
BishopBlack figurePositionTest = new BishopBlack(C1);
assertThat(figurePositionTest.position(), is(C1));
}
@Test
public void testCopy() {
Cell C1 = Cell.C1;
BishopBlack figureCopyTest = new BishopBlack(C1);
assertThat(figureCopyTest.copy(C1).position(), is(C1));
}
@Test
public void testDiagonalWay() throws ImpossibleMoveException {
assertThat(new BishopBlack(Cell.C1).way(Cell.G5), is(new Cell[]{Cell.D2, Cell.E3, Cell.F4, Cell.G5}));
}
@Test(expected = ImpossibleMoveException.class)
public void testNotDiagonalWay() throws ImpossibleMoveException {
try{
Cell[] steps = new BishopBlack(Cell.C1).way(Cell.G5);
} catch (ImpossibleMoveException e) {
System.out.println(e.getMessage());
}
}
}
|
924268c8a5e6bbbe8feb11bbf7992361f44ccaf5
| 87 |
java
|
Java
|
guice-fx/src/main/java/eu/dzim/guice/fx/util/BaseEnumType.java
|
bgmf/poc
|
2761f2911b45f98154af300d7774c8b7b041faa9
|
[
"Apache-2.0"
] | 5 |
2017-10-27T14:43:21.000Z
|
2020-05-11T18:35:07.000Z
|
guice-fx/src/main/java/eu/dzim/guice/fx/util/BaseEnumType.java
|
bgmf/poc
|
2761f2911b45f98154af300d7774c8b7b041faa9
|
[
"Apache-2.0"
] | null | null | null |
guice-fx/src/main/java/eu/dzim/guice/fx/util/BaseEnumType.java
|
bgmf/poc
|
2761f2911b45f98154af300d7774c8b7b041faa9
|
[
"Apache-2.0"
] | 2 |
2017-10-27T14:43:22.000Z
|
2020-05-08T02:24:37.000Z
| 14.5 | 31 | 0.724138 | 1,002,258 |
package eu.dzim.guice.fx.util;
public interface BaseEnumType {
String getKey();
}
|
92426a0ada6e9e0f27e42720d50831a36559ef4d
| 1,000 |
java
|
Java
|
binary_search-trees/src/structures/BSTNode.java
|
ishani-chakraborty/data-structures-algorithms
|
3b97bc928180191cb26d87d681a091a22090db11
|
[
"MIT"
] | null | null | null |
binary_search-trees/src/structures/BSTNode.java
|
ishani-chakraborty/data-structures-algorithms
|
3b97bc928180191cb26d87d681a091a22090db11
|
[
"MIT"
] | null | null | null |
binary_search-trees/src/structures/BSTNode.java
|
ishani-chakraborty/data-structures-algorithms
|
3b97bc928180191cb26d87d681a091a22090db11
|
[
"MIT"
] | 1 |
2022-02-27T22:59:43.000Z
|
2022-02-27T22:59:43.000Z
| 20 | 80 | 0.645 | 1,002,259 |
package structures;
/**
* A node in a BST.
* Note that BSTNode MUST implement BSTNodeInterface; removing this will resulit
* in your program failing to compile for the autograder.
*
* @author liberato
*
* @param <T> : generic type.
*/
public class BSTNode<T extends Comparable<T>> implements BSTNodeInterface<T> {
private T data;
private BSTNode<T> left;
private BSTNode<T> right;
public BSTNode<T> parent;
public BSTNode(T data, BSTNode<T> left, BSTNode<T> right) {
this.data = data;
this.left = left;
this.right = right;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public BSTNode<T> getLeft() {
return left;
}
public void setLeft(BSTNode<T> left) {
this.left = left;
if(left != null) left.parent = this;
}
public BSTNode<T> getRight() {
return right;
}
public void setRight(BSTNode<T> right) {
this.right = right;
if(right != null) right.parent = this;
}
}
|
92426aaf49087dede75c5fdbca5edaeb6cc67f3f
| 179 |
java
|
Java
|
src/org/darkmentat/GuitarScalesBoxes/Controls/GuitarView/OnFretIntervalSelectedListener.java
|
DarkMentat/GuitarScalesBoxes
|
4f4e97339658e7a95fe3bab921c49f839024b919
|
[
"Apache-2.0"
] | 1 |
2019-03-05T03:51:12.000Z
|
2019-03-05T03:51:12.000Z
|
src/org/darkmentat/GuitarScalesBoxes/Controls/GuitarView/OnFretIntervalSelectedListener.java
|
DarkMentat/GuitarScalesBoxes
|
4f4e97339658e7a95fe3bab921c49f839024b919
|
[
"Apache-2.0"
] | null | null | null |
src/org/darkmentat/GuitarScalesBoxes/Controls/GuitarView/OnFretIntervalSelectedListener.java
|
DarkMentat/GuitarScalesBoxes
|
4f4e97339658e7a95fe3bab921c49f839024b919
|
[
"Apache-2.0"
] | null | null | null | 25.571429 | 63 | 0.837989 | 1,002,260 |
package org.darkmentat.GuitarScalesBoxes.Controls.GuitarView;
public interface OnFretIntervalSelectedListener
{
public void OnIntervalSelected(int startFret, int endFret);
}
|
92426ac341cc6a8b224bc4966cb3bf885eacd4e3
| 559 |
java
|
Java
|
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/pending/clazz/QuotationConverter.java
|
nagaikenshin/schemaOrg
|
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
|
[
"Apache-2.0"
] | 1 |
2020-02-18T01:55:36.000Z
|
2020-02-18T01:55:36.000Z
|
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/pending/clazz/QuotationConverter.java
|
nagaikenshin/schemaOrg
|
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
|
[
"Apache-2.0"
] | null | null | null |
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/pending/clazz/QuotationConverter.java
|
nagaikenshin/schemaOrg
|
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
|
[
"Apache-2.0"
] | null | null | null | 24.304348 | 79 | 0.806798 | 1,002,261 |
package org.kyojo.schemaorg.m3n4.doma.pending.clazz;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaorg.m3n4.pending.impl.QUOTATION;
import org.kyojo.schemaorg.m3n4.pending.Clazz.Quotation;
@ExternalDomain
public class QuotationConverter implements DomainConverter<Quotation, String> {
@Override
public String fromDomainToValue(Quotation domain) {
return domain.getNativeValue();
}
@Override
public Quotation fromValueToDomain(String value) {
return new QUOTATION(value);
}
}
|
92426b592c2ab87cfe0c2d697e1393d78d6f5e55
| 326 |
java
|
Java
|
src/main/java/com/engwork/pgndb/users/platformaccess/PlatformAccessBean.java
|
pgnDataBase/pgnDB
|
3da7ac4d7c0cacae1bc9ad591033eb81213fa3fb
|
[
"MIT"
] | 5 |
2019-03-22T23:56:22.000Z
|
2022-01-06T08:18:31.000Z
|
src/main/java/com/engwork/pgndb/users/platformaccess/PlatformAccessBean.java
|
pgnDataBase/pgnDB
|
3da7ac4d7c0cacae1bc9ad591033eb81213fa3fb
|
[
"MIT"
] | 1 |
2019-08-12T08:04:33.000Z
|
2019-08-12T12:10:14.000Z
|
src/main/java/com/engwork/pgndb/users/platformaccess/PlatformAccessBean.java
|
pgnDataBase/pgnDB
|
3da7ac4d7c0cacae1bc9ad591033eb81213fa3fb
|
[
"MIT"
] | 2 |
2020-02-24T10:09:37.000Z
|
2022-03-05T17:23:19.000Z
| 21.733333 | 58 | 0.806748 | 1,002,262 |
package com.engwork.pgndb.users.platformaccess;
import com.engwork.pgndb.users.requestmodel.SignUpRequest;
public interface PlatformAccessBean {
void signUp(SignUpRequest signUpRequest);
String signIn(String username, String password);
void signOut(String token);
String generateTokenForUser(String username);
}
|
92426c857245d514f1f8ec1e7718c94533f95b10
| 3,947 |
java
|
Java
|
code/src/edu/uci/lasso/MathUtil.java
|
ignacioarnaldo/efs
|
6d991fafe203cb43a8eb6b553c622af80d5b5f65
|
[
"MIT"
] | 14 |
2015-09-14T22:16:28.000Z
|
2022-02-04T10:26:28.000Z
|
code/src/edu/uci/lasso/MathUtil.java
|
ShenkieRuben/efs
|
6d991fafe203cb43a8eb6b553c622af80d5b5f65
|
[
"MIT"
] | 1 |
2015-10-12T12:54:41.000Z
|
2015-10-12T14:22:50.000Z
|
code/src/edu/uci/lasso/MathUtil.java
|
ShenkieRuben/efs
|
6d991fafe203cb43a8eb6b553c622af80d5b5f65
|
[
"MIT"
] | 7 |
2015-09-04T15:07:42.000Z
|
2022-01-31T14:08:50.000Z
| 22.426136 | 88 | 0.439321 | 1,002,263 |
/**
* This implemenation is based on: Friedman, J., Hastie, T. and Tibshirani, R.
* (2008) Regularization Paths for Generalized Linear Models via Coordinate
* Descent. http://www-stat.stanford.edu/~hastie/Papers/glmnet.pdf
*
* @author Yasser Ganjisaffar
*/
package edu.uci.lasso;
import java.util.List;
/**
*
* @author Yasser Ganjisaffar
*/
public class MathUtil {
/**
*
* @param arr
* @return
*/
public static double getAvg(double[] arr) {
double sum = 0;
for (double item : arr) {
sum += item;
}
return sum / arr.length;
}
/**
*
* @param arr
* @return
*/
public static double getAvg(float[] arr) {
double sum = 0;
for (double item : arr) {
sum += item;
}
return sum / arr.length;
}
/**
*
* @param arr
* @return
*/
public static double getAvg(List<Double> arr) {
double sum = 0;
for (double item : arr) {
sum += item;
}
return sum / arr.size();
}
/**
*
* @param arr
* @return
*/
public static double getStg(double[] arr) {
return getStd(arr, getAvg(arr));
}
/**
*
* @param arr
* @return
*/
public static double getStg(List<Double> arr) {
return getStd(arr, getAvg(arr));
}
/**
*
* @param arr
* @param avg
* @return
*/
public static double getStd(double[] arr, double avg) {
double sum = 0;
for (double item : arr) {
sum += Math.pow(item - avg, 2);
}
return Math.sqrt(sum / arr.length);
}
/**
*
* @param arr
* @param avg
* @return
*/
public static double getStd(List<Double> arr, double avg) {
double sum = 0;
for (double item : arr) {
sum += Math.pow(item - avg, 2);
}
return Math.sqrt(sum / arr.size());
}
/**
*
* @param vector1
* @param vector2
* @param length
* @return
*/
public static double getDotProduct(float[] vector1, float[] vector2, int length) {
double product = 0;
for (int i = 0; i < length; i++) {
product += vector1[i] * vector2[i];
}
return product;
}
/**
*
* @param vector1
* @param vector2
* @param length
* @return
*/
public static double getDotProduct(double[] vector1, double[] vector2, int length) {
double product = 0;
for (int i = 0; i < length; i++) {
product += vector1[i] * vector2[i];
}
return product;
}
/**
*
* @param vector1
* @param vector2
* @return
*/
public static double getDotProduct(float[] vector1, float[] vector2)
{
return getDotProduct(vector1, vector2, vector1.length);
}
// Divides the second vector from the first one (vector1[i] /= val)
/**
*
* @param vector
* @param val
*/
public static void divideInPlace(float[] vector, float val)
{
int length = vector.length;
for (int i = 0; i < length; i++)
{
vector[i] /= val;
}
}
/**
*
* @param m
* @param n
* @return
*/
public static double[][] allocateDoubleMatrix(int m, int n) {
double[][] mat = new double[m][];
for (int i = 0; i < m; i++) {
mat[i] = new double[n];
}
return mat;
}
}
|
92426d2756fa8667b667697815dafb5a3ea6f681
| 4,448 |
java
|
Java
|
server/src/main/java/de/dhbwheidenheim/informatik/callsim/controller/Utils.java
|
Fabi281/callsim
|
afeeb74e25929bd8d818442f838e3e76cd1567ae
|
[
"MIT"
] | 3 |
2021-07-10T07:17:51.000Z
|
2022-01-25T12:29:15.000Z
|
server/src/main/java/de/dhbwheidenheim/informatik/callsim/controller/Utils.java
|
Fabi281/callsim
|
afeeb74e25929bd8d818442f838e3e76cd1567ae
|
[
"MIT"
] | null | null | null |
server/src/main/java/de/dhbwheidenheim/informatik/callsim/controller/Utils.java
|
Fabi281/callsim
|
afeeb74e25929bd8d818442f838e3e76cd1567ae
|
[
"MIT"
] | null | null | null | 27.8 | 102 | 0.639164 | 1,002,264 |
package de.dhbwheidenheim.informatik.callsim.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.dhbwheidenheim.informatik.callsim.model.User;
public class Utils {
private static final Logger log = LoggerFactory.getLogger(Utils.class);
public static void registerUser(User user, String location, ArrayList<User> users) {
// Add a user to the list of all current users and save it in a file (and close the Output-Streams)
try {
users.add(user);
FileOutputStream fos = new FileOutputStream(location);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(users);
oos.close();
fos.close();
log.info("Data saved at file location: " + location);
} catch (IOException e) {
log.info("Hmm.. Got an error while saving data to file " + e.toString());
}
}
public static ArrayList<User> readFromFile(String location) throws IOException {
ArrayList<User> users = new ArrayList<User>();
File f = new File(location);
// Check if the file exists and create it if not
if (!f.exists()) {
f.createNewFile();
}
// Read all users (ArrayList<User>) from the file and store the data in a variable
// (and close the Input-Streams) as well as returning said variable
try {
FileInputStream fis = new FileInputStream(location);
ObjectInputStream ois = new ObjectInputStream(fis);
users = (ArrayList<User>) ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
if(f.length() == 0){
log.info("file is empty");
} else {
log.info("error load cache from file " + e.toString());
}
}
return users;
}
/*
In the following there are 3 buildResponse()-Method each for a different usecase:
1. For the response regarding the users and their statuses
2. For the response regarding the start of a call (The positive response needs the username extra)
3. The default response which is used in all other cases
*/
public static String buildResponse(Map<String, String> User){
/*
Create a JSONObject in the following format:
{
"Action":"StatusResponse",
"User":[
{"Username":"Status"},
{"Username":"Status"},
{"Username":"Status"}
]
}
*/
JsonArrayBuilder users = Json.createArrayBuilder();
User.forEach((k, v) -> {
users.add(Json.createObjectBuilder().add(k,v));
});
JsonObject res = Json.createObjectBuilder()
.add("Action", "StatusResponse")
.add("User", users)
.build();
// Convert the JSONObject to a string as the sendText()-Method expects a string
Writer writer = new StringWriter();
Json.createWriter(writer).write(res);
return writer.toString();
}
public static String buildResponse(String Action, String Value, String Username){
/*
Create a JSONObject in the following format:
{
"Action":"<Actionname>",
"Value":"<Value>",
"Username":"<Username>"
}
*/
JsonObject res = Json.createObjectBuilder()
.add("Action", Action)
.add("Value", Value)
.add("Username", Username)
.build();
// Convert the JSONObject to a string as the sendText()-Method expects a string
Writer writer = new StringWriter();
Json.createWriter(writer).write(res);
return writer.toString();
}
public static String buildResponse(String Action, String Value){
/*
Create a JSONObject in the following format:
{
"Action":"<Actionname>",
"Value":"<Value>"
}
*/
JsonObject res = Json.createObjectBuilder()
.add("Action", Action)
.add("Value", Value)
.build();
// Convert the JSONObject to a string as the sendText()-Method expects a string
Writer writer = new StringWriter();
Json.createWriter(writer).write(res);
return writer.toString();
}
}
|
92426d50b5644dbf7861702cc49dc29150454f3a
| 1,229 |
java
|
Java
|
greedyalgorithms_solved/src/main/java/FindMajorityElement.java
|
MayurKJParekh/Elements-of-Programming-Interview-in-JAVA
|
f4acf107de3df627c4200e635a4d5010ab4bcee7
|
[
"MIT"
] | null | null | null |
greedyalgorithms_solved/src/main/java/FindMajorityElement.java
|
MayurKJParekh/Elements-of-Programming-Interview-in-JAVA
|
f4acf107de3df627c4200e635a4d5010ab4bcee7
|
[
"MIT"
] | null | null | null |
greedyalgorithms_solved/src/main/java/FindMajorityElement.java
|
MayurKJParekh/Elements-of-Programming-Interview-in-JAVA
|
f4acf107de3df627c4200e635a4d5010ab4bcee7
|
[
"MIT"
] | null | null | null | 33.216216 | 87 | 0.619203 | 1,002,265 |
import java.util.Iterator;
public class FindMajorityElement {
/*
18.5
For the given example, (b,a,c,a,a,b,a,a,c,a), we initialize the candidate to b. The
next element, a is different from the candidate, so the candidate's count goes to 0.
Therefore, we pick the next element c to be the candidate, and its count is1. The next
element, a, is different so the count goes back to 0. The next element is a, which is
the new candidate. The subsequent b decrements the count to 0. Therefore the next
element, a,is the new candidate, and it has a nonzero count till the end.
Since we spend0(1)time per entry, the time complexity is0(n). The additionalspace
complexity is0(1).
*/
public static String majoritySearch(Iterator<String> sequence) {
String candidate =
String iter;
int candidateCount = 0;
while (sequence.hasNext()){
iter = sequence.next();
if (candidateCount == 0) {
candidate = iter;
candidateCount = 1;
} else if (candidate.equals(iter)) {
++candidateCount ;
} else {
--candidateCount ;
}
}
return candidate;
}
}
|
92426e3d002fba8d3b63d67a7a06bdd64d2cad48
| 1,648 |
java
|
Java
|
third_party/android/platform-libcore/android-platform-libcore/support/src/test/java/tests/support/Support_Locale.java
|
phaezah7/openweave-core
|
88d8eaef62769bd567c7684a5f137b030d77dba9
|
[
"Apache-2.0"
] | 249 |
2017-09-18T17:48:34.000Z
|
2022-02-02T06:46:21.000Z
|
third_party/android/platform-libcore/android-platform-libcore/support/src/test/java/tests/support/Support_Locale.java
|
phaezah7/openweave-core
|
88d8eaef62769bd567c7684a5f137b030d77dba9
|
[
"Apache-2.0"
] | 501 |
2017-11-10T11:25:32.000Z
|
2022-02-01T10:43:13.000Z
|
third_party/android/platform-libcore/android-platform-libcore/support/src/test/java/tests/support/Support_Locale.java
|
phaezah7/openweave-core
|
88d8eaef62769bd567c7684a5f137b030d77dba9
|
[
"Apache-2.0"
] | 116 |
2017-09-20T07:06:55.000Z
|
2022-01-08T13:41:15.000Z
| 34.333333 | 85 | 0.700243 | 1,002,266 |
/*
* 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 tests.support;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* Helper class for {@link Locale} tests
*/
public class Support_Locale {
/**
* Helper method to determine if given locales are available.
*
* @param requiredLocales - the set of {@link Locale} to check
*
* @return true if all requiredLocales are available.
*/
public static boolean areLocalesAvailable(Locale... requiredLocales) {
Locale[] availableLocales = Locale.getAvailableLocales();
Set<Locale> localeSet = new HashSet<Locale>(Arrays.asList(availableLocales));
for (Locale requiredLocale : requiredLocales) {
if (!localeSet.contains(requiredLocale)) {
return false;
}
}
return true;
}
}
|
92426f377c9dc999c6a00cd989a775c0dbf2fadf
| 9,516 |
java
|
Java
|
espresso/core/java/androidx/test/espresso/base/Interrogator.java
|
dayanruben/android-test
|
2ed50d534cb7e48433dcfa5f5e9e793e99506d84
|
[
"Apache-2.0"
] | 836 |
2018-05-20T23:00:12.000Z
|
2022-03-29T09:53:59.000Z
|
espresso/core/java/androidx/test/espresso/base/Interrogator.java
|
dayanruben/android-test
|
2ed50d534cb7e48433dcfa5f5e9e793e99506d84
|
[
"Apache-2.0"
] | 602 |
2018-06-29T04:44:44.000Z
|
2022-03-30T19:13:09.000Z
|
espresso/core/java/androidx/test/espresso/base/Interrogator.java
|
dayanruben/android-test
|
2ed50d534cb7e48433dcfa5f5e9e793e99506d84
|
[
"Apache-2.0"
] | 233 |
2018-05-21T19:51:09.000Z
|
2022-03-23T17:01:25.000Z
| 34.230216 | 100 | 0.653741 | 1,002,267 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 androidx.test.espresso.base;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfUnchecked;
import android.os.Binder;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.util.Log;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/** Isolates the nasty details of touching the message queue. */
final class Interrogator {
private static final String TAG = "Interrogator";
private static final Method messageQueueNextMethod;
private static final Field messageQueueHeadField;
private static final Method recycleUncheckedMethod;
private static final int LOOKAHEAD_MILLIS = 15;
private static final ThreadLocal<Boolean> interrogating =
new ThreadLocal<Boolean>() {
@Override
public Boolean initialValue() {
return Boolean.FALSE;
}
};
static {
try {
messageQueueNextMethod = MessageQueue.class.getDeclaredMethod("next");
messageQueueNextMethod.setAccessible(true);
messageQueueHeadField = MessageQueue.class.getDeclaredField("mMessages");
messageQueueHeadField.setAccessible(true);
} catch (IllegalArgumentException
| NoSuchFieldException
| SecurityException
| NoSuchMethodException e) {
Log.e(TAG, "Could not initialize interrogator!", e);
throw new RuntimeException("Could not initialize interrogator!", e);
}
Method recycleUnchecked = null;
try {
recycleUnchecked = Message.class.getDeclaredMethod("recycleUnchecked");
recycleUnchecked.setAccessible(true);
} catch (NoSuchMethodException expectedOnLowerApiLevels) {
}
recycleUncheckedMethod = recycleUnchecked;
}
/** Informed of the state of the queue and controls whether to continue interrogation or quit. */
interface QueueInterrogationHandler<R> {
/**
* called when the queue is empty
*
* @return true to continue interrogating, false otherwise.
*/
public boolean queueEmpty();
/**
* called when the next task on the queue will be executed soon.
*
* @return true to continue interrogating, false otherwise.
*/
public boolean taskDueSoon();
/**
* called when the next task on the queue will be executed in a long time.
*
* @return true to continue interrogating, false otherwise.
*/
public boolean taskDueLong();
/** Called when a barrier has been detected. */
public boolean barrierUp();
/** Called after interrogation has requested to end. */
public R get();
}
/**
* Informed of the state of the looper/queue and controls whether to continue interrogation or
* quit.
*/
interface InterrogationHandler<R> extends QueueInterrogationHandler<R> {
/**
* Notifies that the queue is about to dispatch a task.
*
* @return true to continue interrogating, false otherwise. execution happens regardless.
*/
public boolean beforeTaskDispatch();
/** Called when the looper / message queue being interrogated is about to quit. */
public void quitting();
public void setMessage(Message m);
public String getMessage();
}
/**
* Loops the main thread and informs the interrogation handler at interesting points in the exec
* state.
*
* @param handler an interrogation handler that controls whether to continue looping or not.
*/
static <R> R loopAndInterrogate(InterrogationHandler<R> handler) {
checkSanity();
interrogating.set(Boolean.TRUE);
boolean stillInterested = true;
MessageQueue q = Looper.myQueue();
// We may have an identity when we're called - we want to restore it at the end of the fn.
final long entryIdentity = Binder.clearCallingIdentity();
try {
// this identity should not get changed by dispatching the loop until the observer is happy.
final long threadIdentity = Binder.clearCallingIdentity();
while (stillInterested) {
// run until the observer is no longer interested.
stillInterested = interrogateQueueState(q, handler);
if (stillInterested) {
Message m = getNextMessage();
// the observer cannot stop us from dispatching this message - but we need to let it know
// that we're about to dispatch.
if (null == m) {
handler.quitting();
return handler.get();
}
stillInterested = handler.beforeTaskDispatch();
handler.setMessage(m);
m.getTarget().dispatchMessage(m);
// ensure looper invariants
final long newIdentity = Binder.clearCallingIdentity();
// Detect binder id corruption.
if (newIdentity != threadIdentity) {
Log.wtf(
TAG,
"Thread identity changed from 0x"
+ Long.toHexString(threadIdentity)
+ " to 0x"
+ Long.toHexString(newIdentity)
+ " while dispatching to "
+ m.getTarget().getClass().getName()
+ " "
+ m.getCallback()
+ " what="
+ m.what);
}
recycle(m);
}
}
} finally {
Binder.restoreCallingIdentity(entryIdentity);
interrogating.set(Boolean.FALSE);
}
return handler.get();
}
private static void recycle(Message m) {
if (recycleUncheckedMethod != null) {
try {
recycleUncheckedMethod.invoke(m);
} catch (IllegalAccessException | IllegalArgumentException | SecurityException e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
} catch (InvocationTargetException ite) {
if (ite.getCause() != null) {
throwIfUnchecked(ite.getCause());
throw new RuntimeException(ite.getCause());
} else {
throw new RuntimeException(ite);
}
}
} else {
m.recycle();
}
}
private static Message getNextMessage() {
try {
return (Message) messageQueueNextMethod.invoke(Looper.myQueue());
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException
| SecurityException e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
/**
* Allows caller to see if the message queue is empty, has a task due soon / long, or has a
* barrier.
*
* <p>This method can be called from any thread. It has limitations though - if a task is
* currently being executed in the interrogation loop, you will not know about it. If the Looper
* is quitting you will not know about it. You can only see the state of the message queue - which
* is seperate from the state of the overall loop.
*
* @param q the message queue you wish to inspect
* @param handler a callback that will have one of the following methods invoked on it:
* queueEmpty(), taskDueSoon(), taskDueLong() or barrierUp(). once and only once.
* @return the result of handler.get()
*/
static <R> R peekAtQueueState(MessageQueue q, QueueInterrogationHandler<R> handler) {
checkNotNull(q);
checkNotNull(handler);
checkState(
!interrogateQueueState(q, handler),
"It is expected that %s would stop interrogation after a single peak at the queue.",
handler);
return handler.get();
}
private static boolean interrogateQueueState(
MessageQueue q, QueueInterrogationHandler<?> handler) {
synchronized (q) {
final Message head;
try {
head = (Message) messageQueueHeadField.get(q);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (null == head) {
// no messages pending - AT ALL!
return handler.queueEmpty();
} else if (null == head.getTarget()) {
// null target is a sync barrier token.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "barrier is up");
}
return handler.barrierUp();
}
long headWhen = head.getWhen();
long nowFuz = SystemClock.uptimeMillis() + LOOKAHEAD_MILLIS;
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(
TAG,
"headWhen: " + headWhen + " nowFuz: " + nowFuz + " due long: " + (nowFuz < headWhen));
}
if (nowFuz > headWhen) {
return handler.taskDueSoon();
}
return handler.taskDueLong();
}
}
private static void checkSanity() {
checkState(Looper.myLooper() != null, "Calling non-looper thread!");
checkState(Boolean.FALSE.equals(interrogating.get()), "Already interrogating!");
}
}
|
9242702a9d403ed6eb3128f6baf4d865173d409e
| 4,336 |
java
|
Java
|
ql/src/java/org/apache/hadoop/hive/ql/exec/vector/mapjoin/optimized/VectorMapJoinOptimizedHashMap.java
|
richox/hive
|
5ec4b7df59a5f011560b24100beb0e590a15d692
|
[
"Apache-2.0"
] | 28 |
2020-03-07T04:05:27.000Z
|
2022-03-25T07:44:51.000Z
|
ql/src/java/org/apache/hadoop/hive/ql/exec/vector/mapjoin/optimized/VectorMapJoinOptimizedHashMap.java
|
richox/hive
|
5ec4b7df59a5f011560b24100beb0e590a15d692
|
[
"Apache-2.0"
] | 67 |
2018-12-20T07:32:49.000Z
|
2021-08-02T16:57:54.000Z
|
ql/src/java/org/apache/hadoop/hive/ql/exec/vector/mapjoin/optimized/VectorMapJoinOptimizedHashMap.java
|
richox/hive
|
5ec4b7df59a5f011560b24100beb0e590a15d692
|
[
"Apache-2.0"
] | 18 |
2021-01-08T07:26:59.000Z
|
2022-02-14T02:11:18.000Z
| 33.612403 | 111 | 0.728552 | 1,002,268 |
/*
* 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.hadoop.hive.ql.exec.vector.mapjoin.optimized;
import java.io.IOException;
import org.apache.hadoop.hive.ql.exec.JoinUtil;
import org.apache.hadoop.hive.ql.exec.persistence.BytesBytesMultiHashMap;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainer.ReusableGetAdaptor;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinBytesHashMap;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashMapResult;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashTableResult;
import org.apache.hadoop.hive.serde2.WriteBuffers.ByteSegmentRef;
public class VectorMapJoinOptimizedHashMap
extends VectorMapJoinOptimizedHashTable
implements VectorMapJoinBytesHashMap {
@Override
public VectorMapJoinHashMapResult createHashMapResult() {
return new HashMapResult();
}
public static class HashMapResult extends VectorMapJoinHashMapResult {
private BytesBytesMultiHashMap.Result bytesBytesMultiHashMapResult;
public HashMapResult() {
super();
bytesBytesMultiHashMapResult = new BytesBytesMultiHashMap.Result();
}
public BytesBytesMultiHashMap.Result bytesBytesMultiHashMapResult() {
return bytesBytesMultiHashMapResult;
}
@Override
public boolean hasRows() {
return (joinResult() == JoinUtil.JoinResult.MATCH);
}
@Override
public boolean isSingleRow() {
if (joinResult() != JoinUtil.JoinResult.MATCH) {
throw new RuntimeException("HashMapResult is not a match");
}
return bytesBytesMultiHashMapResult.isSingleRow();
}
@Override
public boolean isCappedCountAvailable() {
return true;
}
@Override
public int cappedCount() {
// the return values are capped to return ==0, ==1 and >= 2
return hasRows() ? (isSingleRow() ? 1 : 2) : 0;
}
@Override
public ByteSegmentRef first() {
if (joinResult() != JoinUtil.JoinResult.MATCH) {
throw new RuntimeException("HashMapResult is not a match");
}
return bytesBytesMultiHashMapResult.first();
}
@Override
public ByteSegmentRef next() {
return bytesBytesMultiHashMapResult.next();
}
@Override
public void forget() {
bytesBytesMultiHashMapResult.forget();
super.forget();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(" + super.toString() + ", ");
sb.append("isSingleRow " + (joinResult() == JoinUtil.JoinResult.MATCH ? isSingleRow() : "<none>") + ")");
return sb.toString();
}
@Override
public String getDetailedHashMapResultPositionString() {
return "(Not supported yet)";
}
}
@Override
public JoinUtil.JoinResult lookup(byte[] keyBytes, int keyOffset, int keyLength,
VectorMapJoinHashMapResult hashMapResult) throws IOException {
HashMapResult implementationHashMapResult = (HashMapResult) hashMapResult;
JoinUtil.JoinResult joinResult =
doLookup(keyBytes, keyOffset, keyLength,
implementationHashMapResult.bytesBytesMultiHashMapResult(),
(VectorMapJoinHashTableResult) hashMapResult);
return joinResult;
}
public VectorMapJoinOptimizedHashMap(
MapJoinTableContainer originalTableContainer, ReusableGetAdaptor hashMapRowGetter) {
super(originalTableContainer, hashMapRowGetter);
}
}
|
924270483012a325a1e1a1e54b99e8ab12c66f6e
| 2,560 |
java
|
Java
|
src/main/java/org/smoothbuild/exec/compute/IfTask.java
|
mikosik/smooth-build
|
b7ae7b38a91b21d0f4e45be3f352547daa5fbbcd
|
[
"Apache-2.0"
] | 8 |
2015-01-30T10:21:32.000Z
|
2022-02-22T21:32:35.000Z
|
src/main/java/org/smoothbuild/exec/compute/IfTask.java
|
mikosik/smooth-build
|
b7ae7b38a91b21d0f4e45be3f352547daa5fbbcd
|
[
"Apache-2.0"
] | 109 |
2015-01-06T16:41:02.000Z
|
2022-01-28T12:36:17.000Z
|
src/main/java/org/smoothbuild/exec/compute/IfTask.java
|
mikosik/smooth-build
|
b7ae7b38a91b21d0f4e45be3f352547daa5fbbcd
|
[
"Apache-2.0"
] | 1 |
2015-11-29T07:43:43.000Z
|
2015-11-29T07:43:43.000Z
| 36.056338 | 96 | 0.757813 | 1,002,269 |
package org.smoothbuild.exec.compute;
import static org.smoothbuild.exec.base.Input.input;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.smoothbuild.db.record.base.Bool;
import org.smoothbuild.db.record.base.Record;
import org.smoothbuild.exec.algorithm.Algorithm;
import org.smoothbuild.exec.base.Input;
import org.smoothbuild.exec.parallel.ParallelTaskExecutor.Worker;
import org.smoothbuild.lang.base.Location;
import org.smoothbuild.lang.base.type.ConcreteType;
import org.smoothbuild.util.concurrent.Feeder;
import org.smoothbuild.util.concurrent.FeedingConsumer;
import com.google.common.collect.ImmutableList;
public class IfTask extends ComputableTask {
public static final String IF_FUNCTION_NAME = "if";
public IfTask(ConcreteType type, Algorithm algorithm, List<? extends Task> dependencies,
Location location, boolean cacheable) {
super(TaskKind.CALL, type, IF_FUNCTION_NAME, algorithm, dependencies, location, cacheable);
}
@Override
public Feeder<Record> startComputation(Worker worker) {
FeedingConsumer<Record> ifResult = new FeedingConsumer<>();
Feeder<Record> conditionResult = conditionTask().startComputation(worker);
Consumer<Record> ifEnqueuer = ifEnqueuer(worker, ifResult, conditionResult);
Consumer<Record> thenOrElseEnqueuer = thenOrElseEnqueuer(worker, ifEnqueuer);
conditionResult.addConsumer(thenOrElseEnqueuer);
return ifResult;
}
private Consumer<Record> thenOrElseEnqueuer(Worker worker, Consumer<Record> ifEnqueuer) {
return conditionValue -> {
boolean condition = ((Bool) conditionValue).jValue();
Task thenOrElseTask = condition ? thenTask() : elseTask();
thenOrElseTask.startComputation(worker).addConsumer(ifEnqueuer);
};
}
private Consumer<Record> ifEnqueuer(Worker worker, Consumer<Record> ifResultConsumer,
Supplier<Record> conditionResult) {
return thenOrElseResult -> {
Record conditionValue = conditionResult.get();
// Only one of then/else values will be used and it will be used twice.
// This way TaskExecutor can calculate task hash and use it for caching.
Input input = input(ImmutableList.of(conditionValue, thenOrElseResult, thenOrElseResult));
worker.enqueueComputation(this, input, ifResultConsumer);
};
}
private Task conditionTask() {
return dependencies().get(0);
}
private Task thenTask() {
return dependencies().get(1);
}
private Task elseTask() {
return dependencies().get(2);
}
}
|
9242715930c342895e28db6600fea881477587c8
| 720 |
java
|
Java
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactDeletionTests.java
|
Bughuntress/Java_course
|
dea944c3518b7338bf87b9d3d1f4737632b38d10
|
[
"Apache-2.0"
] | null | null | null |
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactDeletionTests.java
|
Bughuntress/Java_course
|
dea944c3518b7338bf87b9d3d1f4737632b38d10
|
[
"Apache-2.0"
] | null | null | null |
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactDeletionTests.java
|
Bughuntress/Java_course
|
dea944c3518b7338bf87b9d3d1f4737632b38d10
|
[
"Apache-2.0"
] | null | null | null | 32.727273 | 238 | 0.738889 | 1,002,270 |
package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
public class ContactDeletionTests1 extends TestBase {
@Test
public void testContactDeletion() {
app.getNavigationHelper().gotoContactPage();
if (!app.getContactHelper().ThereisAContact()){
app.getContactHelper().createContact(new ContactData(null, "Джейсон", "Красавица", "Красавица и Чудовище", "Диснейлэнд", "1, Заколдованный Замок, Волшебный Лес", "+22222222", "22, Дом Отца, Маленькая деревушка", "Сказочные герои"));
}
app.getContactHelper().selectContact();
app.getContactHelper().selectedDeleteContact();
app.getContactHelper().closePopup();
}
}
|
924272de05f7617fdd443ce0800b71305e06ec34
| 413 |
java
|
Java
|
src/main/java/pe/edu/upc/service/IUploadFileService.java
|
GigiSagastegui/TrabajoFinal
|
5c20aa3250a36d9c8481727cb05a470176c3f534
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/pe/edu/upc/service/IUploadFileService.java
|
GigiSagastegui/TrabajoFinal
|
5c20aa3250a36d9c8481727cb05a470176c3f534
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/pe/edu/upc/service/IUploadFileService.java
|
GigiSagastegui/TrabajoFinal
|
5c20aa3250a36d9c8481727cb05a470176c3f534
|
[
"Apache-2.0"
] | null | null | null | 22.944444 | 68 | 0.825666 | 1,002,271 |
package pe.edu.upc.service;
import java.io.IOException;
import java.net.MalformedURLException;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
public interface IUploadFileService {
public Resource load(String filename) throws MalformedURLException;
public String copy(MultipartFile file) throws IOException;
public boolean delete(String filename);
}
|
9242730580613aeb80039bc82bf1188c929f6d74
| 2,987 |
java
|
Java
|
tlg_gtk/src/main/java/ch/bailu/tlg_gtk/BaseContext.java
|
bailuk/TLG
|
37553806dfa75ccb049a7e0ed15ac43b17dc6282
|
[
"CC-BY-4.0"
] | 1 |
2018-09-13T18:19:17.000Z
|
2018-09-13T18:19:17.000Z
|
tlg_gtk/src/main/java/ch/bailu/tlg_gtk/BaseContext.java
|
bailuk/TLG
|
37553806dfa75ccb049a7e0ed15ac43b17dc6282
|
[
"CC-BY-4.0"
] | null | null | null |
tlg_gtk/src/main/java/ch/bailu/tlg_gtk/BaseContext.java
|
bailuk/TLG
|
37553806dfa75ccb049a7e0ed15ac43b17dc6282
|
[
"CC-BY-4.0"
] | null | null | null | 22.458647 | 92 | 0.606294 | 1,002,272 |
package ch.bailu.tlg_gtk;
import ch.bailu.gtk.gdk.RGBA;
import ch.bailu.tlg.PlatformContext;
import ch.bailu.tlg.StateRunning;
import ch.bailu.tlg.TlgPoint;
import ch.bailu.tlg.TlgRectangle;
public class BaseContext extends PlatformContext {
private static final int PALETTE_RESERVED=5;
private static final int PALETTE_SIZE=(StateRunning.SHAPE_PER_LEVEL*3)+PALETTE_RESERVED;
private static final int COLOR_GRID=PALETTE_SIZE-PALETTE_RESERVED-1;
private static final int COLOR_BACKGROUND=COLOR_GRID+1;
private static final int COLOR_HIGHLIGHT=COLOR_GRID+2;
private static final int COLOR_DARK=COLOR_GRID+3;
private static final int COLOR_FRAME=COLOR_GRID+4;
private static final int COLOR_GRAYED=COLOR_GRID+5;
private static RGBA palette[] = null;
public BaseContext() {
if (palette == null) {
initPalette();
}
}
private void initPalette() {
float h=0f;
palette=new RGBA[PALETTE_SIZE];
for (int i=0; i< (PALETTE_SIZE - PALETTE_RESERVED); i++) {
float[] rgb = ColorHelper.HSVtoRGB(h, 1f, 1f);
palette[i]=newColor(rgb[0], rgb[1], rgb[2]);
h++;
h%=6;
}
double x=1d/256d;
palette[COLOR_GRID]=newColor(x*44,x*67,x*77);
palette[COLOR_FRAME]=newColor(x*44,x*109,x*205);
palette[COLOR_BACKGROUND]=newColor(x*10,x*10,x*10);
palette[COLOR_HIGHLIGHT]=newColor(1,1,1);
palette[COLOR_DARK]=newColor(0,0,0);
palette[COLOR_GRAYED]=newColor(x*208,x*208,x*208);
}
private RGBA newColor(double r, double g, double b) {
RGBA result = new RGBA();
result.setFieldRed(r);
result.setFieldGreen(g);
result.setFieldBlue(b);
result.setFieldAlpha(1);
return result;
}
public RGBA getGtkColor(int color) {
return palette[color];
}
@Override
public void drawLine(int color, TlgPoint p1, TlgPoint p2) {
}
@Override
public void drawFilledRectangle(int color, TlgRectangle rect) {
}
@Override
public void drawText(int color, TlgRectangle rect, String text) {
}
@Override
public int colorBackground() {
return COLOR_BACKGROUND;
}
@Override
public int colorDark() {
return COLOR_DARK;
}
@Override
public int colorHighlight() {
return COLOR_HIGHLIGHT;
}
@Override
public int colorGrayed() {
return COLOR_GRAYED;
}
@Override
public int colorFrame() {
return COLOR_FRAME;
}
@Override
public int colorGrid() {
return COLOR_GRID;
}
@Override
public int countOfColor() {
return PALETTE_SIZE;
}
@Override
public int getColor(int i) {
return i;
}
@Override
public void onNewHighscore() {
}
}
|
924273181b26ece0dfadda243b6d0ae780e83ee6
| 879 |
java
|
Java
|
src/java/model/entity/Author.java
|
Charlene19/BookShopWeb
|
4778114b260a6b2294a4c145bf001d0c30f56ca7
|
[
"Unlicense",
"MIT"
] | 2 |
2020-09-26T11:42:24.000Z
|
2020-09-26T11:43:08.000Z
|
src/java/model/entity/Author.java
|
Charlene19/BookShopWeb
|
4778114b260a6b2294a4c145bf001d0c30f56ca7
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/java/model/entity/Author.java
|
Charlene19/BookShopWeb
|
4778114b260a6b2294a4c145bf001d0c30f56ca7
|
[
"Unlicense",
"MIT"
] | 1 |
2020-09-27T15:44:06.000Z
|
2020-09-27T15:44:06.000Z
| 16.277778 | 48 | 0.569966 | 1,002,273 |
package model.entity;
/**
*
* @author zvr
*/
public class Author {
private int id;
private String firstName;
private String lastName;
private String postIt;
public Author(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPostIt() {
return postIt;
}
public void setPostIt(String postIt) {
this.postIt = postIt;
}
@Override
public String toString() {
return firstName+" "+lastName;
}
}
|
9242734444a2b9ec6046dd7208a4fb3b9b9ca8f6
| 1,183 |
java
|
Java
|
Source/Plugins/Core/com.equella.core/src/com/tle/web/contentrestrictions/ContentRestrictionsModule.java
|
infiniticg/equella
|
75ddd69bca3a94e213705dcfe90cf7077cc89872
|
[
"Apache-2.0"
] | 1 |
2018-07-25T02:34:16.000Z
|
2018-07-25T02:34:16.000Z
|
Source/Plugins/Core/com.equella.core/src/com/tle/web/contentrestrictions/ContentRestrictionsModule.java
|
infiniticg/equella
|
75ddd69bca3a94e213705dcfe90cf7077cc89872
|
[
"Apache-2.0"
] | null | null | null |
Source/Plugins/Core/com.equella.core/src/com/tle/web/contentrestrictions/ContentRestrictionsModule.java
|
infiniticg/equella
|
75ddd69bca3a94e213705dcfe90cf7077cc89872
|
[
"Apache-2.0"
] | 1 |
2018-04-11T20:31:51.000Z
|
2018-04-11T20:31:51.000Z
| 26.886364 | 90 | 0.759932 | 1,002,274 |
/*
* Copyright 2017 Apereo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.contentrestrictions;
import com.google.inject.name.Names;
import com.tle.web.sections.equella.guice.SectionsModule;
/**
* @author larry
*/
public class ContentRestrictionsModule extends SectionsModule
{
@Override
protected void configure()
{
bind(Object.class).annotatedWith(Names.named("/access/contentrestrictions")).toProvider(
contentRestrictionsTree());
}
private NodeProvider contentRestrictionsTree()
{
NodeProvider node = node(RootContentRestrictionsSection.class);
node.innerChild(EditContentRestrictionsSection.class);
return node;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.