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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e05f83322f4792408154c8a609cf64b150e7075
| 1,547 |
java
|
Java
|
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/providers/IssuersProviderImpl.java
|
serguei-ml/px-android
|
39a671eab63079c1bdd9ff7f53d96b1d3d2a4681
|
[
"MIT"
] | 1 |
2018-09-12T05:39:00.000Z
|
2018-09-12T05:39:00.000Z
|
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/providers/IssuersProviderImpl.java
|
serguei-ml/px-android
|
39a671eab63079c1bdd9ff7f53d96b1d3d2a4681
|
[
"MIT"
] | null | null | null |
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/providers/IssuersProviderImpl.java
|
serguei-ml/px-android
|
39a671eab63079c1bdd9ff7f53d96b1d3d2a4681
|
[
"MIT"
] | null | null | null | 34.377778 | 115 | 0.77117 | 2,515 |
package com.mercadopago.android.px.internal.features.providers;
import android.content.Context;
import android.support.annotation.NonNull;
import com.mercadopago.android.px.R;
import com.mercadopago.android.px.internal.datasource.MercadoPagoServicesAdapter;
import com.mercadopago.android.px.internal.callbacks.TaggedCallback;
import com.mercadopago.android.px.internal.di.Session;
import com.mercadopago.android.px.model.Issuer;
import com.mercadopago.android.px.model.exceptions.MercadoPagoError;
import java.util.List;
/**
* Created by mromar on 4/26/17.
*/
public class IssuersProviderImpl implements IssuersProvider {
private final Context context;
private final MercadoPagoServicesAdapter mercadoPago;
public IssuersProviderImpl(@NonNull final Context context) {
this.context = context;
mercadoPago = Session.getSession(context).getMercadoPagoServiceAdapter();
}
@Override
public void getIssuers(String paymentMethodId, String bin, final TaggedCallback<List<Issuer>> taggedCallback) {
mercadoPago.getIssuers(paymentMethodId, bin, taggedCallback);
}
@Override
public MercadoPagoError getEmptyIssuersError() {
String message = context.getString(R.string.px_standard_error_message);
String detail = context.getString(R.string.px_error_message_detail_issuers);
return new MercadoPagoError(message, detail, false);
}
@Override
public String getCardIssuersTitle() {
return context.getString(R.string.px_card_issuers_title);
}
}
|
3e05f8b05ce08190a43964c081a2f57bd47e3b89
| 2,844 |
java
|
Java
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/Ring.java
|
XAXB75/Settings.java
|
2e0b192d85121368b826db551f10e9dc9490abfa
|
[
"MIT"
] | null | null | null |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/Ring.java
|
XAXB75/Settings.java
|
2e0b192d85121368b826db551f10e9dc9490abfa
|
[
"MIT"
] | null | null | null |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/Ring.java
|
XAXB75/Settings.java
|
2e0b192d85121368b826db551f10e9dc9490abfa
|
[
"MIT"
] | null | null | null | 30.255319 | 126 | 0.528481 | 2,516 |
package org.firstinspires.ftc.teamcode.util;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import java.util.Objects;
public class Ring {
private final Position position;
private final Point downMost;
private final String ringCase;
private final int left, right, top, bottom;
public Ring(int left, int right, int up, int down, Point downMost) {
this.left = left;
this.right = right;
this.top = up;
this.bottom = down;
this.downMost = downMost;
double x = downMost.x;
double y = downMost.y;
this.position = new Position((-0.105027791 * x -0.011669755 * y + 18.81747929)/(0.000413387 * x -0.013068208 * y + 1),
(-0.054849212 * x -0.061229618 * y -10.49356972)/(-0.000764579 * x -0.009489632
* y + 1));
if (1.0 * (right - left) / (down - up) > 1.5) this.ringCase = "Single";
else this.ringCase = "Quad";
}
public void drawFrame(Mat mat) {
Imgproc.rectangle(mat,
new Point(left - 1, top - 1),
new Point(right + 1, bottom + 1),
new Scalar(Color.GREEN.toChannel4()),
2,
8,
0 );
Imgproc.rectangle(mat,
new Point(downMost.x - 1, downMost.y - 1),
new Point(downMost.x + 1, downMost.y + 1),
new Scalar(Color.GREEN.toChannel4()),
1,
8,
0 );
Imgproc.putText(mat,
getRingCase(),
new Point(left - 3, bottom + 15),
Imgproc.FONT_HERSHEY_COMPLEX,
0.5,
new Scalar(Color.GREEN.toChannel4()));
}
public double getDistance() {
return new Position().getDistance(position);
}
public Position getRelativePosition() {
return position;
}
public int getWidth() {
return right - left;
}
public int getHeight() {
return bottom - top;
}
public double getRatio() {
return 1.0 * getWidth() / getHeight();
}
public String getRingCase() {
return ringCase;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Ring ring = (Ring) obj;
return left == ring.left &&
right == ring.right &&
top == ring.top &&
bottom == ring.bottom;
}
@Override
public int hashCode() {
return Objects.hash(left, right, top, bottom);
}
@Override
public String toString() {
return "Ring " + ringCase + " at (" + position.x + ", " + position.y + ")";
}
}
|
3e05f930f22b8c996cfb25609b9ec05e7acdfecf
| 1,323 |
java
|
Java
|
src/io/github/azewilous/folderchange/FolderHandler.java
|
Azewilous/UserFolderChange
|
1442d6cdecba295300b02aa6b4d38f7f030e9310
|
[
"MIT"
] | null | null | null |
src/io/github/azewilous/folderchange/FolderHandler.java
|
Azewilous/UserFolderChange
|
1442d6cdecba295300b02aa6b4d38f7f030e9310
|
[
"MIT"
] | null | null | null |
src/io/github/azewilous/folderchange/FolderHandler.java
|
Azewilous/UserFolderChange
|
1442d6cdecba295300b02aa6b4d38f7f030e9310
|
[
"MIT"
] | null | null | null | 28.76087 | 86 | 0.515495 | 2,517 |
package io.github.azewilous.folderchange;
import java.io.File;
/**
* Created on 3/2/2017.
*/
public class FolderHandler {
static boolean running = false;
public static void handleFolderNameChange(String path, String name) {
running = true;
String oldPath = path;
if (path.contains("\\")) {
String separator = "\\";
int index = path.lastIndexOf(separator);
String folder = path.substring(index);
path = path.replace(folder, "\\" + name);
File file = new File(oldPath);
if (file.exists()) {
boolean result = file.renameTo(new File(path));
if (result) {
System.out.println("Folder successfully renamed");
} else {
System.out.println("Error... folder was not renamed.");
}
} else {
System.out.println("The specified path does not exist");
}
System.out.println("Path changed from -> " + oldPath + " to -> " + path);
} else {
path = name;
System.out.println("Path changed from -> " + oldPath + " to -> " + path);
}
running = false;
}
public static boolean isRunning() {
return running;
}
}
|
3e05f99670f725cc9d9d55309df431da04ce3062
| 27,083 |
java
|
Java
|
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
|
lvheyang/orientdb
|
f3eff9bac0a83ad852934f9e15f32bf30f436569
|
[
"Apache-2.0"
] | 1 |
2019-01-26T04:19:01.000Z
|
2019-01-26T04:19:01.000Z
|
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
|
lvheyang/orientdb
|
f3eff9bac0a83ad852934f9e15f32bf30f436569
|
[
"Apache-2.0"
] | null | null | null |
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
|
lvheyang/orientdb
|
f3eff9bac0a83ad852934f9e15f32bf30f436569
|
[
"Apache-2.0"
] | null | null | null | 43.682258 | 142 | 0.607872 | 2,518 |
/*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* 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.orientechnologies.orient.core.serialization.serializer.record.string;
import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;
import java.util.*;
import com.orientechnologies.common.parser.OStringParser;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.record.ORecordLazyList;
import com.orientechnologies.orient.core.db.record.ORecordLazyMultiValue;
import com.orientechnologies.orient.core.db.record.OTrackedList;
import com.orientechnologies.orient.core.db.record.OTrackedSet;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.fetch.OFetchHelper;
import com.orientechnologies.orient.core.fetch.json.OJSONFetchContext;
import com.orientechnologies.orient.core.fetch.json.OJSONFetchListener;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.ORecordStringable;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;
import com.orientechnologies.orient.core.util.ODateHelper;
import com.orientechnologies.orient.core.version.ODistributedVersion;
@SuppressWarnings("serial")
public class ORecordSerializerJSON extends ORecordSerializerStringAbstract {
public static final String NAME = "json";
public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON();
public static final String ATTRIBUTE_FIELD_TYPES = "@fieldTypes";
public static final char[] PARAMETER_SEPARATOR = new char[] { ':', ',' };
private static final Long MAX_INT = new Long(Integer.MAX_VALUE);
private static final Long MIN_INT = new Long(Integer.MIN_VALUE);
private static final Double MAX_FLOAT = new Double(Float.MAX_VALUE);
private static final Double MIN_FLOAT = new Double(Float.MIN_VALUE);
public class FormatSettings {
public boolean includeVer;
public boolean includeType;
public boolean includeId;
public boolean includeClazz;
public boolean attribSameRow;
public boolean alwaysFetchEmbeddedDocuments;
public int indentLevel;
public String fetchPlan = null;
public boolean keepTypes = true;
public boolean dateAsLong = false;
public boolean prettyPrint = false;
public FormatSettings(final String iFormat) {
if (iFormat == null) {
includeType = true;
includeVer = true;
includeId = true;
includeClazz = true;
attribSameRow = true;
indentLevel = 1;
fetchPlan = "";
keepTypes = true;
alwaysFetchEmbeddedDocuments = true;
} else {
includeType = false;
includeVer = false;
includeId = false;
includeClazz = false;
attribSameRow = false;
alwaysFetchEmbeddedDocuments = false;
indentLevel = 1;
keepTypes = false;
final String[] format = iFormat.split(",");
for (String f : format)
if (f.equals("type"))
includeType = true;
else if (f.equals("rid"))
includeId = true;
else if (f.equals("version"))
includeVer = true;
else if (f.equals("class"))
includeClazz = true;
else if (f.equals("attribSameRow"))
attribSameRow = true;
else if (f.startsWith("indent"))
indentLevel = Integer.parseInt(f.substring(f.indexOf(':') + 1));
else if (f.startsWith("fetchPlan"))
fetchPlan = f.substring(f.indexOf(':') + 1);
else if (f.startsWith("keepTypes"))
keepTypes = true;
else if (f.startsWith("alwaysFetchEmbedded"))
alwaysFetchEmbeddedDocuments = true;
else if (f.startsWith("dateAsLong"))
dateAsLong = true;
else if (f.startsWith("prettyPrint"))
prettyPrint = true;
}
}
}
public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields, boolean needReload) {
return fromString(iSource, iRecord, iFields, null, needReload);
}
@Override
public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields) {
return fromString(iSource, iRecord, iFields, null, false);
}
public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields, final String iOptions,
boolean needReload) {
if (iSource == null)
throw new OSerializationException("Error on unmarshalling JSON content: content is null");
iSource = iSource.trim();
if (!iSource.startsWith("{") || !iSource.endsWith("}"))
throw new OSerializationException("Error on unmarshalling JSON content: content must be between { }");
if (iRecord != null)
// RESET ALL THE FIELDS
iRecord.clear();
iSource = iSource.substring(1, iSource.length() - 1).trim();
// PARSE OPTIONS
boolean noMap = false;
if (iOptions != null) {
final String[] format = iOptions.split(",");
for (String f : format)
if (f.equals("noMap"))
noMap = true;
}
final List<String> fields = OStringSerializerHelper.smartSplit(iSource, PARAMETER_SEPARATOR, 0, -1, true, true, false, ' ',
'\n', '\r', '\t');
if (fields.size() % 2 != 0)
throw new OSerializationException("Error on unmarshalling JSON content: wrong format. Use <field> : <value>");
Map<String, Character> fieldTypes = null;
if (fields != null && fields.size() > 0) {
// SEARCH FOR FIELD TYPES IF ANY
for (int i = 0; i < fields.size(); i += 2) {
final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i));
final String fieldValue = fields.get(i + 1);
final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue);
if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) {
// LOAD THE FIELD TYPE MAP
final String[] fieldTypesParts = fieldValueAsString.split(",");
if (fieldTypesParts.length > 0) {
fieldTypes = new HashMap<String, Character>();
String[] part;
for (String f : fieldTypesParts) {
part = f.split("=");
if (part.length == 2)
fieldTypes.put(part[0], part[1].charAt(0));
}
}
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
if (iRecord == null || iRecord.getRecordType() != fieldValueAsString.charAt(0)) {
// CREATE THE RIGHT RECORD INSTANCE
iRecord = Orient.instance().getRecordFactoryManager().newInstance((byte) fieldValueAsString.charAt(0));
}
} else if (needReload && fieldName.equals(ODocumentHelper.ATTRIBUTE_RID) && iRecord instanceof ODocument) {
if (fieldValue != null && fieldValue.length() > 0) {
ORecordInternal<?> localRecord = ODatabaseRecordThreadLocal.INSTANCE.get().load(new ORecordId(fieldValueAsString));
if (localRecord != null)
iRecord = localRecord;
}
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_CLASS) && iRecord instanceof ODocument) {
((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString);
}
}
try {
int recordVersion = 0;
long timestamp = 0L;
long macAddress = 0L;
for (int i = 0; i < fields.size(); i += 2) {
final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i));
final String fieldValue = fields.get(i + 1);
final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue);
// RECORD ATTRIBUTES
if (fieldName.equals(ODocumentHelper.ATTRIBUTE_RID))
iRecord.setIdentity(new ORecordId(fieldValueAsString));
else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION))
if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean())
recordVersion = Integer.parseInt(fieldValue);
else
iRecord.getRecordVersion().setCounter(Integer.parseInt(fieldValue));
else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION_TIMESTAMP)) {
if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean())
timestamp = Long.parseLong(fieldValue);
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION_MACADDRESS)) {
if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean())
macAddress = Long.parseLong(fieldValue);
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
continue;
} else if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument)
// JUMP IT
continue;
// RECORD VALUE(S)
else if (fieldName.equals("value") && !(iRecord instanceof ODocument)) {
if ("null".equals(fieldValue))
iRecord.fromStream(new byte[] {});
else if (iRecord instanceof ORecordBytes) {
// BYTES
iRecord.fromStream(OBase64Utils.decode(fieldValueAsString));
} else if (iRecord instanceof ORecordStringable) {
((ORecordStringable) iRecord).value(fieldValueAsString);
}
} else {
if (iRecord instanceof ODocument) {
final ODocument doc = ((ODocument) iRecord);
// DETERMINE THE TYPE FROM THE SCHEMA
OType type = null;
final OClass cls = doc.getSchemaClass();
if (cls != null) {
final OProperty prop = cls.getProperty(fieldName);
if (prop != null)
type = prop.getType();
}
final Object v = getValue(doc, fieldName, fieldValue, fieldValueAsString, type, null, fieldTypes, noMap, iOptions);
if (v != null)
if (v instanceof Collection<?> && !((Collection<?>) v).isEmpty()) {
if (v instanceof ORecordLazyMultiValue)
((ORecordLazyMultiValue) v).setAutoConvertToRecord(false);
// CHECK IF THE COLLECTION IS EMBEDDED
if (type == null) {
// TRY TO UNDERSTAND BY FIRST ITEM
Object first = ((Collection<?>) v).iterator().next();
if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid())
type = v instanceof Set<?> ? OType.EMBEDDEDSET : OType.EMBEDDEDLIST;
}
if (type != null) {
// TREAT IT AS EMBEDDED
doc.field(fieldName, v, type);
continue;
}
} else if (v instanceof Map<?, ?> && !((Map<?, ?>) v).isEmpty()) {
// CHECK IF THE MAP IS EMBEDDED
Object first = ((Map<?, ?>) v).values().iterator().next();
if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) {
doc.field(fieldName, v, OType.EMBEDDEDMAP);
continue;
}
} else if (v instanceof ODocument && type != null && type.isLink()) {
String className = ((ODocument) v).getClassName();
if (className != null && className.length() > 0)
((ODocument) v).save();
}
if (type == null && fieldTypes != null && fieldTypes.containsKey(fieldName))
type = ORecordSerializerStringAbstract.getType(fieldValue, fieldTypes.get(fieldName));
if (type != null)
doc.field(fieldName, v, type);
else
doc.field(fieldName, v);
}
}
}
if (timestamp != 0 && OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean()) {
((ODistributedVersion) iRecord.getRecordVersion()).update(recordVersion, timestamp, macAddress);
}
} catch (Exception e) {
e.printStackTrace();
throw new OSerializationException("Error on unmarshalling JSON content for record " + iRecord.getIdentity(), e);
}
}
return iRecord;
}
@SuppressWarnings("unchecked")
private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType iType,
OType iLinkedType, final Map<String, Character> iFieldTypes, final boolean iNoMap, final String iOptions) {
if (iFieldValue.equals("null"))
return null;
if (iFieldName != null)
if (iRecord.getSchemaClass() != null) {
final OProperty p = iRecord.getSchemaClass().getProperty(iFieldName);
if (p != null) {
iType = p.getType();
iLinkedType = p.getLinkedType();
}
}
if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) {
// OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT
iFieldValueAsString = iFieldValue.substring(1, iFieldValue.length() - 1);
final String[] fields = OStringParser.getWords(iFieldValueAsString, ":,", true);
if (fields == null || fields.length == 0)
// EMPTY, RETURN an EMPTY HASHMAP
return new HashMap<String, Object>();
if (iNoMap || hasTypeField(fields)) {
// OBJECT
final ORecordInternal<?> recordInternal = fromString(iFieldValue, new ODocument(), null, iOptions, false);
if (iType != null && iType.isLink()) {
} else if (recordInternal instanceof ODocument)
((ODocument) recordInternal).addOwner(iRecord);
return recordInternal;
} else {
if (fields.length % 2 == 1)
throw new OSerializationException("Bad JSON format on map. Expected pairs of field:value but received '"
+ iFieldValueAsString + "'");
// MAP
final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < fields.length; i += 2) {
iFieldName = fields[i];
if (iFieldName.length() >= 2)
iFieldName = iFieldName.substring(1, iFieldName.length() - 1);
iFieldValue = fields[i + 1];
iFieldValueAsString = OStringSerializerHelper.getStringContent(iFieldValue);
embeddedMap.put(iFieldName,
getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes, iNoMap, iOptions));
}
return embeddedMap;
}
} else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) {
// EMBEDDED VALUES
final Collection<?> embeddedCollection;
if (iType == OType.LINKSET)
embeddedCollection = new OMVRBTreeRIDSet(iRecord);
else if (iType == OType.EMBEDDEDSET)
embeddedCollection = new OTrackedSet<Object>(iRecord);
else if (iType == OType.LINKLIST)
embeddedCollection = new ORecordLazyList(iRecord);
else
embeddedCollection = new OTrackedList<Object>(iRecord);
iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1);
if (!iFieldValue.isEmpty()) {
// EMBEDDED VALUES
List<String> items = OStringSerializerHelper.smartSplit(iFieldValue, ',');
Object collectionItem;
for (String item : items) {
iFieldValue = item.trim();
if (!(iLinkedType == OType.DATE || iLinkedType == OType.BYTE || iLinkedType == OType.INTEGER || iLinkedType == OType.LONG
|| iLinkedType == OType.DATETIME || iLinkedType == OType.DECIMAL || iLinkedType == OType.DOUBLE || iLinkedType == OType.FLOAT))
iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue;
else
iFieldValueAsString = iFieldValue;
collectionItem = getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes, iNoMap,
iOptions);
if (iType != null && iType.isLink()) {
// LINK
} else if (collectionItem instanceof ODocument && iRecord instanceof ODocument)
// SET THE OWNER
((ODocument) collectionItem).addOwner(iRecord);
if (collectionItem instanceof String && ((String) collectionItem).length() == 0)
continue;
((Collection<Object>) embeddedCollection).add(collectionItem);
}
}
return embeddedCollection;
}
if (iType == null)
// TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE
if (iFieldValue.charAt(0) != '\"' && iFieldValue.charAt(0) != '\'') {
if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true"))
iType = OType.BOOLEAN;
else {
Character c = null;
if (iFieldTypes != null) {
c = iFieldTypes.get(iFieldName);
if (c != null)
iType = ORecordSerializerStringAbstract.getType(iFieldValue + c);
}
if (c == null && !iFieldValue.isEmpty()) {
// TRY TO AUTODETERMINE THE BEST TYPE
if (iFieldValue.charAt(0) == ORID.PREFIX && iFieldValue.contains(":"))
iType = OType.LINK;
else if (OStringSerializerHelper.contains(iFieldValue, '.')) {
// DECIMAL FORMAT: DETERMINE IF DOUBLE OR FLOAT
final Double v = new Double(OStringSerializerHelper.getStringContent(iFieldValue));
if (v.doubleValue() > 0) {
// POSITIVE NUMBER
if (v.compareTo(MAX_FLOAT) <= 0)
return v.floatValue();
} else if (v.compareTo(MIN_FLOAT) >= 0)
// NEGATIVE NUMBER
return v.floatValue();
return v;
} else {
final Long v = new Long(OStringSerializerHelper.getStringContent(iFieldValue));
// INTEGER FORMAT: DETERMINE IF DOUBLE OR FLOAT
if (v.longValue() > 0) {
// POSITIVE NUMBER
if (v.compareTo(MAX_INT) <= 0)
return v.intValue();
} else if (v.compareTo(MIN_INT) >= 0)
// NEGATIVE NUMBER
return v.intValue();
return v;
}
}
}
} else if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}"))
iType = OType.EMBEDDED;
else {
if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == ORID.PREFIX && iFieldValueAsString.contains(":")) {
// IS IT A LINK?
final List<String> parts = OStringSerializerHelper.split(iFieldValueAsString, 1, -1, ':');
if (parts.size() == 2)
try {
Short.parseShort(parts.get(0));
// YES, IT'S A LINK
if (parts.get(1).matches("\\d+")) {
iType = OType.LINK;
}
} catch (Exception e) {
}
}
if (iFieldTypes != null) {
Character c = null;
c = iFieldTypes.get(iFieldName);
if (c != null)
iType = ORecordSerializerStringAbstract.getType(iFieldValueAsString, c);
}
if (iType == null) {
if (iFieldValueAsString.length() == ODateHelper.getDateFormat().length())
// TRY TO PARSE AS DATE
try {
return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString);
} catch (Exception e) {
// IGNORE IT
}
if (iFieldValueAsString.length() == ODateHelper.getDateTimeFormat().length())
// TRY TO PARSE AS DATETIME
try {
return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString);
} catch (Exception e) {
// IGNORE IT
}
iType = OType.STRING;
}
}
if (iType != null)
switch (iType) {
case STRING:
return decodeJSON(iFieldValueAsString);
case LINK:
final int pos = iFieldValueAsString.indexOf('@');
if (pos > -1)
// CREATE DOCUMENT
return new ODocument(iFieldValueAsString.substring(1, pos), new ORecordId(iFieldValueAsString.substring(pos + 1)));
else {
// CREATE SIMPLE RID
return new ORecordId(iFieldValueAsString);
}
case EMBEDDED:
return fromString(iFieldValueAsString);
case DATE:
if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
return null;
try {
// TRY TO PARSE AS LONG
return Long.parseLong(iFieldValueAsString);
} catch (NumberFormatException e) {
try {
// TRY TO PARSE AS DATE
return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString);
} catch (ParseException ex) {
throw new OSerializationException("Unable to unmarshall date (format=" + ODateHelper.getDateFormat() + ") : "
+ iFieldValueAsString, e);
}
}
case DATETIME:
if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
return null;
try {
// TRY TO PARSE AS LONG
return Long.parseLong(iFieldValueAsString);
} catch (NumberFormatException e) {
try {
// TRY TO PARSE AS DATETIME
return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString);
} catch (ParseException ex) {
throw new OSerializationException("Unable to unmarshall datetime (format=" + ODateHelper.getDateTimeFormat() + ") : "
+ iFieldValueAsString, e);
}
}
case BINARY:
return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValueAsString);
default:
return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValue);
}
return iFieldValueAsString;
}
private String decodeJSON(String iFieldValueAsString) {
iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\\\", "\\");
iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\\"", "\"");
iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\/", "/");
return iFieldValueAsString;
}
@Override
public StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat,
final OUserObject2RecordHandler iObjHandler, final Set<ODocument> iMarshalledRecords, boolean iOnlyDelta,
boolean autoDetectCollectionType) {
try {
final StringWriter buffer = new StringWriter();
final OJSONWriter json = new OJSONWriter(buffer, iFormat);
final FormatSettings settings = new FormatSettings(iFormat);
json.beginObject();
OJSONFetchContext context = new OJSONFetchContext(json, settings);
context.writeSignature(json, iRecord);
if (iRecord instanceof ORecordSchemaAware<?>) {
OFetchHelper.fetch(iRecord, null, OFetchHelper.buildFetchPlan(settings.fetchPlan), new OJSONFetchListener(), context,
iFormat);
} else if (iRecord instanceof ORecordStringable) {
// STRINGABLE
final ORecordStringable record = (ORecordStringable) iRecord;
json.writeAttribute(settings.indentLevel + 1, true, "value", record.value());
} else if (iRecord instanceof ORecordBytes) {
// BYTES
final ORecordBytes record = (ORecordBytes) iRecord;
json.writeAttribute(settings.indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream()));
} else
throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass()
+ "' to JSON. The record type cannot be exported to JSON");
json.endObject(0, true);
iOutput.append(buffer);
return iOutput;
} catch (IOException e) {
throw new OSerializationException("Error on marshalling of record to JSON", e);
}
}
private boolean hasTypeField(final String[] fields) {
for (int i = 0; i < fields.length; i = i + 2) {
if (fields[i].equals("\"@type\"") || fields[i].equals("'@type'")) {
return true;
}
}
return false;
}
@Override
public String toString() {
return NAME;
}
}
|
3e05f9c20c27f786aef7eec7514d6f3d0bff6796
| 2,323 |
java
|
Java
|
lost/src/main/java/com/mapzen/android/lost/internal/FusedLocationProviderService.java
|
nycex/lost
|
c8b849c2549002440eadf967c61ab12a0d88440b
|
[
"Apache-2.0"
] | 135 |
2015-01-17T19:32:48.000Z
|
2016-09-22T14:07:10.000Z
|
lost/src/main/java/com/mapzen/android/lost/internal/FusedLocationProviderService.java
|
nycex/lost
|
c8b849c2549002440eadf967c61ab12a0d88440b
|
[
"Apache-2.0"
] | 111 |
2016-09-26T00:59:02.000Z
|
2017-11-28T19:24:02.000Z
|
lost/src/main/java/com/mapzen/android/lost/internal/FusedLocationProviderService.java
|
nycex/lost
|
c8b849c2549002440eadf967c61ab12a0d88440b
|
[
"Apache-2.0"
] | 37 |
2017-12-15T18:05:00.000Z
|
2021-07-22T11:33:31.000Z
| 31.821918 | 99 | 0.719328 | 2,519 |
package com.mapzen.android.lost.internal;
import com.mapzen.android.lost.api.LocationAvailability;
import com.mapzen.android.lost.api.LocationRequest;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import java.util.List;
/**
* Service which runs the fused location provider in the background.
*/
public class FusedLocationProviderService extends Service {
private FusedLocationProviderServiceDelegate delegate;
private final IFusedLocationProviderService.Stub binder =
new IFusedLocationProviderService.Stub() {
@Override public void add(IFusedLocationProviderCallback callback) throws RemoteException {
delegate.add(callback);
}
@Override public void remove(IFusedLocationProviderCallback callback) throws
RemoteException {
delegate.remove(callback);
}
@Override public Location getLastLocation() throws RemoteException {
return delegate.getLastLocation();
}
@Override public LocationAvailability getLocationAvailability() throws RemoteException {
return delegate.getLocationAvailability();
}
@Override public void requestLocationUpdates(LocationRequest request)
throws RemoteException {
delegate.requestLocationUpdates(request);
}
@Override public void removeLocationUpdates(List<LocationRequest> requests)
throws RemoteException {
delegate.removeLocationUpdates(requests);
}
@Override public void setMockMode(boolean isMockMode) throws RemoteException {
delegate.setMockMode(isMockMode);
}
@Override public void setMockLocation(Location mockLocation) throws RemoteException {
delegate.setMockLocation(mockLocation);
}
@Override public void setMockTrace(String path, String filename) throws RemoteException {
delegate.setMockTrace(path, filename);
}
};
@Nullable @Override public IBinder onBind(Intent intent) {
return binder;
}
@Override public void onCreate() {
super.onCreate();
delegate = new FusedLocationProviderServiceDelegate(this);
}
}
|
3e05faa9da831b13ce265e8380cdd7cb8ff469da
| 3,822 |
java
|
Java
|
moemall-mbg/src/main/java/com/chanshiyu/moemall/mbg/model/OmsOrderReturnApply.java
|
chanshiyucx/moemall
|
7fa629c42dfd98cec13e173ccabdac0002d7be67
|
[
"MIT"
] | 6 |
2019-10-04T14:18:33.000Z
|
2021-01-30T13:40:33.000Z
|
moemall-mbg/src/main/java/com/chanshiyu/moemall/mbg/model/OmsOrderReturnApply.java
|
chanshiyucx/moemall
|
7fa629c42dfd98cec13e173ccabdac0002d7be67
|
[
"MIT"
] | null | null | null |
moemall-mbg/src/main/java/com/chanshiyu/moemall/mbg/model/OmsOrderReturnApply.java
|
chanshiyucx/moemall
|
7fa629c42dfd98cec13e173ccabdac0002d7be67
|
[
"MIT"
] | null | null | null | 19.11 | 58 | 0.588174 | 2,520 |
package com.chanshiyu.moemall.mbg.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
import lombok.Data;
@Data
@ApiModel("订单退货申请")
@Table(name = "oms_order_return_apply")
public class OmsOrderReturnApply implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty("")
private Long id;
/**
* 订单id
*/
@Column(name = "order_id")
@ApiModelProperty("订单id")
private Long orderId;
/**
* 收货地址表id
*/
@Column(name = "company_address_id")
@ApiModelProperty("收货地址表id")
private Long companyAddressId;
/**
* 退货商品id
*/
@Column(name = "product_id")
@ApiModelProperty("退货商品id")
private Long productId;
/**
* 订单编号
*/
@Column(name = "order_sn")
@ApiModelProperty("订单编号")
private String orderSn;
/**
* 申请时间
*/
@Column(name = "create_time")
@ApiModelProperty("申请时间")
private Date createTime;
/**
* 会员用户名
*/
@Column(name = "member_username")
@ApiModelProperty("会员用户名")
private String memberUsername;
/**
* 退款金额
*/
@Column(name = "return_amount")
@ApiModelProperty("退款金额")
private BigDecimal returnAmount;
/**
* 退货人姓名
*/
@Column(name = "return_name")
@ApiModelProperty("退货人姓名")
private String returnName;
/**
* 退货人电话
*/
@Column(name = "return_phone")
@ApiModelProperty("退货人电话")
private String returnPhone;
/**
* 申请状态:0->待处理;1->退货中;2->已完成;3->已拒绝
*/
@ApiModelProperty("申请状态:0->待处理;1->退货中;2->已完成;3->已拒绝")
private Integer status;
/**
* 处理时间
*/
@Column(name = "handle_time")
@ApiModelProperty("处理时间")
private Date handleTime;
/**
* 商品图片
*/
@Column(name = "product_pic")
@ApiModelProperty("商品图片")
private String productPic;
/**
* 商品名称
*/
@Column(name = "product_name")
@ApiModelProperty("商品名称")
private String productName;
/**
* 商品品牌
*/
@Column(name = "product_brand")
@ApiModelProperty("商品品牌")
private String productBrand;
/**
* 商品销售属性:颜色:红色;尺码:xl;
*/
@Column(name = "product_attr")
@ApiModelProperty("商品销售属性:颜色:红色;尺码:xl;")
private String productAttr;
/**
* 退货数量
*/
@Column(name = "product_count")
@ApiModelProperty("退货数量")
private Integer productCount;
/**
* 商品单价
*/
@Column(name = "product_price")
@ApiModelProperty("商品单价")
private BigDecimal productPrice;
/**
* 商品实际支付单价
*/
@Column(name = "product_real_price")
@ApiModelProperty("商品实际支付单价")
private BigDecimal productRealPrice;
/**
* 原因
*/
@ApiModelProperty("原因")
private String reason;
/**
* 描述
*/
@ApiModelProperty("描述")
private String description;
/**
* 凭证图片,以逗号隔开
*/
@Column(name = "proof_pics")
@ApiModelProperty("凭证图片,以逗号隔开")
private String proofPics;
/**
* 处理备注
*/
@Column(name = "handle_note")
@ApiModelProperty("处理备注")
private String handleNote;
/**
* 处理人员
*/
@Column(name = "handle_man")
@ApiModelProperty("处理人员")
private String handleMan;
/**
* 收货人
*/
@Column(name = "receive_man")
@ApiModelProperty("收货人")
private String receiveMan;
/**
* 收货时间
*/
@Column(name = "receive_time")
@ApiModelProperty("收货时间")
private Date receiveTime;
/**
* 收货备注
*/
@Column(name = "receive_note")
@ApiModelProperty("收货备注")
private String receiveNote;
private static final long serialVersionUID = 1L;
}
|
3e05facd5d88275cb2b20eb1e3d9fc3909453ba2
| 2,220 |
java
|
Java
|
tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/remote/TomEERemoteWebapp.java
|
gerwinjansen/tomee
|
4763c8131acffbc7f212d4944d9dea044ab14375
|
[
"Apache-2.0"
] | 378 |
2015-01-14T09:51:24.000Z
|
2022-03-26T05:26:01.000Z
|
tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/remote/TomEERemoteWebapp.java
|
gerwinjansen/tomee
|
4763c8131acffbc7f212d4944d9dea044ab14375
|
[
"Apache-2.0"
] | 393 |
2015-11-16T08:44:15.000Z
|
2022-03-31T07:05:40.000Z
|
tomee/tomee-catalina/src/main/java/org/apache/tomee/catalina/remote/TomEERemoteWebapp.java
|
gerwinjansen/tomee
|
4763c8131acffbc7f212d4944d9dea044ab14375
|
[
"Apache-2.0"
] | 767 |
2015-01-02T19:38:49.000Z
|
2022-03-28T16:59:10.000Z
| 44.4 | 122 | 0.748198 | 2,521 |
/*
* 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.tomee.catalina.remote;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.openejb.loader.SystemInstance;
import org.apache.openejb.server.httpd.ServerServlet;
import org.apache.tomee.catalina.IgnoredStandardContext;
import org.apache.tomee.catalina.OpenEJBValve;
public class TomEERemoteWebapp extends IgnoredStandardContext {
private static final String CONTEXT_NAME = SystemInstance.get().getProperty("tomee.remote.support.context", "/tomee");
private static final String MAPPING = SystemInstance.get().getProperty("tomee.remote.support.mapping", "/ejb");
public TomEERemoteWebapp() {
setDocBase("");
setParentClassLoader(TomEERemoteWebapp.class.getClassLoader());
setDelegate(true);
setName(CONTEXT_NAME);
setPath(CONTEXT_NAME);
setLoader(new ServerClassLoaderLoader(this));
addValve(new OpenEJBValve()); // Ensure security context is reset (ThreadLocal) for each request
}
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
final Wrapper servlet = createWrapper();
servlet.setName(ServerServlet.class.getSimpleName());
servlet.setServletClass(ServerServlet.class.getName());
addChild(servlet);
addServletMappingDecoded(MAPPING, ServerServlet.class.getSimpleName());
}
}
|
3e05fb441920d787b44a61b902985e1f5fe86889
| 408 |
java
|
Java
|
calf-resource/generator/src/main/java/com/qinweizhao/generator/AbcTest.java
|
qinweizhao/qwz-calf
|
d5153c8326b8c1fd0c6608bbc84f694953246b8c
|
[
"Apache-2.0"
] | null | null | null |
calf-resource/generator/src/main/java/com/qinweizhao/generator/AbcTest.java
|
qinweizhao/qwz-calf
|
d5153c8326b8c1fd0c6608bbc84f694953246b8c
|
[
"Apache-2.0"
] | null | null | null |
calf-resource/generator/src/main/java/com/qinweizhao/generator/AbcTest.java
|
qinweizhao/qwz-calf
|
d5153c8326b8c1fd0c6608bbc84f694953246b8c
|
[
"Apache-2.0"
] | null | null | null | 25.5 | 58 | 0.644608 | 2,522 |
package com.qinweizhao.generator;
/**
* @author qinweizhao
* @since 2021/12/15
*/
public class AbcTest {
public static void main(String[] args) {
String s ="/code/generator/src/main/java";
String property = System.getProperty("user.dir");
String userHome = System.getProperty("user.home");
System.out.println(property+s);
System.out.println(userHome);
}
}
|
3e05fba9aafc59ed0ddc3f75c58ef96ab6290dd7
| 5,504 |
java
|
Java
|
platform/arcus-containers/scheduler-service/src/test/java/com/iris/platform/scheduler/TestSchedulerService.java
|
eanderso/arcusplatform
|
a2293efa1cd8e884e6bedbe9c51bf29832ba8652
|
[
"Apache-2.0"
] | null | null | null |
platform/arcus-containers/scheduler-service/src/test/java/com/iris/platform/scheduler/TestSchedulerService.java
|
eanderso/arcusplatform
|
a2293efa1cd8e884e6bedbe9c51bf29832ba8652
|
[
"Apache-2.0"
] | null | null | null |
platform/arcus-containers/scheduler-service/src/test/java/com/iris/platform/scheduler/TestSchedulerService.java
|
eanderso/arcusplatform
|
a2293efa1cd8e884e6bedbe9c51bf29832ba8652
|
[
"Apache-2.0"
] | null | null | null | 35.057325 | 118 | 0.706395 | 2,523 |
/*
* Copyright 2019 Arcus 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.iris.platform.scheduler;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.easymock.EasyMock;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.iris.core.messaging.memory.InMemoryMessageModule;
import com.iris.core.messaging.memory.InMemoryPlatformMessageBus;
import com.iris.io.json.JSON;
import com.iris.messages.MessageBody;
import com.iris.messages.PlatformMessage;
import com.iris.messages.address.Address;
import com.iris.messages.capability.SchedulerCapability;
import com.iris.messages.model.Fixtures;
import com.iris.messages.model.SimpleModel;
import com.iris.messages.model.test.ModelFixtures;
import com.iris.messages.service.SchedulerService.ListSchedulersRequest;
import com.iris.messages.service.SchedulerService.ListSchedulersResponse;
import com.iris.service.scheduler.SchedulerCapabilityDispatcher;
import com.iris.service.scheduler.SchedulerCapabilityService;
import com.iris.service.scheduler.SchedulerRegistry;
import com.iris.test.IrisMockTestCase;
import com.iris.test.Mocks;
import com.iris.test.Modules;
/**
*
*/
@Modules(InMemoryMessageModule.class)
@Mocks(SchedulerRegistry.class)
public class TestSchedulerService extends IrisMockTestCase {
UUID placeId = UUID.randomUUID();
Address clientAddress = Fixtures.createClientAddress();
Address serviceAddress = Address.platformService(SchedulerCapability.NAMESPACE);
// unit under test
@Inject SchedulerCapabilityService service;
@Inject InMemoryPlatformMessageBus messageBus;
@Inject SchedulerRegistry mockRegistry;
protected void send(MessageBody body) {
PlatformMessage message =
PlatformMessage
.buildRequest(body, clientAddress, serviceAddress)
.withPlaceId(placeId)
.create();
messageBus.send(message);
// throw away what we sent
assertEquals(message, messageBus.poll());
}
@Test
public void testListNoneForPlace() throws Exception {
EasyMock
.expect(mockRegistry.loadByPlace(placeId, true))
.andReturn(ImmutableList.of());
replay();
MessageBody body =
ListSchedulersRequest
.builder()
.withPlaceId(placeId.toString())
.build();
send(body);
MessageBody response = messageBus.take().getValue();
assertEquals(ListSchedulersResponse.NAME, response.getMessageType());
assertEquals(ImmutableList.of(), ListSchedulersResponse.getSchedulers(response));
verify();
}
@Test
public void testListSomeForPlace() throws Exception {
Map<String, Object> schedulerAttributes1 = ModelFixtures.createServiceAttributes(SchedulerCapability.NAMESPACE);
Map<String, Object> schedulerAttributes2 = ModelFixtures.createServiceAttributes(SchedulerCapability.NAMESPACE);
SchedulerCapabilityDispatcher executor1 = EasyMock.createNiceMock(SchedulerCapabilityDispatcher.class);
EasyMock.expect(executor1.getScheduler()).andReturn(new SimpleModel(schedulerAttributes1)).anyTimes();
SchedulerCapabilityDispatcher executor2 = EasyMock.createNiceMock(SchedulerCapabilityDispatcher.class);
EasyMock.expect(executor2.getScheduler()).andReturn(new SimpleModel(schedulerAttributes2)).anyTimes();
EasyMock
.expect(mockRegistry.loadByPlace(placeId, true))
.andReturn(ImmutableList.of(executor1, executor2));
replay();
EasyMock.replay(executor1, executor2);
MessageBody body =
ListSchedulersRequest
.builder()
.withPlaceId(placeId.toString())
.build();
send(body);
MessageBody response = messageBus.take().getValue();
assertEquals(ListSchedulersResponse.NAME, response.getMessageType());
List<Map<String, Object>> responseAttributes = ListSchedulersResponse.getSchedulers(response);
assertEquals(
JSON.fromJson(JSON.toJson(
ImmutableList.of(schedulerAttributes1, schedulerAttributes2)
), Object.class),
responseAttributes
);
verify();
}
@Test
public void testListWrongPlace() throws Exception {
// there shouldn't be any requests to the scheduler because of the mis-match
replay();
MessageBody body =
ListSchedulersRequest
.builder()
.withPlaceId(UUID.randomUUID().toString())
.build();
send(body);
MessageBody response = messageBus.take().getValue();
assertEquals(ListSchedulersResponse.NAME, response.getMessageType());
assertEquals(
ImmutableList.of(),
ListSchedulersResponse.getSchedulers(response)
);
verify();
}
}
|
3e05fbc3d679eca32edb2d0e60916d6231e3332d
| 1,725 |
java
|
Java
|
spring-mvc-demo/src/com/github/magdau/springdemo/mvc/HelloWorldController.java
|
magdaU/Spring_and_Hibernate_tutorial
|
cf64577a0eff14009b08f788d42a576aaa893fcf
|
[
"MIT"
] | 1 |
2019-04-13T14:32:58.000Z
|
2019-04-13T14:32:58.000Z
|
spring-mvc-demo/src/com/github/magdau/springdemo/mvc/HelloWorldController.java
|
magdaU/Spring_and_Hibernate_tutorial
|
cf64577a0eff14009b08f788d42a576aaa893fcf
|
[
"MIT"
] | 15 |
2020-03-04T22:42:55.000Z
|
2022-03-31T21:13:26.000Z
|
spring-mvc-demo/src/com/github/magdau/springdemo/mvc/HelloWorldController.java
|
magdaU/spring-and-hibernate-tutorial
|
cf64577a0eff14009b08f788d42a576aaa893fcf
|
[
"MIT"
] | null | null | null | 26.953125 | 83 | 0.727536 | 2,524 |
package com.github.magdau.springdemo.mvc;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/hello") // parent maping
public class HelloWorldController {
// Need a controller method to show the initial HTML form
@RequestMapping("/showForm") // url // sub maping
public String showForm() {
return "helloworld-form"; // the name of file.jsp
}
// Need a controller method to process to HTML form
@RequestMapping("/processForm") // sub maping
public String processForm() {
return "helloworld"; // the name of file.jsp
}
// New a controller method to read form data and add data to the model
@RequestMapping("/processFormVersionTwo")
public String letsShoutDude(HttpServletRequest request, Model model) {
//Read the request parameter from the HTML form
String theName = request.getParameter("studentName");
//Convert the data to all caps
theName=theName.toUpperCase();
//Create message
String result = "Yo! " + theName;
//Add a message to the model
model.addAttribute("message", result);
return "helloworld";
}
@RequestMapping("/processFormVersionThree")
public String processFormVersionThree(@RequestParam("studentName") String theName,
Model model) {
//Convert the data to all caps
theName=theName.toUpperCase();
//Create message
String result = "Hey My Friend from v3! " + theName;
//Add a message to the model
model.addAttribute("message", result);
return "helloworld";
}
}
|
3e05fbfc1285c4a6e8bcc38f4ee8fde8b0c3ed97
| 1,547 |
java
|
Java
|
src/chapter4FunctionalProgramming/chapter4_2Streams/App.java
|
KurtTaylan/ocpJavaSE8preparation
|
c3a4cccdc0363e3656ff913b13652544d852329d
|
[
"Apache-2.0"
] | null | null | null |
src/chapter4FunctionalProgramming/chapter4_2Streams/App.java
|
KurtTaylan/ocpJavaSE8preparation
|
c3a4cccdc0363e3656ff913b13652544d852329d
|
[
"Apache-2.0"
] | null | null | null |
src/chapter4FunctionalProgramming/chapter4_2Streams/App.java
|
KurtTaylan/ocpJavaSE8preparation
|
c3a4cccdc0363e3656ff913b13652544d852329d
|
[
"Apache-2.0"
] | null | null | null | 33.630435 | 94 | 0.731092 | 2,525 |
/**
* Stream in Java is a sequence of data. A stream pipeline is the operations that run on a
* stream to produce a result.With streams,
* the data isn’t generated up front—it is created when needed.
*
* Data isn’t generated up front—it is created when needed.
* Many things can happen in the assembly line stations along the way. In programming,
* these are called stream operations. Just like with the assembly line, operations occur in a
* pipeline. Someone has to start and end the work, and there can be any number of stations
* in between.
*
* After all, a job with one person isn’t an assembly line! There are three parts to
* a stream pipeline,
*
* -Source: Where the stream comes from.
*
* -Intermediate operations: Transforms the stream into another one. There can be as few
* or as many intermediate operations as you’d like. Since streams use lazy evaluation, the
* intermediate operations do not run until the terminal operation runs.
*
* -Terminal operation: Actually produces a result. Since streams can be used only once,
* the stream is no longer valid after a terminal operation completes.
*
* When viewing the assembly line from the outside,
* you care only about what comes in and goes out. What happens in
* between is an implementation detail.
*
* We all want to avoid unnecessary work!
*
*
*/
package chapter4FunctionalProgramming.chapter4_2Streams;
/**
* @author tkurt
* Date: Apr 21, 2016 12:18:23 PM
*
*/
public class App {
public static void main(String[] args) {
}
}
|
3e05fdc55d3dedebc8b33204923e351e6acc20a4
| 145 |
java
|
Java
|
library/src/main/java/com/devil/library/camera/listener/OnFpsListener.java
|
GuangNian10000/DVMediaSelector-2.1.0
|
2bc06f7c306e75e398a578dd657efb8eb1ad6066
|
[
"Apache-2.0"
] | 1 |
2021-11-17T01:30:18.000Z
|
2021-11-17T01:30:18.000Z
|
library/src/main/java/com/devil/library/camera/listener/OnFpsListener.java
|
GuangNian10000/DVMediaSelector-2.1.0
|
2bc06f7c306e75e398a578dd657efb8eb1ad6066
|
[
"Apache-2.0"
] | null | null | null |
library/src/main/java/com/devil/library/camera/listener/OnFpsListener.java
|
GuangNian10000/DVMediaSelector-2.1.0
|
2bc06f7c306e75e398a578dd657efb8eb1ad6066
|
[
"Apache-2.0"
] | null | null | null | 14.5 | 42 | 0.689655 | 2,526 |
package com.devil.library.camera.listener;
/**
* fps监听器
*/
public interface OnFpsListener {
// fps回调
void onFpsCallback(float fps);
}
|
3e05fe25c580ba75261daf7de7969a5f59a7088e
| 3,163 |
java
|
Java
|
commons/src/main/java/com/platform/common/excel/AbstractExcelReader.java
|
andyZheng/-common-platform
|
50c6f8df4df47c833ad2b4d389723534c19c6224
|
[
"Apache-2.0"
] | 2 |
2016-02-17T10:56:46.000Z
|
2016-04-12T11:10:40.000Z
|
commons/src/main/java/com/platform/common/excel/AbstractExcelReader.java
|
andyZheng/common-platform
|
50c6f8df4df47c833ad2b4d389723534c19c6224
|
[
"Apache-2.0"
] | null | null | null |
commons/src/main/java/com/platform/common/excel/AbstractExcelReader.java
|
andyZheng/common-platform
|
50c6f8df4df47c833ad2b4d389723534c19c6224
|
[
"Apache-2.0"
] | null | null | null | 27.094017 | 115 | 0.665931 | 2,527 |
/*
* 文件名:AbstractExcelReader.java
* 版权:Copyright 2012-2013 Beijing Founder Apabi Tech. Co. Ltd. All Rights Reserved.
* 描述:
* 修改人:
* 修改时间:
* 跟踪单号:
* 修改单号:
* 修改内容:
*/
package com.platform.common.excel;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.Map;
import com.platform.common.excel.entity.Sheet;
import com.platform.common.excel.handler.DataRowHandler;
import com.platform.common.excel.handler.ExcelReader;
import com.platform.common.excel.parser.ExcelDataParser;
import com.platform.common.excel.parser.HSSFParser;
import com.platform.common.excel.parser.XSSFParser;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
* 功能描述: <code>AbstractExcelReader</code>为Excel大数据文件读取器抽象类。
* <P>
* 功能详细描述:目前主要针对Excel电子表格、Excel XML两个格式提供个性化的解决方案。
*
* @author [email protected]
* @version 1.0, 2013-7-29 下午4:55:08
* @since Commons Platform 1.0
*/
public abstract class AbstractExcelReader implements ExcelReader, DataRowHandler{
/** 中式日期格式 */
private String dateFormateString = "yyyy-MM-dd 00:00:00";
/** 表格总数 */
private int sheetCount = 1;
/**
* 功能描述: 加载Excel文件。<p>
* 功能详细描述:根据加载的Excel文件版本,自动匹配相应的解析器。
*
* @param fileName 待加载的Excel文件。
* @throws Throwable
*/
public void load(String fileName) throws Throwable {
ExcelDataParser parser = null;
InputStream inp = new FileInputStream(fileName);
if (!inp.markSupported())
inp = new PushbackInputStream(inp, 8);
if (POIFSFileSystem.hasPOIFSHeader(inp)) {
parser = new HSSFParser(this);
} else if (POIXMLDocument.hasOOXMLHeader(inp)) {
parser = new XSSFParser(this);
}
if (null == parser) {
throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
}
parser.setDateFormateString(dateFormateString);
parser.parser(fileName);
this.sheetCount = parser.getSheetCount();
}
/**
* 功能说明:设置单元格日期格式。<p>
* 缺省为:yyyy-MM-dd 00:00:00
*
* @param dateFormateString 待设置的单元格日期格式。
*/
@Override
public void setDateFormateString(String dateFormateString) {
this.dateFormateString = dateFormateString;
}
/**
* 功能说明:获取加载的Excel文件表格总数量。
*
* @return int the sheetIndex 返回加载的Excel文件表格总数量。
*/
@Override
public int getSheetCount() {
return sheetCount;
}
/*
* @see com.platform.common.excel.handler.ExcelReader#getSingleSheetDataList(java.lang.String)
*/
@Override
public Sheet getSingleSheetDataList(String sheetIndex) {
return null;
}
/*
* @see com.platform.common.excel.handler.ExcelReader#getMoreSheetDataList()
*/
@Override
public Map<String, Sheet> getMoreSheetDataList() {
return null;
}
/*
* @see com.platform.common.excel.handler.ExcelReader#setDataSeparator(java.lang.String)
*/
@Override
public void setDataSeparator(String dataSeparator) {
}
}
|
3e05ff3f613320d237bf447baf5913312c2cc3b5
| 3,463 |
java
|
Java
|
aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/entities/Cause.java
|
wangzlei/aws-xray-sdk-java
|
d5ccae28236b274fccb7f44b027b8c8e819b0f99
|
[
"Apache-2.0"
] | 1 |
2021-07-10T15:04:07.000Z
|
2021-07-10T15:04:07.000Z
|
aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/entities/Cause.java
|
wangzlei/aws-xray-sdk-java
|
d5ccae28236b274fccb7f44b027b8c8e819b0f99
|
[
"Apache-2.0"
] | 2 |
2021-02-19T23:31:36.000Z
|
2021-02-21T02:35:29.000Z
|
aws-xray-recorder-sdk-core/src/main/java/com/amazonaws/xray/entities/Cause.java
|
wangzlei/aws-xray-sdk-java
|
d5ccae28236b274fccb7f44b027b8c8e819b0f99
|
[
"Apache-2.0"
] | null | null | null | 23.557823 | 129 | 0.634999 | 2,528 |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.xray.entities;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A representation of what issues caused this (sub)segment to include a failure / error. Can include exceptions or references to
* other exceptions.
*
*/
public class Cause {
private static final Log logger =
LogFactory.getLog(Cause.class);
@Nullable
private String workingDirectory;
@Nullable
private String id;
@Nullable
private String message;
@Nullable
private Collection<String> paths;
private final List<ThrowableDescription> exceptions;
public Cause() {
this(new ArrayList<>(), new ArrayList<>());
}
Cause(List<String> paths, List<ThrowableDescription> exceptions) {
this.paths = paths;
this.exceptions = exceptions;
}
/**
* @return the workingDirectory
*/
@Nullable
public String getWorkingDirectory() {
return workingDirectory;
}
/**
* @param workingDirectory the workingDirectory to set
*/
public void setWorkingDirectory(@Nullable String workingDirectory) {
this.workingDirectory = workingDirectory;
}
/**
* @return the id
*/
@Nullable
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the message
*/
@Nullable
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the paths
*/
@Nullable
public Collection<String> getPaths() {
return paths;
}
/**
* @param paths the paths to set
*/
public void setPaths(Collection<String> paths) {
this.paths = paths;
}
/**
* @return the exceptions
*/
public List<ThrowableDescription> getExceptions() {
return exceptions;
}
public void addException(ThrowableDescription descriptor) {
if (exceptions.isEmpty()) {
addWorkingDirectoryAndPaths();
}
exceptions.add(descriptor);
}
public void addExceptions(List<ThrowableDescription> descriptors) {
if (exceptions.isEmpty()) {
addWorkingDirectoryAndPaths();
}
exceptions.addAll(descriptors);
}
private void addWorkingDirectoryAndPaths() {
try {
setWorkingDirectory(System.getProperty("user.dir"));
} catch (SecurityException se) {
logger.warn("Unable to set working directory.", se);
}
}
}
|
3e05ff89056203792491ce835d2510c47cc6bf39
| 3,218 |
java
|
Java
|
src/test/java/org/ndextools/morphcx/tables/ExcelAppTest.java
|
ndextools/ndex-morphcs
|
ee5da0e9f15c628453f92b667b6704ee02e2d3c8
|
[
"MIT"
] | null | null | null |
src/test/java/org/ndextools/morphcx/tables/ExcelAppTest.java
|
ndextools/ndex-morphcs
|
ee5da0e9f15c628453f92b667b6704ee02e2d3c8
|
[
"MIT"
] | 4 |
2019-01-26T03:52:00.000Z
|
2019-02-02T00:19:52.000Z
|
src/test/java/org/ndextools/morphcx/tables/ExcelAppTest.java
|
ndextools/ndex-morphcx
|
ee5da0e9f15c628453f92b667b6704ee02e2d3c8
|
[
"MIT"
] | null | null | null | 27.741379 | 91 | 0.682722 | 2,529 |
package org.ndextools.morphcx.tables;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ExcelAppTest {
private SXSSFWorkbook wb;
private ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private static final String SHEET_NAME = "Captain Ahab";
private static final List<String> columnHeadings =
new ArrayList<>( Arrays.asList( "Ishmael", "Starbuck", "Stubb" ) );
@Before
public void setUp() throws Exception {
// Redirect console output to outContent in order to perform JUnit tests.
PrintStream ps;
try (PrintStream printStream = new PrintStream(outContent);
SXSSFWorkbook workbook = new SXSSFWorkbook() )
{
this.wb = workbook;
ps = printStream;
}
catch (Exception e) {
System.setOut(System.out);
throw new Exception(e);
}
System.setOut(ps);
}
@After
public void tearDown() {
//Redirect console output to system stdout stream.
System.setOut(System.out);
}
@Ignore
public void initializeSpreadsheets() {
/*
// Not implemented because of the requirement to mock the creation of a
// NiceCXNetwork object. Besides, the crux of its functionality is validated
// when testing the addSSInfoElement() method.
*/
}
@Test
public void _Should_populateNetworkTableSheet() {
}
@Test
public void _Should_populateNodeTableSheet() {
}
@Test
public void _Should_populateEdgeTableSheet() {
}
@Test
public void _Should_gatherNetworkTableColumnHeadings() {
}
@Test
public void _Should_gatherNodeTableColumnHeadings() {
}
@Test
public void _Should_gatherEdgeTableColumnHeadings() {
}
@Test
public void _Should_addColumnHeadings() {
}
@Test
public void _Should_makeColumnHeadings() {
}
@Test
public void _Should_toString() {
}
@Test
public void _Should_Add_SheetName_To_New_SpreadsheetInfo_Element() {
SpreadsheetInfo ssInfo = ExcelApp.addSSInfoElement(wb, SHEET_NAME, columnHeadings);
Assert.assertEquals(SHEET_NAME, ssInfo.getSheetName());
}
@Test
public void _Should_Add_Column_Headings_To_New_SpreadsheetInfo_Element() {
SpreadsheetInfo ssInfo = ExcelApp.addSSInfoElement(wb, SHEET_NAME, columnHeadings);
Assert.assertEquals(columnHeadings, ssInfo.getColumnHeadings());
}
@Test
public void _Should_Add_Workbook_Reference_To_New_SpreadsheetInfo_Element() {
SpreadsheetInfo ssInfo = ExcelApp.addSSInfoElement(wb, SHEET_NAME, columnHeadings);
Assert.assertEquals(wb, ssInfo.getWorkbook());
}
@Test
public void _Should_Increment_RowIdx_In_New_SpreadsheetInfo_Element() {
SpreadsheetInfo ssInfo = ExcelApp.addSSInfoElement(wb, SHEET_NAME, columnHeadings);
Assert.assertEquals(1, ssInfo.getNextRowIdx());
}
}
|
3e05ffab898a54eed77802c6b88425b14fadc33f
| 10,720 |
java
|
Java
|
plugins/mps-vcs/vcs-core/modules/jetbrains.mps.ide.vcs.core/source_gen/jetbrains/mps/smodel/persistence/def/v6/LineToContentMapReader6Handler.java
|
trespasserw/MPS
|
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
|
[
"Apache-2.0"
] | null | null | null |
plugins/mps-vcs/vcs-core/modules/jetbrains.mps.ide.vcs.core/source_gen/jetbrains/mps/smodel/persistence/def/v6/LineToContentMapReader6Handler.java
|
trespasserw/MPS
|
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
|
[
"Apache-2.0"
] | null | null | null |
plugins/mps-vcs/vcs-core/modules/jetbrains.mps.ide.vcs.core/source_gen/jetbrains/mps/smodel/persistence/def/v6/LineToContentMapReader6Handler.java
|
trespasserw/MPS
|
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
|
[
"Apache-2.0"
] | null | null | null | 37.879859 | 215 | 0.697948 | 2,530 |
package jetbrains.mps.smodel.persistence.def.v6;
/*Generated by MPS */
import jetbrains.mps.annotations.GeneratedClass;
import jetbrains.mps.util.xml.XMLSAXHandler;
import java.util.List;
import jetbrains.mps.smodel.persistence.lines.LineContent;
import java.util.Stack;
import org.xml.sax.Locator;
import jetbrains.mps.smodel.persistence.def.v5.LineContentAccumulator;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXParseException;
import jetbrains.mps.smodel.SNodeId;
@GeneratedClass(node = "r:83748538-cbc9-4e2d-b0e1-e282b3d0c13d(jetbrains.mps.smodel.persistence.def.v6)/651246788329803429", model = "r:83748538-cbc9-4e2d-b0e1-e282b3d0c13d(jetbrains.mps.smodel.persistence.def.v6)")
public class LineToContentMapReader6Handler extends XMLSAXHandler<List<LineContent>> {
private ModelElementHandler modelHandler = new ModelElementHandler();
private NodeElementHandler nodeHandler = new NodeElementHandler();
private PropertyElementHandler propertyHandler = new PropertyElementHandler();
private LinkElementHandler linkHandler = new LinkElementHandler();
private Root_stubsElementHandler root_stubsHandler = new Root_stubsElementHandler();
private NullElementHandler nullHandler = new NullElementHandler();
private Stack<ElementHandler> myHandlersStack = new Stack<ElementHandler>();
private Stack<ChildHandler> myChildHandlersStack = new Stack<ChildHandler>();
private Stack<Object> myValues = new Stack<Object>();
private Locator myLocator;
private List<LineContent> myResult;
private LineContentAccumulator my_accumulatorField;
public LineToContentMapReader6Handler() {
}
public List<LineContent> getResult() {
return myResult;
}
@Override
public void setDocumentLocator(Locator locator) {
myLocator = locator;
}
@Override
public void characters(char[] array, int start, int len) throws SAXException {
globalHandleText(myValues.firstElement(), new String(array, start, len));
ElementHandler current = (myHandlersStack.empty() ? (ElementHandler) null : myHandlersStack.peek());
if (current != null) {
current.handleText(myValues.peek(), new String(array, start, len));
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
ElementHandler current = myHandlersStack.pop();
Object childValue = myValues.pop();
current.validate(childValue);
if (myChildHandlersStack.empty()) {
myResult = (List<LineContent>) childValue;
} else {
ChildHandler ch = myChildHandlersStack.pop();
if (ch != null) {
ch.apply(myValues.peek(), childValue);
}
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
ElementHandler current = (myHandlersStack.empty() ? (ElementHandler) null : myHandlersStack.peek());
if (current == null) {
// root
current = modelHandler;
} else {
current = current.createChild(myValues.peek(), qName, attributes);
}
// check required
for (String attr : current.requiredAttributes()) {
if (attributes.getValue(attr) == null) {
throw new SAXParseException("attribute " + attr + " is absent", null);
}
}
Object result = current.createObject(attributes);
if (myHandlersStack.empty()) {
myResult = (List<LineContent>) result;
}
// handle attributes
for (int i = 0; i < attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
current.handleAttribute(result, name, value);
}
myHandlersStack.push(current);
myValues.push(result);
}
public void globalHandleText(Object resultObject, String value) {
List<LineContent> result = (List<LineContent>) resultObject;
my_accumulatorField.processText(value, myLocator);
}
private interface ChildHandler {
void apply(Object resultObject, Object value) throws SAXException;
}
private class ElementHandler {
private String[] requiredAttributes = new String[0];
private ElementHandler() {
}
protected Object createObject(Attributes attrs) throws SAXException {
return null;
}
protected void handleAttribute(Object resultObject, String name, String value) throws SAXException {
}
protected ElementHandler createChild(Object resultObject, String tagName, Attributes attrs) throws SAXException {
throw new SAXParseException("unknown tag: " + tagName, null);
}
protected void handleText(Object resultObject, String value) throws SAXException {
if (value.trim().length() == 0) {
return;
}
throw new SAXParseException("text is not accepted: '" + value + "'", null);
}
protected String[] requiredAttributes() {
return requiredAttributes;
}
protected void setRequiredAttributes(String... required) {
requiredAttributes = required;
}
protected void validate(Object resultObject) throws SAXException {
}
}
public class ModelElementHandler extends ElementHandler {
public ModelElementHandler() {
}
@Override
protected List<LineContent> createObject(Attributes attrs) throws SAXException {
my_accumulatorField = new LineContentAccumulator();
return my_accumulatorField.getLineToContentMap();
}
@Override
protected ElementHandler createChild(Object resultObject, String tagName, Attributes attrs) throws SAXException {
if ("persistence".equals(tagName)) {
myChildHandlersStack.push(null);
return nullHandler;
}
if ("language".equals(tagName)) {
myChildHandlersStack.push(null);
return nullHandler;
}
if ("language-engaged-on-generation".equals(tagName)) {
myChildHandlersStack.push(null);
return nullHandler;
}
if ("devkit".equals(tagName)) {
myChildHandlersStack.push(null);
return nullHandler;
}
if ("import".equals(tagName)) {
myChildHandlersStack.push(null);
return nullHandler;
}
if ("root_stubs".equals(tagName)) {
myChildHandlersStack.push(null);
return root_stubsHandler;
}
if ("node".equals(tagName)) {
myChildHandlersStack.push(new ChildHandler() {
@Override
public void apply(Object resultObject, Object value) throws SAXException {
handleChild_7606567306781655212(resultObject, value);
}
});
return nodeHandler;
}
return super.createChild(resultObject, tagName, attrs);
}
private void handleChild_7606567306781655212(Object resultObject, Object value) throws SAXException {
Object child = (Object) value;
my_accumulatorField.popNode(myLocator);
}
}
public class NodeElementHandler extends ElementHandler {
public NodeElementHandler() {
setRequiredAttributes("type");
}
@Override
protected void handleAttribute(Object resultObject, String name, String value) throws SAXException {
Object result = (Object) resultObject;
if ("id".equals(name)) {
my_accumulatorField.pushNode(SNodeId.fromString(value), myLocator);
return;
}
super.handleAttribute(resultObject, name, value);
}
@Override
protected ElementHandler createChild(Object resultObject, String tagName, Attributes attrs) throws SAXException {
if ("property".equals(tagName)) {
myChildHandlersStack.push(new ChildHandler() {
@Override
public void apply(Object resultObject, Object value) throws SAXException {
handleChild_651246788329803624(resultObject, value);
}
});
return propertyHandler;
}
if ("link".equals(tagName)) {
myChildHandlersStack.push(new ChildHandler() {
@Override
public void apply(Object resultObject, Object value) throws SAXException {
handleChild_651246788329803647(resultObject, value);
}
});
return linkHandler;
}
if ("node".equals(tagName)) {
myChildHandlersStack.push(new ChildHandler() {
@Override
public void apply(Object resultObject, Object value) throws SAXException {
handleChild_651246788329803692(resultObject, value);
}
});
return nodeHandler;
}
return super.createChild(resultObject, tagName, attrs);
}
private void handleChild_651246788329803624(Object resultObject, Object value) throws SAXException {
String child = (String) value;
if (child != null) {
my_accumulatorField.saveProperty(child, myLocator);
}
}
private void handleChild_651246788329803647(Object resultObject, Object value) throws SAXException {
String child = (String) value;
if (child != null) {
my_accumulatorField.saveReference(child, myLocator);
}
}
private void handleChild_651246788329803692(Object resultObject, Object value) throws SAXException {
Object child = (Object) value;
my_accumulatorField.popNode(myLocator);
}
}
public class PropertyElementHandler extends ElementHandler {
public PropertyElementHandler() {
setRequiredAttributes("name");
}
@Override
protected String createObject(Attributes attrs) throws SAXException {
return VersionUtil.readRoleSimple(attrs.getValue("name"));
}
}
public class LinkElementHandler extends ElementHandler {
public LinkElementHandler() {
setRequiredAttributes("role");
}
@Override
protected String createObject(Attributes attrs) throws SAXException {
return VersionUtil.readRoleSimple(attrs.getValue("role"));
}
}
public class Root_stubsElementHandler extends ElementHandler {
public Root_stubsElementHandler() {
}
@Override
protected ElementHandler createChild(Object resultObject, String tagName, Attributes attrs) throws SAXException {
if ("node".equals(tagName)) {
myChildHandlersStack.push(new ChildHandler() {
@Override
public void apply(Object resultObject, Object value) throws SAXException {
handleChild_1967473504308989641(resultObject, value);
}
});
return nodeHandler;
}
return super.createChild(resultObject, tagName, attrs);
}
private void handleChild_1967473504308989641(Object resultObject, Object value) throws SAXException {
Object child = (Object) value;
my_accumulatorField.popNode(myLocator);
}
}
public class NullElementHandler extends ElementHandler {
public NullElementHandler() {
}
}
}
|
3e05ffca1832a13f5e8727cda540a59cf2661de7
| 3,212 |
java
|
Java
|
lcm-types/lcmtypes/control_parameter_respones_lcmt.java
|
FikkleG/gallopingFaster
|
2578980f0fbb3a2aa32054bc12cab6e156f1953f
|
[
"MIT"
] | 12 |
2020-09-16T06:21:36.000Z
|
2021-12-21T12:42:39.000Z
|
lcm-types/lcmtypes/control_parameter_respones_lcmt.java
|
FikkleG/gallopingFaster
|
2578980f0fbb3a2aa32054bc12cab6e156f1953f
|
[
"MIT"
] | null | null | null |
lcm-types/lcmtypes/control_parameter_respones_lcmt.java
|
FikkleG/gallopingFaster
|
2578980f0fbb3a2aa32054bc12cab6e156f1953f
|
[
"MIT"
] | 5 |
2021-02-16T10:14:54.000Z
|
2022-03-02T03:16:58.000Z
| 27.452991 | 116 | 0.655978 | 2,531 |
/* LCM type definition class file
* This file was automatically generated by lcm-gen
* DO NOT MODIFY BY HAND!!!!
*/
package lcmtypes;
import java.io.*;
import java.util.*;
import lcm.lcm.*;
public final class control_parameter_respones_lcmt implements lcm.lcm.LCMEncodable
{
public byte name[];
public long requestNumber;
public byte value[];
public byte parameterKind;
public byte requestKind;
public control_parameter_respones_lcmt()
{
name = new byte[64];
value = new byte[64];
}
public static final long LCM_FINGERPRINT;
public static final long LCM_FINGERPRINT_BASE = 0xe827e9f6525296b9L;
static {
LCM_FINGERPRINT = _hashRecursive(new ArrayList<Class<?>>());
}
public static long _hashRecursive(ArrayList<Class<?>> classes)
{
if (classes.contains(lcmtypes.control_parameter_respones_lcmt.class))
return 0L;
classes.add(lcmtypes.control_parameter_respones_lcmt.class);
long hash = LCM_FINGERPRINT_BASE
;
classes.remove(classes.size() - 1);
return (hash<<1) + ((hash>>63)&1);
}
public void encode(DataOutput outs) throws IOException
{
outs.writeLong(LCM_FINGERPRINT);
_encodeRecursive(outs);
}
public void _encodeRecursive(DataOutput outs) throws IOException
{
outs.write(this.name, 0, 64);
outs.writeLong(this.requestNumber);
outs.write(this.value, 0, 64);
outs.writeByte(this.parameterKind);
outs.writeByte(this.requestKind);
}
public control_parameter_respones_lcmt(byte[] data) throws IOException
{
this(new LCMDataInputStream(data));
}
public control_parameter_respones_lcmt(DataInput ins) throws IOException
{
if (ins.readLong() != LCM_FINGERPRINT)
throw new IOException("LCM Decode error: bad fingerprint");
_decodeRecursive(ins);
}
public static lcmtypes.control_parameter_respones_lcmt _decodeRecursiveFactory(DataInput ins) throws IOException
{
lcmtypes.control_parameter_respones_lcmt o = new lcmtypes.control_parameter_respones_lcmt();
o._decodeRecursive(ins);
return o;
}
public void _decodeRecursive(DataInput ins) throws IOException
{
this.name = new byte[(int) 64];
ins.readFully(this.name, 0, 64);
this.requestNumber = ins.readLong();
this.value = new byte[(int) 64];
ins.readFully(this.value, 0, 64);
this.parameterKind = ins.readByte();
this.requestKind = ins.readByte();
}
public lcmtypes.control_parameter_respones_lcmt copy()
{
lcmtypes.control_parameter_respones_lcmt outobj = new lcmtypes.control_parameter_respones_lcmt();
outobj.name = new byte[(int) 64];
System.arraycopy(this.name, 0, outobj.name, 0, 64);
outobj.requestNumber = this.requestNumber;
outobj.value = new byte[(int) 64];
System.arraycopy(this.value, 0, outobj.value, 0, 64);
outobj.parameterKind = this.parameterKind;
outobj.requestKind = this.requestKind;
return outobj;
}
}
|
3e06004681af689cdeeb1a8b952c6bda138e3d2e
| 1,394 |
java
|
Java
|
src/test/java/be/tombaeyens/cbe/test/framework/TestServer.java
|
tombaeyens/non-blocking-server
|
0803f0e66623d0101cd7831b8d168b4acd46e7b9
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/be/tombaeyens/cbe/test/framework/TestServer.java
|
tombaeyens/non-blocking-server
|
0803f0e66623d0101cd7831b8d168b4acd46e7b9
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/be/tombaeyens/cbe/test/framework/TestServer.java
|
tombaeyens/non-blocking-server
|
0803f0e66623d0101cd7831b8d168b4acd46e7b9
|
[
"Apache-2.0"
] | null | null | null | 30.977778 | 75 | 0.763989 | 2,532 |
/* 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 be.tombaeyens.cbe.test.framework;
import be.tombaeyens.cbe.http.framework.Server;
import be.tombaeyens.cbe.http.framework.ServerBuilder;
import be.tombaeyens.cbe.http.framework.ServerChannelInitializer;
/**
* @author Tom Baeyens
*/
public class TestServer extends Server {
protected Exception latestException;
public TestServer() {
super(createTestServerBuilder());
}
private static ServerBuilder createTestServerBuilder() {
ServerBuilder testServerBuilder = new ServerBuilder();
testServerBuilder.getDbBuilder().idGenerator(new TestIdGenerator());
return testServerBuilder;
}
@Override
protected ServerChannelInitializer createServerChannelInitializer() {
return new TestServerChannelInitializer(this);
}
public Throwable getLatestException() {
return latestException;
}
}
|
3e060122eb56c8c5d5e0572bfefe37ac1b0bf83d
| 1,602 |
java
|
Java
|
app/src/main/java/net/hyx/app/volumenotification/model/AudioManagerModel.java
|
yuukiyork/volumenotification
|
1f8dfd5b521e841f79f97469194cf045eee8e6ad
|
[
"Apache-2.0"
] | 42 |
2016-09-11T11:25:30.000Z
|
2021-01-20T04:41:21.000Z
|
app/src/main/java/net/hyx/app/volumenotification/model/AudioManagerModel.java
|
yuukiyork/volumenotification
|
1f8dfd5b521e841f79f97469194cf045eee8e6ad
|
[
"Apache-2.0"
] | 26 |
2017-01-30T09:29:53.000Z
|
2019-08-22T15:47:35.000Z
|
app/src/main/java/net/hyx/app/volumenotification/model/AudioManagerModel.java
|
yuukiyork/volumenotification
|
1f8dfd5b521e841f79f97469194cf045eee8e6ad
|
[
"Apache-2.0"
] | 14 |
2017-02-05T20:33:12.000Z
|
2020-05-02T16:28:40.000Z
| 34.085106 | 162 | 0.717853 | 2,533 |
/*
* Copyright 2017 https://github.com/seht
*
* 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 net.hyx.app.volumenotification.model;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
public class AudioManagerModel {
private final AudioManager audio;
private final SettingsModel settings;
public AudioManagerModel(Context context) {
audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
settings = new SettingsModel(context);
}
public void adjustVolume(int streamType) {
audio.adjustStreamVolume(streamType, getStreamFlag(streamType), AudioManager.FLAG_SHOW_UI);
}
private int getStreamFlag(int streamType) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((streamType == AudioManager.STREAM_MUSIC && settings.getToggleMute()) || (streamType == AudioManager.STREAM_RING && settings.getToggleSilent())) {
return AudioManager.ADJUST_TOGGLE_MUTE;
}
}
return AudioManager.ADJUST_SAME;
}
}
|
3e060132622ba4d01034404138c9ba3e78375a6c
| 3,299 |
java
|
Java
|
sources/androidx/media2/exoplayer/external/source/MediaSource.java
|
Minionguyjpro/Ghostly-Skills
|
d1a1fb2498aec461da09deb3ef8d98083542baaf
|
[
"MIT"
] | 1 |
2021-11-03T14:24:37.000Z
|
2021-11-03T14:24:37.000Z
|
sources/androidx/media2/exoplayer/external/source/MediaSource.java
|
Minionguyjpro/Ghostly-Skills
|
d1a1fb2498aec461da09deb3ef8d98083542baaf
|
[
"MIT"
] | null | null | null |
sources/androidx/media2/exoplayer/external/source/MediaSource.java
|
Minionguyjpro/Ghostly-Skills
|
d1a1fb2498aec461da09deb3ef8d98083542baaf
|
[
"MIT"
] | null | null | null | 35.858696 | 301 | 0.6505 | 2,534 |
package androidx.media2.exoplayer.external.source;
import android.os.Handler;
import androidx.media2.exoplayer.external.Timeline;
import androidx.media2.exoplayer.external.upstream.Allocator;
import androidx.media2.exoplayer.external.upstream.TransferListener;
import java.io.IOException;
public interface MediaSource {
public interface SourceInfoRefreshListener {
void onSourceInfoRefreshed(MediaSource mediaSource, Timeline timeline, Object obj);
}
void addEventListener(Handler handler, MediaSourceEventListener mediaSourceEventListener);
MediaPeriod createPeriod(MediaPeriodId mediaPeriodId, Allocator allocator, long j);
Object getTag();
void maybeThrowSourceInfoRefreshError() throws IOException;
void prepareSource(SourceInfoRefreshListener sourceInfoRefreshListener, TransferListener transferListener);
void releasePeriod(MediaPeriod mediaPeriod);
void releaseSource(SourceInfoRefreshListener sourceInfoRefreshListener);
void removeEventListener(MediaSourceEventListener mediaSourceEventListener);
public static final class MediaPeriodId {
public final int adGroupIndex;
public final int adIndexInAdGroup;
public final int nextAdGroupIndex;
public final Object periodUid;
public final long windowSequenceNumber;
public MediaPeriodId(Object obj) {
this(obj, -1);
}
public MediaPeriodId(Object obj, long j) {
this(obj, -1, -1, j, -1);
}
public MediaPeriodId(Object obj, long j, int i) {
this(obj, -1, -1, j, i);
}
public MediaPeriodId(Object obj, int i, int i2, long j) {
this(obj, i, i2, j, -1);
}
private MediaPeriodId(Object obj, int i, int i2, long j, int i3) {
this.periodUid = obj;
this.adGroupIndex = i;
this.adIndexInAdGroup = i2;
this.windowSequenceNumber = j;
this.nextAdGroupIndex = i3;
}
public MediaPeriodId copyWithPeriodUid(Object obj) {
if (this.periodUid.equals(obj)) {
return this;
}
return new MediaPeriodId(obj, this.adGroupIndex, this.adIndexInAdGroup, this.windowSequenceNumber, this.nextAdGroupIndex);
}
public boolean isAd() {
return this.adGroupIndex != -1;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
MediaPeriodId mediaPeriodId = (MediaPeriodId) obj;
if (this.periodUid.equals(mediaPeriodId.periodUid) && this.adGroupIndex == mediaPeriodId.adGroupIndex && this.adIndexInAdGroup == mediaPeriodId.adIndexInAdGroup && this.windowSequenceNumber == mediaPeriodId.windowSequenceNumber && this.nextAdGroupIndex == mediaPeriodId.nextAdGroupIndex) {
return true;
}
return false;
}
public int hashCode() {
return ((((((((527 + this.periodUid.hashCode()) * 31) + this.adGroupIndex) * 31) + this.adIndexInAdGroup) * 31) + ((int) this.windowSequenceNumber)) * 31) + this.nextAdGroupIndex;
}
}
}
|
3e06019b46ed23fab7c5d2b9f0435796756b269a
| 1,827 |
java
|
Java
|
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/form/FormBodyResourceTest.java
|
iweiss/Resteasy
|
254e74f84806534f8a2b57cc73693428a2a9fcca
|
[
"Apache-2.0"
] | 841 |
2015-01-01T10:13:52.000Z
|
2021-09-17T03:41:49.000Z
|
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/form/FormBodyResourceTest.java
|
iweiss/Resteasy
|
254e74f84806534f8a2b57cc73693428a2a9fcca
|
[
"Apache-2.0"
] | 974 |
2015-01-23T02:42:23.000Z
|
2021-09-17T03:35:22.000Z
|
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/form/FormBodyResourceTest.java
|
iweiss/Resteasy
|
254e74f84806534f8a2b57cc73693428a2a9fcca
|
[
"Apache-2.0"
] | 747 |
2015-01-08T22:48:05.000Z
|
2021-09-02T15:56:08.000Z
| 37.285714 | 89 | 0.747126 | 2,535 |
package org.jboss.resteasy.test.form;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import jakarta.ws.rs.client.ClientBuilder;
import org.jboss.resteasy.test.form.resource.FormBodyResourceClient;
import org.jboss.resteasy.test.form.resource.FormBodyResourceForm;
import org.jboss.resteasy.test.form.resource.FormBodyResourceResource;
import org.jboss.resteasy.utils.PortProviderUtil;
import org.jboss.resteasy.utils.TestUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @tpSubChapter Form tests
* @tpChapter Integration tests
* @tpSince RESTEasy 3.0.16
*/
@RunWith(Arquillian.class)
@RunAsClient
public class FormBodyResourceTest {
@Deployment
public static Archive<?> createTestArchive() {
WebArchive war = TestUtil.prepareArchive(FormParameterTest.class.getSimpleName());
war.addClasses(FormBodyResourceClient.class);
war.addClasses(FormBodyResourceForm.class);
return TestUtil.finishContainerPrepare(war, null, FormBodyResourceResource.class);
}
/**
* @tpTestDetails Check body of form.
* @tpSince RESTEasy 3.0.16
*/
@Test
public void test() {
ResteasyClient client = (ResteasyClient)ClientBuilder.newClient();
FormBodyResourceClient proxy = client.target(
PortProviderUtil.generateBaseUrl(FormParameterTest.class.getSimpleName()))
.proxyBuilder(FormBodyResourceClient.class).build();
Assert.assertEquals("foo.gotIt", proxy.put("foo"));
client.close();
}
}
|
3e06026551821fea02cddc7eba1e9c32fea23ab0
| 10,028 |
java
|
Java
|
Databases Frameworks - Hibernate & Spring Data/Exercises JSON Processing/product-shop/src/main/java/json/processing/CmdRunner.java
|
Valentin9003/Java
|
9d263063685ba60ab75dc9efd25554b715a7980a
|
[
"Apache-2.0"
] | 1 |
2018-10-28T13:48:48.000Z
|
2018-10-28T13:48:48.000Z
|
Databases Frameworks - Hibernate & Spring Data/Exercises JSON Processing/product-shop/src/main/java/json/processing/CmdRunner.java
|
Valentin9003/Java
|
9d263063685ba60ab75dc9efd25554b715a7980a
|
[
"Apache-2.0"
] | null | null | null |
Databases Frameworks - Hibernate & Spring Data/Exercises JSON Processing/product-shop/src/main/java/json/processing/CmdRunner.java
|
Valentin9003/Java
|
9d263063685ba60ab75dc9efd25554b715a7980a
|
[
"Apache-2.0"
] | null | null | null | 43.411255 | 114 | 0.727962 | 2,536 |
package json.processing;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import json.processing.model.dto.binding.jsonBindingModels.CategoryBindingModel;
import json.processing.model.dto.binding.jsonBindingModels.ProductCreateBindingModel;
import json.processing.model.dto.binding.jsonBindingModels.UsersBindingModel;
import json.processing.model.dto.binding.xmlBindingModels.seedCategoriesBindingModels.CategorySeedDataWrapper;
import json.processing.model.dto.binding.xmlBindingModels.seedProductsBindingModels.ProductSeedDataDto;
import json.processing.model.dto.binding.xmlBindingModels.seedProductsBindingModels.ProductsSeedDataWrapper;
import json.processing.model.dto.binding.xmlBindingModels.seedUsersBindingModels.UsersSeedDataWrapper;
import json.processing.model.dto.view.jsonViewModels.CategoryByProductsCountViewModel;
import json.processing.model.dto.view.jsonViewModels.ProductInRangeViewModel;
import json.processing.model.dto.view.jsonViewModels.UserWithSoldItemViewModel;
import json.processing.model.dto.view.jsonViewModels.usersAndProductsQuery4.UsersViewModelWrapper;
import json.processing.model.dto.view.xmlViewModels.categoriesByProductsCountModel.CategoriesByProductCountWraper;
import json.processing.model.dto.view.xmlViewModels.productsInRangeModel.ProductInRangeWraper;
import json.processing.model.dto.view.xmlViewModels.successfullySoldProductsModel.UserWithSoldItemWrapper;
import json.processing.service.categoryService.CategoryService;
import json.processing.service.productService.ProductService;
import json.processing.service.userService.UserService;
import json.processing.util.io.FileIO;
import json.processing.util.serialize.Serializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.*;
@SuppressWarnings("ALL")
@Component
@Transactional
public class CmdRunner implements CommandLineRunner {
private static final String USERS_INPUT_JSON = "/files/input/json/users.json";
private static final String PRODUCTS_INPUT_JSON = "/files/input/json/products.json";
private static final String CATEGORIES_INPUT_JSON = "/files/input/json/categories.json";
private static final String OUTPUT_JSON_DIRECTORY_PATH = "src/main/resources/files/output/json/";
private static final String USERS_INPUT_XML = "/files/input/xml/users.xml";
private static final String PRODUCTS_INPUT_XML = "/files/input/xml/products.xml";
private static final String CATEGORIES_INPUT_XML = "/files/input/xml/categories.xml";
private static final String OUTPUT_XML_DIRECTORY_PATH = "src/main/resources/files/output/xml/";
private final Serializer serializerJson;
private final Serializer serializerXml;
private final UserService userService;
private final ProductService productService;
private final CategoryService categoryService;
private final FileIO fileIO;
private final Gson gson;
@Autowired
public CmdRunner(@Qualifier(value = "JsonSerializer") Serializer serializerJson,
@Qualifier(value = "XmlSerializer") Serializer serializerXml,
UserService userService,
ProductService productService,
CategoryService categoryService,
FileIO fileIO,
Gson gson) {
this.serializerJson = serializerJson;
this.serializerXml = serializerXml;
this.userService = userService;
this.productService = productService;
this.categoryService = categoryService;
this.fileIO = fileIO;
this.gson = gson;
}
@Override
public void run(String... args) throws Exception {
// seedDataIntoDbFromJson();
// queryAndExportDataJson();
// seedDataIntoDbFromXml();
queryAndExportDataXml();
}
private void queryAndExportDataXml() {
// productsInRangeQueryXML();
// successfullySoldProductsQueryXML();
// categoriesByProductsCountQueryXML();
usersAndProductsQueryXML();
}
private void usersAndProductsQueryXML() {
}
private void categoriesByProductsCountQueryXML() {
List<CategoryByProductsCountViewModel> categories = this.categoryService.categoriesByProductCount();
CategoriesByProductCountWraper viewModelWrapper = new CategoriesByProductCountWraper();
viewModelWrapper.setViewModelsList(categories);
this.serializerXml.serialize(viewModelWrapper, OUTPUT_XML_DIRECTORY_PATH + "categories-by-products.xml");
}
private void successfullySoldProductsQueryXML() {
List<UserWithSoldItemViewModel> viewModels = this.productService.getAllUsersQuery2();
UserWithSoldItemWrapper userWrapper = new UserWithSoldItemWrapper();
userWrapper.setViewModelWrapper(viewModels);
this.serializerXml.serialize(userWrapper, OUTPUT_XML_DIRECTORY_PATH + "users-sold-products.xml");
}
private void productsInRangeQueryXML() {
List<ProductInRangeViewModel> viewModels = this.productService.getAllByRangeWithoutBuyer(500, 1000);
ProductInRangeWraper viewModelWrapper = new ProductInRangeWraper();
viewModelWrapper.setViewModels(viewModels);
this.serializerXml.serialize(viewModelWrapper, OUTPUT_XML_DIRECTORY_PATH + "products-in-range.xml");
}
private void seedDataIntoDbFromXml() {
seedUsersXml();
seedCategoriesXml();
seedProductsXml();
}
private void seedCategoriesXml() {
CategorySeedDataWrapper categoryWrapper =
serializerXml.deserialize(CategorySeedDataWrapper.class, CATEGORIES_INPUT_XML);
this.categoryService.persisAllCategories(categoryWrapper);
}
private void seedProductsXml() {
ProductsSeedDataWrapper productWrapper =
serializerXml.deserialize(ProductsSeedDataWrapper.class, PRODUCTS_INPUT_XML);
productWrapper.getProductDtos().forEach(this::randomizeDataXml);
this.productService.persistAllProducts(productWrapper);
}
private void randomizeDataXml(ProductSeedDataDto model) {
Random random = new Random();
int buyer = 0;
do {
buyer = random.nextInt(69);
if (buyer <= 56 && buyer != 0) model.setBuyer(buyer);
} while (buyer == 0);
int seller = 0;
do {
seller = random.nextInt(56);
if (seller != buyer && seller != 0) {
model.setSeller(seller);
}
} while (seller == buyer || seller == 0);
}
private void seedUsersXml() {
UsersSeedDataWrapper userWrapper = serializerXml.deserialize(UsersSeedDataWrapper.class, USERS_INPUT_XML);
this.userService.persistAllUsers(userWrapper);
}
private void queryAndExportDataJson() throws IOException {
queryProductsInRange();
querySuccessfullySoldProducts();
queryCategoriesByProductsCount();
usersAndProducts();
}
private void usersAndProducts() {
UsersViewModelWrapper modelWrappers = this.userService.getAllUsersWithSoldProduct();
serializerJson.serialize(modelWrappers, OUTPUT_JSON_DIRECTORY_PATH + "users-and-products.json");
}
private void queryCategoriesByProductsCount() {
List<CategoryByProductsCountViewModel> categories = this.categoryService.categoriesByProductCount();
serializerJson.serialize(categories, OUTPUT_JSON_DIRECTORY_PATH + "categories-by-products.json");
}
private void querySuccessfullySoldProducts() {
List<UserWithSoldItemViewModel> viewModels = this.productService.getAllUsersQuery2();
serializerJson.serialize(viewModels, OUTPUT_JSON_DIRECTORY_PATH + "users-sold-products.json");
}
private void queryProductsInRange() {
List<ProductInRangeViewModel> viewModels = this.productService.getAllByRangeWithoutBuyer(500, 1000);
serializerJson.serialize(viewModels, OUTPUT_JSON_DIRECTORY_PATH + "products-in-range.json");
}
private void seedDataIntoDbFromJson() throws IOException {
seedUsers();
seedCategories();
seedProducts();
}
private void seedProducts() throws IOException {
String content = fileIO.read(PRODUCTS_INPUT_JSON);
Type listType = new TypeToken<List<ProductCreateBindingModel>>() {
}.getType();
List<ProductCreateBindingModel> products = this.gson.fromJson(content, listType);
products.forEach(this::randomizeData);
this.productService.persist(products);
}
private void randomizeData(ProductCreateBindingModel model) {
Random random = new Random();
int buyer = 0;
do {
buyer = random.nextInt(69);
if (buyer <= 56 && buyer != 0) model.setBuyer(buyer);
} while (buyer == 0);
int seller = 0;
do {
seller = random.nextInt(56);
if (seller != buyer && seller != 0) {
model.setSeller(seller);
}
} while (seller == buyer || seller == 0);
}
private void seedCategories() throws IOException {
String content = fileIO.read(CATEGORIES_INPUT_JSON);
CategoryBindingModel[] categories = gson.fromJson(content, CategoryBindingModel[].class);
Arrays.stream(categories).forEach(this.categoryService::persist);
}
private void seedUsers() throws IOException {
// UsersBindingModel[] usersDtos = serializerJson.deserialize(UsersBindingModel[].class, USERS_INPUT_JSON);
// String debug = "";
String content = fileIO.read(USERS_INPUT_JSON);
UsersBindingModel[] users = gson.fromJson(content, UsersBindingModel[].class);
Arrays.stream(users).forEach(this.userService::persist);
}
}
|
3e06026b6a694a78e482597c852e50ad24160a63
| 2,786 |
java
|
Java
|
giraph-core/src/main/java/org/apache/giraph/comm/netty/handler/MasterRequestServerHandler.java
|
rvs/giraph
|
7e48523b520afee8e727d1e1aaab801a3bd80f06
|
[
"ECL-2.0",
"Apache-2.0"
] | 10 |
2015-03-01T19:31:09.000Z
|
2018-02-28T07:55:05.000Z
|
giraph-core/src/main/java/org/apache/giraph/comm/netty/handler/MasterRequestServerHandler.java
|
rvs/giraph
|
7e48523b520afee8e727d1e1aaab801a3bd80f06
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
giraph-core/src/main/java/org/apache/giraph/comm/netty/handler/MasterRequestServerHandler.java
|
rvs/giraph
|
7e48523b520afee8e727d1e1aaab801a3bd80f06
|
[
"ECL-2.0",
"Apache-2.0"
] | 15 |
2015-03-01T19:31:11.000Z
|
2018-02-28T07:54:53.000Z
| 34.825 | 75 | 0.745154 | 2,537 |
/*
* 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.giraph.comm.netty.handler;
import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration;
import org.apache.giraph.comm.requests.MasterRequest;
import org.apache.giraph.master.MasterAggregatorHandler;
import org.apache.giraph.graph.TaskInfo;
/** Handler for requests on master */
public class MasterRequestServerHandler extends
RequestServerHandler<MasterRequest> {
/** Aggregator handler */
private final MasterAggregatorHandler aggregatorHandler;
/**
* Constructor
*
* @param workerRequestReservedMap Worker request reservation map
* @param conf Configuration
* @param myTaskInfo Current task info
* @param aggregatorHandler Master aggregator handler
*/
public MasterRequestServerHandler(
WorkerRequestReservedMap workerRequestReservedMap,
ImmutableClassesGiraphConfiguration conf,
TaskInfo myTaskInfo,
MasterAggregatorHandler aggregatorHandler) {
super(workerRequestReservedMap, conf, myTaskInfo);
this.aggregatorHandler = aggregatorHandler;
}
@Override
public void processRequest(MasterRequest request) {
request.doRequest(aggregatorHandler);
}
/**
* Factory for {@link MasterRequestServerHandler}
*/
public static class Factory implements RequestServerHandler.Factory {
/** Master aggregator handler */
private final MasterAggregatorHandler aggregatorHandler;
/**
* Constructor
*
* @param aggregatorHandler Master aggregator handler
*/
public Factory(MasterAggregatorHandler aggregatorHandler) {
this.aggregatorHandler = aggregatorHandler;
}
@Override
public RequestServerHandler newHandler(
WorkerRequestReservedMap workerRequestReservedMap,
ImmutableClassesGiraphConfiguration conf,
TaskInfo myTaskInfo) {
return new MasterRequestServerHandler(workerRequestReservedMap, conf,
myTaskInfo, aggregatorHandler);
}
}
}
|
3e06026d40d66ebe5cde4cc9bd1ce5722b83dc41
| 1,726 |
java
|
Java
|
src/main/java/com/covens/common/crafting/VanillaCrafting.java
|
zabi94/Covens-reborn
|
6fe956025ad47051e14e2e7c45893ddebc5c330a
|
[
"MIT"
] | 11 |
2019-01-02T17:22:55.000Z
|
2019-12-31T21:22:29.000Z
|
src/main/java/com/covens/common/crafting/VanillaCrafting.java
|
zabi94/Covens-reborn
|
6fe956025ad47051e14e2e7c45893ddebc5c330a
|
[
"MIT"
] | 66 |
2019-01-03T14:41:49.000Z
|
2021-02-24T17:47:24.000Z
|
src/main/java/com/covens/common/crafting/VanillaCrafting.java
|
zabi94/Covens-reborn
|
6fe956025ad47051e14e2e7c45893ddebc5c330a
|
[
"MIT"
] | 2 |
2019-04-17T09:52:23.000Z
|
2020-05-13T17:13:03.000Z
| 45.421053 | 120 | 0.80591 | 2,538 |
package com.covens.common.crafting;
import com.covens.common.block.ModBlocks;
import com.covens.common.block.natural.Gem;
import com.covens.common.item.ModItems;
import com.covens.common.item.ModMaterials;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
public final class VanillaCrafting {
private VanillaCrafting() {
}
public static void blocks() {
GameRegistry.addSmelting(ModBlocks.silver_ore, new ItemStack(ModItems.silver_ingot, 1), 0.35F);
GameRegistry.addSmelting(Blocks.SAPLING, new ItemStack(ModItems.wood_ash, 4), 0.15F);
GameRegistry.addSmelting(ModItems.silver_scales, new ItemStack(ModItems.silver_nugget, 1), 0.20F);
GameRegistry.addSmelting((new ItemStack(ModItems.unfired_jar)), new ItemStack(ModItems.empty_jar), 0.45F);
for (Gem g:Gem.values()) {
GameRegistry.addSmelting(new ItemStack(g.getOreBlock()), new ItemStack(g.getGemItem(), 4), 0.35F);
}
GameRegistry.addSmelting(new ItemStack((ModItems.golden_thread), 1, 0), new ItemStack(Items.GOLD_NUGGET, 1, 0), 1.0F);
ModMaterials.TOOL_ATHAME.setRepairItem(new ItemStack(ModItems.silver_ingot));
ModMaterials.ARMOR_SILVER.setRepairItem(new ItemStack(ModItems.silver_ingot));
ModMaterials.TOOL_SILVER.setRepairItem(new ItemStack(ModItems.silver_ingot));
ModMaterials.TOOL_COLD_IRON.setRepairItem(new ItemStack(ModItems.cold_iron_ingot));
ModMaterials.ARMOR_COLD_IRON.setRepairItem(new ItemStack(ModItems.cold_iron_ingot));
ModMaterials.ARMOR_WITCH_LEATHER.setRepairItem(new ItemStack(ModItems.witches_stitching));
ModMaterials.ARMOR_VAMPIRE.setRepairItem(new ItemStack(ModItems.sanguine_fabric));
}
}
|
3e06028aa12f96a629d0e5d13086f3b82cdcb78c
| 995 |
java
|
Java
|
taverna-workflowmodel-impl/src/main/java/org/apache/taverna/annotation/impl/DisputeEventDetails.java
|
apache/incubator-taverna-engine
|
7318b4319c5e63709c3ea3a3a918f02d3f299130
|
[
"Apache-2.0"
] | 19 |
2015-07-22T10:31:28.000Z
|
2021-11-10T19:40:24.000Z
|
taverna-workflowmodel-impl/src/main/java/org/apache/taverna/annotation/impl/DisputeEventDetails.java
|
apache/incubator-taverna-engine
|
7318b4319c5e63709c3ea3a3a918f02d3f299130
|
[
"Apache-2.0"
] | 1 |
2018-01-05T13:42:33.000Z
|
2018-01-05T13:42:33.000Z
|
taverna-workflowmodel-impl/src/main/java/org/apache/taverna/annotation/impl/DisputeEventDetails.java
|
apache/incubator-taverna-engine
|
7318b4319c5e63709c3ea3a3a918f02d3f299130
|
[
"Apache-2.0"
] | 17 |
2015-12-11T18:02:53.000Z
|
2022-03-06T10:51:17.000Z
| 35.535714 | 66 | 0.784925 | 2,539 |
/*
* 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.taverna.annotation.impl;
import org.apache.taverna.annotation.CurationEventBeanSPI;
public class DisputeEventDetails implements CurationEventBeanSPI {
public DisputeEventDetails() {
}
}
|
3e06038399e0e97854886f62f209ecb49c3eb818
| 2,072 |
java
|
Java
|
S04.03-Exercise-AddMapAndSharing/app/src/main/java/com/example/android/sunshine/DetailActivity.java
|
maneletorres/Sunshine
|
d2277b940f2438c2e0900235f860249f3cf06d2f
|
[
"Apache-2.0"
] | null | null | null |
S04.03-Exercise-AddMapAndSharing/app/src/main/java/com/example/android/sunshine/DetailActivity.java
|
maneletorres/Sunshine
|
d2277b940f2438c2e0900235f860249f3cf06d2f
|
[
"Apache-2.0"
] | null | null | null |
S04.03-Exercise-AddMapAndSharing/app/src/main/java/com/example/android/sunshine/DetailActivity.java
|
maneletorres/Sunshine
|
d2277b940f2438c2e0900235f860249f3cf06d2f
|
[
"Apache-2.0"
] | null | null | null | 32.888889 | 92 | 0.678571 | 2,540 |
package com.example.android.sunshine;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ShareCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private String mForecast;
private TextView mWeatherDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
mWeatherDisplay = (TextView) findViewById(R.id.tv_display_weather);
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity != null) {
if (intentThatStartedThisActivity.hasExtra(Intent.EXTRA_TEXT)) {
mForecast = intentThatStartedThisActivity.getStringExtra(Intent.EXTRA_TEXT);
mWeatherDisplay.setText(mForecast);
}
}
}
// TODO (3) Create a menu with an item with id of action_share
// TODO (4) Display the menu and implement the forecast sharing functionality
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.details, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_share) {
createShareForecastIntent();
return true;
}
return super.onOptionsItemSelected(item);
}
private void createShareForecastIntent() {
Intent intent = ShareCompat.IntentBuilder.from(this)
.setType("text/plain")
.setText(mForecast + FORECAST_SHARE_HASHTAG)
.setChooserTitle("Share Weather Details")
.createChooserIntent();
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
|
3e06039294a53ea25862ed2b17c0b3e5ecaa4e10
| 668 |
java
|
Java
|
src/main/java/org/kyojo/schemaOrg/m3n3/doma/pending/clazz/AdvertiserContentArticleConverter.java
|
covernorgedi/nagoyakaICT
|
b375db53216eaa54f9797549a36e7c79f66b44c0
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/kyojo/schemaOrg/m3n3/doma/pending/clazz/AdvertiserContentArticleConverter.java
|
covernorgedi/nagoyakaICT
|
b375db53216eaa54f9797549a36e7c79f66b44c0
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/kyojo/schemaOrg/m3n3/doma/pending/clazz/AdvertiserContentArticleConverter.java
|
covernorgedi/nagoyakaICT
|
b375db53216eaa54f9797549a36e7c79f66b44c0
|
[
"Apache-2.0"
] | null | null | null | 29.043478 | 109 | 0.838323 | 2,541 |
package org.kyojo.schemaOrg.m3n3.doma.pending.clazz;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaOrg.m3n3.pending.impl.ADVERTISER_CONTENT_ARTICLE;
import org.kyojo.schemaOrg.m3n3.pending.Clazz.AdvertiserContentArticle;
@ExternalDomain
public class AdvertiserContentArticleConverter implements DomainConverter<AdvertiserContentArticle, String> {
@Override
public String fromDomainToValue(AdvertiserContentArticle domain) {
return domain.getNativeValue();
}
@Override
public AdvertiserContentArticle fromValueToDomain(String value) {
return new ADVERTISER_CONTENT_ARTICLE(value);
}
}
|
3e0604680524b51c1d59a87758e5164f90ecca3c
| 534 |
java
|
Java
|
easy_youtube_library/src/main/java/net/anapsil/easyyoutubelibrary/api/errors/YouTubeErrorHandler.java
|
anapsil/easy_youtube
|
ea6482920fc1d4218bf700de8e8516cd87bf11f9
|
[
"Apache-2.0"
] | 5 |
2015-07-15T12:49:11.000Z
|
2015-08-22T22:06:05.000Z
|
easy_youtube_library/src/main/java/net/anapsil/easyyoutubelibrary/api/errors/YouTubeErrorHandler.java
|
anapsil/easy_youtube
|
ea6482920fc1d4218bf700de8e8516cd87bf11f9
|
[
"Apache-2.0"
] | null | null | null |
easy_youtube_library/src/main/java/net/anapsil/easyyoutubelibrary/api/errors/YouTubeErrorHandler.java
|
anapsil/easy_youtube
|
ea6482920fc1d4218bf700de8e8516cd87bf11f9
|
[
"Apache-2.0"
] | null | null | null | 28.105263 | 74 | 0.685393 | 2,542 |
package net.anapsil.easyyoutubelibrary.api.errors;
import retrofit.ErrorHandler;
import retrofit.RetrofitError;
/**
* Created by ana.silva on 02/07/15.
*/
public class YouTubeErrorHandler implements ErrorHandler {
@Override
public Throwable handleError(RetrofitError cause) {
if (cause.getKind() == RetrofitError.Kind.NETWORK) {
return new NetworkError(cause.getMessage(), cause.getCause());
} else {
return new YouTubeError(cause.getMessage(), cause.getCause());
}
}
}
|
3e0606351a1216f3b6db372cf27682236b1dc771
| 2,202 |
java
|
Java
|
documents/课程文档/10.软工/第11组——博影--娱乐票务平台/项目源码/后端/boying/boying-admin/src/main/java/com/tongji/boying/controller/UmsLoginController.java
|
tongji4m3/boying
|
1901685eb549207f9cbf2ae79869dadbf2ceb985
|
[
"MIT"
] | 22 |
2020-10-09T09:05:47.000Z
|
2022-02-08T03:29:32.000Z
|
documents/课程文档/10.软工/第11组——博影--娱乐票务平台/项目源码/后端/boying/boying-admin/src/main/java/com/tongji/boying/controller/UmsLoginController.java
|
tongji4m3/community
|
1901685eb549207f9cbf2ae79869dadbf2ceb985
|
[
"MIT"
] | null | null | null |
documents/课程文档/10.软工/第11组——博影--娱乐票务平台/项目源码/后端/boying/boying-admin/src/main/java/com/tongji/boying/controller/UmsLoginController.java
|
tongji4m3/community
|
1901685eb549207f9cbf2ae79869dadbf2ceb985
|
[
"MIT"
] | 11 |
2020-11-04T12:14:10.000Z
|
2021-09-16T08:17:46.000Z
| 36.098361 | 81 | 0.760672 | 2,543 |
package com.tongji.boying.controller;
import com.tongji.boying.common.api.CommonResult;
import com.tongji.boying.dto.adminParam.AdminInfo;
import com.tongji.boying.dto.adminParam.LoginReturn;
import com.tongji.boying.dto.adminParam.UsernameLoginParam;
import com.tongji.boying.model.BoyingAdmin;
import com.tongji.boying.service.UmsAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.security.Principal;
/**
* 后台管理员登录相关,是所有管理员都能访问的板块
*/
@Controller
@Api(tags = "UmsLoginController", description = "后台管理员登录相关")
@RequestMapping("/login")
public class UmsLoginController {
@Value("${jwt.tokenHead}")
private String tokenHead;
@Autowired
private UmsAdminService adminService;
@ApiOperation(value = "登录以后返回token")
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public CommonResult login(@Validated @RequestBody UsernameLoginParam param) {
String token = adminService.login(param);
return CommonResult.success(new LoginReturn(token, tokenHead));
}
@ApiOperation(value = "获取管理员信息")
@RequestMapping(value = "/info", method = RequestMethod.POST)
@ResponseBody
public CommonResult<AdminInfo> info(Principal principal) {
/**
防止直接查询时报错
*/
if (principal == null) return CommonResult.unauthorized(null);
BoyingAdmin currentAdmin = adminService.getCurrentAdmin();
AdminInfo adminInfo = new AdminInfo();
adminInfo.setIcon(currentAdmin.getIcon());
adminInfo.setLastTime(currentAdmin.getLastTime());
adminInfo.setUsername(currentAdmin.getUsername());
return CommonResult.success(adminInfo);
}
}
|
3e060662aff3c3d4eb0f0a9f0a34acce0c7d501c
| 964 |
java
|
Java
|
user-interface/src/test/java/ksch/LogoutTest.java
|
jmewes/ksch-workflows
|
3894fb8788dd7bd2293a5eae500daf388bbb54a1
|
[
"Apache-2.0"
] | 10 |
2018-03-05T04:16:10.000Z
|
2021-09-18T15:41:53.000Z
|
user-interface/src/test/java/ksch/LogoutTest.java
|
jmewes/ksch-workflows
|
3894fb8788dd7bd2293a5eae500daf388bbb54a1
|
[
"Apache-2.0"
] | 35 |
2018-02-06T20:48:50.000Z
|
2020-01-16T04:51:41.000Z
|
user-interface/src/test/java/ksch/LogoutTest.java
|
jmewes/ksch-workflows
|
3894fb8788dd7bd2293a5eae500daf388bbb54a1
|
[
"Apache-2.0"
] | 10 |
2018-02-18T17:39:57.000Z
|
2021-02-04T17:18:35.000Z
| 28.352941 | 75 | 0.719917 | 2,544 |
/*
* Copyright 2019 KS-plus e.V.
*
* 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 ksch;
import ksch.registration.RegistrationDashboard;
import org.junit.Test;
public class LogoutTest extends WebPageTest {
@Test
public void should_log_out_user() {
login("user", "pwd");
tester.startPage(Logout.class);
tester.startPage(RegistrationDashboard.class);
tester.assertRenderedPage(Login.class);
}
}
|
3e060693ec8ebc67f9c6b2d1878bb7b3110c62b6
| 5,736 |
java
|
Java
|
sample/peas/core/src/forplay/sample/peas/core/PeaWorld.java
|
billy93/forplay
|
e00729bef2d861031467889a4e5cc126135b16b5
|
[
"Apache-2.0"
] | 5 |
2015-01-08T04:48:34.000Z
|
2020-03-30T07:09:18.000Z
|
sample/peas/core/src/forplay/sample/peas/core/PeaWorld.java
|
pyricau/forplay-clone-pyricau
|
f90fe976e9782ec10ac243523c4744c56b751c1b
|
[
"Apache-2.0"
] | null | null | null |
sample/peas/core/src/forplay/sample/peas/core/PeaWorld.java
|
pyricau/forplay-clone-pyricau
|
f90fe976e9782ec10ac243523c4744c56b751c1b
|
[
"Apache-2.0"
] | 1 |
2019-04-23T02:44:09.000Z
|
2019-04-23T02:44:09.000Z
| 32.40678 | 92 | 0.714784 | 2,545 |
/**
* Copyright 2011 The ForPlay 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 forplay.sample.peas.core;
import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.callbacks.ContactListener;
import org.jbox2d.callbacks.DebugDraw;
import org.jbox2d.collision.Manifold;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;
import org.jbox2d.dynamics.contacts.Contact;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import static forplay.core.ForPlay.graphics;
import forplay.core.CanvasLayer;
import forplay.core.DebugDrawBox2D;
import forplay.core.GroupLayer;
import forplay.sample.peas.core.entities.Entity;
import forplay.sample.peas.core.entities.PhysicsEntity;
public class PeaWorld implements ContactListener {
public GroupLayer staticLayerBack;
public GroupLayer dynamicLayer;
public GroupLayer staticLayerFront;
// size of world
private static int width = 24;
private static int height = 18;
// box2d object containing physics world
protected World world;
private List<Entity> entities = new ArrayList<Entity>(0);
private HashMap<Body, PhysicsEntity> bodyEntityLUT = new HashMap<Body, PhysicsEntity>();
private Stack<Contact> contacts = new Stack<Contact>();
private static boolean showDebugDraw = false;
private DebugDrawBox2D debugDraw;
public PeaWorld(GroupLayer scaledLayer) {
staticLayerBack = graphics().createGroupLayer();
scaledLayer.add(staticLayerBack);
dynamicLayer = graphics().createGroupLayer();
scaledLayer.add(dynamicLayer);
staticLayerFront = graphics().createGroupLayer();
scaledLayer.add(staticLayerFront);
// create the physics world
Vec2 gravity = new Vec2(0.0f, 10.0f);
world = new World(gravity, true);
world.setWarmStarting(true);
world.setAutoClearForces(true);
world.setContactListener(this);
// create the ground
Body ground = world.createBody(new BodyDef());
PolygonShape groundShape = new PolygonShape();
groundShape.setAsEdge(new Vec2(0, height), new Vec2(width, height));
ground.createFixture(groundShape, 0.0f);
// create the walls
Body wallLeft = world.createBody(new BodyDef());
PolygonShape wallLeftShape = new PolygonShape();
wallLeftShape.setAsEdge(new Vec2(0, 0), new Vec2(0, height));
wallLeft.createFixture(wallLeftShape, 0.0f);
Body wallRight = world.createBody(new BodyDef());
PolygonShape wallRightShape = new PolygonShape();
wallRightShape.setAsEdge(new Vec2(width, 0), new Vec2(width, height));
wallRight.createFixture(wallRightShape, 0.0f);
if (showDebugDraw) {
CanvasLayer canvasLayer =
graphics().createCanvasLayer((int) (width / Peas.physUnitPerScreenUnit),
(int) (height / Peas.physUnitPerScreenUnit));
graphics().rootLayer().add(canvasLayer);
debugDraw = new DebugDrawBox2D();
debugDraw.setCanvas(canvasLayer);
debugDraw.setFlipY(false);
debugDraw.setStrokeAlpha(150);
debugDraw.setFillAlpha(75);
debugDraw.setStrokeWidth(2.0f);
debugDraw.setFlags(DebugDraw.e_shapeBit | DebugDraw.e_jointBit | DebugDraw.e_aabbBit);
debugDraw.setCamera(0, 0, 1f / Peas.physUnitPerScreenUnit);
world.setDebugDraw(debugDraw);
}
}
public void update(float delta) {
for (Entity e : entities) {
e.update(delta);
}
// the step delta is fixed so box2d isn't affected by framerate
world.step(0.033f, 10, 10);
processContacts();
}
public void paint(float delta) {
if (showDebugDraw) {
debugDraw.getCanvas().canvas().clear();
world.drawDebugData();
}
for (Entity e : entities) {
e.paint(delta);
}
}
public void add(Entity entity) {
entities.add(entity);
if (entity instanceof PhysicsEntity) {
PhysicsEntity physicsEntity = (PhysicsEntity) entity;
bodyEntityLUT.put(physicsEntity.getBody(), physicsEntity);
}
}
// handle contacts out of physics loop
public void processContacts() {
while (!contacts.isEmpty()) {
Contact contact = contacts.pop();
// handle collision
PhysicsEntity entityA = bodyEntityLUT.get(contact.m_fixtureA.m_body);
PhysicsEntity entityB = bodyEntityLUT.get(contact.m_fixtureB.m_body);
if (entityA != null && entityB != null) {
if (entityA instanceof PhysicsEntity.HasContactListener) {
((PhysicsEntity.HasContactListener) entityA).contact(entityB);
}
if (entityB instanceof PhysicsEntity.HasContactListener) {
((PhysicsEntity.HasContactListener) entityB).contact(entityA);
}
}
}
}
// Box2d's begin contact
@Override
public void beginContact(Contact contact) {
contacts.push(contact);
}
// Box2d's end contact
@Override
public void endContact(Contact contact) {
}
// Box2d's pre solve
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
// Box2d's post solve
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
}
|
3e0606aebe372ad96eb9f8e3461faa3991acc197
| 11,771 |
java
|
Java
|
source code/CostFed/costfed/src/main/java/org/aksw/simba/quetsal/startup/Queries.java
|
dice-group/CostBased-FedEval
|
eb7b6a6972a53cc774be53362fe6dcfba4dadf28
|
[
"Apache-2.0"
] | null | null | null |
source code/CostFed/costfed/src/main/java/org/aksw/simba/quetsal/startup/Queries.java
|
dice-group/CostBased-FedEval
|
eb7b6a6972a53cc774be53362fe6dcfba4dadf28
|
[
"Apache-2.0"
] | null | null | null |
source code/CostFed/costfed/src/main/java/org/aksw/simba/quetsal/startup/Queries.java
|
dice-group/CostBased-FedEval
|
eb7b6a6972a53cc774be53362fe6dcfba4dadf28
|
[
"Apache-2.0"
] | 4 |
2019-05-25T15:50:45.000Z
|
2020-04-05T14:22:18.000Z
| 51.854626 | 172 | 0.610653 | 2,546 |
package org.aksw.simba.quetsal.startup;
import java.util.ArrayList;
import java.util.List;
public class Queries {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* Get FedBench Queries
* @return List of queries
*/
public static List<String> getFedBenchQueries() {
List<String> queries = new ArrayList<String> ();
String CD1 = "SELECT ?predicate ?object \n" //cd1 of fedbench
+ "WHERE \n"
+ " { \n" +
" { \n"
+ " <http://dbpedia.org/resource/Barack_Obama> ?predicate ?object . \n"
+ " }\n" +
" UNION \n " +
" { \n"
+ " ?subject <http://www.w3.org/2002/07/owl#sameAs> <http://dbpedia.org/resource/Barack_Obama> .\n" +
" ?subject ?predicate ?object .\n"
+ " } \n " +
"}";
String CD2 = "SELECT ?party ?page WHERE { \n" + //cd2
" <http://dbpedia.org/resource/Barack_Obama> <http://dbpedia.org/ontology/party> ?party .\n" +
" ?x <http://data.nytimes.com/elements/topicPage> ?page .\n" +
"?x <http://www.w3.org/2002/07/owl#sameAs> <http://dbpedia.org/resource/Barack_Obama> .\n"+
"}";
String CD3 = "SELECT ?president ?party ?page WHERE { \n" + //cd3
"?president <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/President> .\n" +
"?president <http://dbpedia.org/ontology/nationality> <http://dbpedia.org/resource/United_States> .\n" +
"?president <http://dbpedia.org/ontology/party> ?party .\n" +
"?x <http://data.nytimes.com/elements/topicPage> ?page .\n" +
"?x <http://www.w3.org/2002/07/owl#sameAs> ?president .\n" +
"}";
String CD4 = "SELECT ?actor ?news WHERE {\n"+ //cd4
"?film <http://purl.org/dc/terms/title> \"Tarzan\" .\n"+
"?film <http://data.linkedmdb.org/resource/movie/actor> ?actor .\n"+
"?actor <http://www.w3.org/2002/07/owl#sameAs> ?x .\n"+
"?y <http://www.w3.org/2002/07/owl#sameAs> ?x .\n"+
"?y <http://data.nytimes.com/elements/topicPage> ?news . \n"+
"}";
String CD5 = "SELECT ?film ?director ?genre WHERE {\n"+ //cd5
"?film <http://dbpedia.org/ontology/director> ?director .\n"+
"?director <http://dbpedia.org/ontology/nationality> <http://dbpedia.org/resource/Italy> .\n"+
"?x <http://www.w3.org/2002/07/owl#sameAs> ?film .\n"+
"?x <http://data.linkedmdb.org/resource/movie/genre> ?genre .\n"+
"}";
String CD6 = "SELECT ?name ?location WHERE {\n"+ //cd 6
"?artist <http://xmlns.com/foaf/0.1/name> ?name .\n"+
"?artist <http://xmlns.com/foaf/0.1/based_near> ?location .\n"+
"?location <http://www.geonames.org/ontology#parentFeature> ?germany .\n"+
"?germany <http://www.geonames.org/ontology#name> \"Federal Republic of Germany\" .\n"+
"}";
String CD7= "SELECT ?location ?news WHERE {\n"+ //cd7
"?location <http://www.geonames.org/ontology#parentFeature> ?parent .\n"+
"?parent <http://www.geonames.org/ontology#name> \"California\" .\n"+
"?y <http://www.w3.org/2002/07/owl#sameAs> ?location .\n"+
"?y <http://data.nytimes.com/elements/topicPage> ?news . \n "+
"}";
//-----------------------------------------LS queries of FedBench-----------------------------------
String LS1 = "SELECT ?drug ?melt WHERE {\n"+ //LS1
"{ ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/meltingPoint> ?melt . }\n"+
" UNION"+
" { ?drug <http://dbpedia.org/ontology/Drug/meltingPoint> ?melt . \n}"+
"}";
String LS2 = "SELECT ?predicate ?object WHERE {\n"+ //LS2
"{ <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugs/DB00201> ?predicate ?object . }\n"+
"UNION "+
"{ <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugs/DB00201> <http://www.w3.org/2002/07/owl#sameAs> ?caff .\n"+
" ?caff ?predicate ?object . } \n"+
"}";
String LS3 = "SELECT ?Drug ?IntDrug ?IntEffect WHERE { \n"+ //LS3
" ?Drug <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Drug> .\n"+
" ?y <http://www.w3.org/2002/07/owl#sameAs> ?Drug .\n"+
" ?Int <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/interactionDrug1> ?y .\n"+
" ?Int <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/interactionDrug2> ?IntDrug .\n"+
" ?Int <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/text> ?IntEffect . \n"+
"}";
String LS4 = "SELECT ?drugDesc ?cpd ?equation WHERE {\n"+ //LS4
"?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/drugCategory> <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugcategory/cathartics> .\n"+
" ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/keggCompoundId> ?cpd .\n"+
" ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/description> ?drugDesc .\n"+
" ?enzyme <http://bio2rdf.org/ns/kegg#xSubstrate> ?cpd .\n"+
"?enzyme <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://bio2rdf.org/ns/kegg#Enzyme> .\n"+
"?reaction <http://bio2rdf.org/ns/kegg#xEnzyme> ?enzyme .\n"+
"?reaction <http://bio2rdf.org/ns/kegg#equation> ?equation . \n"+
"}";
String LS5 = "SELECT ?drug ?keggUrl ?chebiImage WHERE {\n"+ //LS5
"?drug <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/drugs> .\n"+
" ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/keggCompoundId> ?keggDrug .\n"+
" ?keggDrug <http://bio2rdf.org/ns/bio2rdf#url> ?keggUrl .\n"+
" ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/genericName> ?drugBankName .\n"+
" ?chebiDrug <http://purl.org/dc/elements/1.1/title> ?drugBankName .\n"+
" ?chebiDrug <http://bio2rdf.org/ns/bio2rdf#image> ?chebiImage .\n"+
"}" ;
String LS6 = "SELECT ?drug ?title WHERE {\n "+ //LS6
"?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/drugCategory> <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugcategory/micronutrient> .\n"+
" ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/casRegistryNumber> ?id .\n"+
" ?keggDrug <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://bio2rdf.org/ns/kegg#Drug> .\n"+
" ?keggDrug <http://bio2rdf.org/ns/bio2rdf#xRef> ?id .\n"+
" ?keggDrug <http://purl.org/dc/elements/1.1/title> ?title .\n"+
"}";
String LS7 = "SELECT ?drug ?transform ?mass WHERE { \n "+ //LS7
"{ ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/affectedOrganism> \"Humans and other mammals\" .\n"+
" ?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/casRegistryNumber> ?cas .\n"+
" ?keggDrug <http://bio2rdf.org/ns/bio2rdf#xRef> ?cas .\n"+
" ?keggDrug <http://bio2rdf.org/ns/bio2rdf#mass> ?mass . \n"+
" } "+
"}";
//------------------------------------ld-----------------------------------
String ld1 = "SELECT * WHERE { \n"+
"?paper <http://data.semanticweb.org/ns/swc/ontology#isPartOf> <http://data.semanticweb.org/conference/iswc/2008/poster_demo_proceedings> .\n"+
"?paper <http://swrc.ontoware.org/ontology#author> ?p .\n"+
"?p <http://www.w3.org/2000/01/rdf-schema#label> ?n .\n"+
"}";
//queries.add(ld1);
String ld2 = "SELECT * WHERE {\n" +
"?proceedings <http://data.semanticweb.org/ns/swc/ontology#relatedToEvent> <http://data.semanticweb.org/conference/eswc/2010> .\n" +
"?paper <http://data.semanticweb.org/ns/swc/ontology#isPartOf> ?proceedings .\n" +
"?paper <http://swrc.ontoware.org/ontology#author> ?p .\n" +
"}";
//queries.add(ld2);
String ld3 ="SELECT * WHERE {\n" +
"?paper <http://data.semanticweb.org/ns/swc/ontology#isPartOf> <http://data.semanticweb.org/conference/iswc/2008/poster_demo_proceedings> .\n" +
"?paper <http://swrc.ontoware.org/ontology#author> ?p .\n" +
"?p <http://www.w3.org/2002/07/owl#sameAs> ?x .\n" +
"?p <http://www.w3.org/2000/01/rdf-schema#label> ?n .\n" +
"}";
//queries.add(ld3);
String ld4 = "SELECT * WHERE {\n" +
"?role <http://data.semanticweb.org/ns/swc/ontology#isRoleAt> <http://data.semanticweb.org/conference/eswc/2010> .\n" +
"?role <http://data.semanticweb.org/ns/swc/ontology#heldBy> ?p .\n" +
"?paper <http://swrc.ontoware.org/ontology#author> ?p .\n" +
"?paper <http://data.semanticweb.org/ns/swc/ontology#isPartOf> ?proceedings .\n" +
"?proceedings <http://data.semanticweb.org/ns/swc/ontology#relatedToEvent> <http://data.semanticweb.org/conference/eswc/2010> .\n" +
"}";
//queries.add(ld4);
String ld5 = "SELECT * WHERE {\n" +
"?a <http://dbpedia.org/ontology/artist> <http://dbpedia.org/resource/Michael_Jackson> .\n" +
"?a <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Album> .\n" +
"?a <http://xmlns.com/foaf/0.1/name> ?n .\n" +
"}";
//queries.add(ld5);
String ld6 = "SELECT * WHERE {\n" +
"?director <http://dbpedia.org/ontology/nationality> <http://dbpedia.org/resource/Italy> .\n" +
"?film <http://dbpedia.org/ontology/director> ?director .\n" +
"?x <http://www.w3.org/2002/07/owl#sameAs> ?film .\n" +
"?x <http://xmlns.com/foaf/0.1/based_near> ?y .\n" +
"?y <http://www.geonames.org/ontology#officialName> ?n .\n" +
"}";
//queries.add(ld6);
String ld7 = "SELECT * WHERE {\n" +
"?x <http://www.geonames.org/ontology#parentFeature> <http://sws.geonames.org/2921044/> .\n" +
"?x <http://www.geonames.org/ontology#name> ?n .\n" +
"}";
//queries.add(ld7);
String ld8 =
"SELECT * WHERE {\n" +
"?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/drugCategory> <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugcategory/micronutrient> .\n" +
"?drug <http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/casRegistryNumber> ?id .\n" +
"?drug <http://www.w3.org/2002/07/owl#sameAs> ?s .\n" +
"?s <http://xmlns.com/foaf/0.1/name> ?o .\n" +
"?s <http://www.w3.org/2004/02/skos/core#subject> ?sub .\n" +
"}";
//queries.add(ld8);
String ld9 =
"SELECT * WHERE {\n" +
"?x <http://www.w3.org/2004/02/skos/core#subject> <http://dbpedia.org/resource/Category:FIFA_World_Cup-winning_countries> .\n" +
"?p <http://dbpedia.org/ontology/managerClub> ?x .\n" +
"?p <http://xmlns.com/foaf/0.1/name> \"Luiz Felipe Scolari\"@en . \n" +
"}";
//queries.add(ld9);
String ld10 =
"SELECT * WHERE {\n" +
"?n <http://www.w3.org/2004/02/skos/core#subject> <http://dbpedia.org/resource/Category:Chancellors_of_Germany> .\n" +
"?n <http://www.w3.org/2002/07/owl#sameAs> ?p2 .\n" +
"?p2 <http://data.nytimes.com/elements/latest_use> ?u .\n" +
"}";
//queries.add(ld10);
String ld11 =
"SELECT * WHERE {\n" +
"?x <http://dbpedia.org/ontology/team> <http://dbpedia.org/resource/Eintracht_Frankfurt> .\n" +
"?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#label> ?y .\n" +
"?x <http://dbpedia.org/ontology/birthDate> ?d .\n" +
"?x <http://dbpedia.org/ontology/birthPlace> ?p .\n" +
"?p <http://www.w3.org/1999/02/22-rdf-syntax-ns#label> ?l .\n" +
"} ";
queries.add(CD1);
queries.add(CD2);
// queries.add(CD3);
// queries.add(CD4);
// queries.add(CD5);
// queries.add(CD6);
// queries.add(CD7);
// queries.add(LS1);
// queries.add(LS2);
// queries.add(LS3);
// queries.add(LS4);
//queries.add(LS5);
// queries.add(LS6);
// queries.add(LS7);
// queries.add(ld1);
// queries.add(ld2);
// queries.add(ld3);
// queries.add(ld4);
// queries.add(ld5);
queries.add(ld6);
// queries.add(ld7);
// queries.add(ld8);
// queries.add(ld9);
// queries.add(ld10);
// queries.add(ld11);
return queries;
}
}
|
3e0606f2523002aac38470022bc91f4cf3e341c9
| 180 |
java
|
Java
|
Dataset/Leetcode/test/58/541.java
|
kkcookies99/UAST
|
fff81885aa07901786141a71e5600a08d7cb4868
|
[
"MIT"
] | null | null | null |
Dataset/Leetcode/test/58/541.java
|
kkcookies99/UAST
|
fff81885aa07901786141a71e5600a08d7cb4868
|
[
"MIT"
] | null | null | null |
Dataset/Leetcode/test/58/541.java
|
kkcookies99/UAST
|
fff81885aa07901786141a71e5600a08d7cb4868
|
[
"MIT"
] | null | null | null | 20 | 52 | 0.522222 | 2,547 |
class Solution {
public int XXX(String s) {
s = s.trim();
String[] strings = s.trim().split(" ");
return strings[strings.length - 1].length();
}
}
|
3e060749e2777f1fbd96676e8284a29244170309
| 290 |
java
|
Java
|
src/main/java/com/spring/insight/api/cases/web/rest/errors/LoginAlreadyUsedException.java
|
yousefexperts/CloudServerUpgraded
|
1b25590339b70997585bee3f37f887f531c25746
|
[
"MIT"
] | null | null | null |
src/main/java/com/spring/insight/api/cases/web/rest/errors/LoginAlreadyUsedException.java
|
yousefexperts/CloudServerUpgraded
|
1b25590339b70997585bee3f37f887f531c25746
|
[
"MIT"
] | 22 |
2020-03-04T23:39:29.000Z
|
2022-03-31T21:43:22.000Z
|
src/main/java/com/spring/insight/api/cases/web/rest/errors/LoginAlreadyUsedException.java
|
yousefexperts/CloudServerUpgraded
|
1b25590339b70997585bee3f37f887f531c25746
|
[
"MIT"
] | 2 |
2020-07-31T22:25:48.000Z
|
2022-01-09T12:19:55.000Z
| 32.222222 | 110 | 0.775862 | 2,548 |
package com.spring.insight.api.cases.web.rest.errors;
public class LoginAlreadyUsedException extends BadRequestAlertException {
public LoginAlreadyUsedException() {
super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login already in use", "userManagement", "userexists");
}
}
|
3e06076da423d4cffaf213d7459fb1821cb49934
| 488 |
java
|
Java
|
taotao-common/src/test/java/com/taotao/common/utils/FastdfsTest.java
|
liuhang93/taotao
|
9f2771a0c2c6fc066fa611386bd4b436079e2adb
|
[
"Apache-2.0"
] | 1 |
2018-11-21T06:10:43.000Z
|
2018-11-21T06:10:43.000Z
|
taotao-common/src/test/java/com/taotao/common/utils/FastdfsTest.java
|
liuhang93/taotao
|
9f2771a0c2c6fc066fa611386bd4b436079e2adb
|
[
"Apache-2.0"
] | null | null | null |
taotao-common/src/test/java/com/taotao/common/utils/FastdfsTest.java
|
liuhang93/taotao
|
9f2771a0c2c6fc066fa611386bd4b436079e2adb
|
[
"Apache-2.0"
] | null | null | null | 25.684211 | 86 | 0.723361 | 2,549 |
package com.taotao.common.utils;
import org.csource.common.MyException;
import org.junit.Test;
import java.io.IOException;
/**
* Created by liuhang on 2017/2/28.
*/
public class FastdfsTest {
@Test
public void testFastfsClient() throws IOException, MyException {
FastdfsClient client = new FastdfsClient("properties/fastdfs.conf");
String uploadFile=client.uploadFile("/Users/liuhang/Pictures/weichatPay.png");
System.out.println(uploadFile);
}
}
|
3e060776339415cf18d35f08dbd5b8e8c9dc08eb
| 23,630 |
java
|
Java
|
app/src/main/java/org/wikipedia/main/MainFragment.java
|
uniqx/apps-android-wikipedia
|
bf06da540acc030fa95dbacbb861d38c78f705cf
|
[
"Apache-2.0"
] | 1 |
2020-02-05T18:51:45.000Z
|
2020-02-05T18:51:45.000Z
|
app/src/main/java/org/wikipedia/main/MainFragment.java
|
felixyf0124/FandroidsWiki
|
059ef7331e5ba07f6d774239380b9992d5b5d173
|
[
"Apache-2.0"
] | 3 |
2020-07-16T17:23:26.000Z
|
2021-05-08T03:13:29.000Z
|
app/src/main/java/org/wikipedia/main/MainFragment.java
|
felixyf0124/FandroidsWiki
|
059ef7331e5ba07f6d774239380b9992d5b5d173
|
[
"Apache-2.0"
] | 1 |
2020-01-31T08:34:59.000Z
|
2020-01-31T08:34:59.000Z
| 41.383538 | 151 | 0.687008 | 2,550 |
package org.wikipedia.main;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.apache.commons.lang3.StringUtils;
import org.wikipedia.BackPressedHandler;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.FragmentUtil;
import org.wikipedia.analytics.GalleryFunnel;
import org.wikipedia.analytics.IntentFunnel;
import org.wikipedia.analytics.LoginFunnel;
import org.wikipedia.feed.FeedFragment;
import org.wikipedia.feed.image.FeaturedImage;
import org.wikipedia.feed.image.FeaturedImageCard;
import org.wikipedia.feed.mainpage.MainPageClient;
import org.wikipedia.feed.news.NewsActivity;
import org.wikipedia.feed.news.NewsItemCard;
import org.wikipedia.feed.view.HorizontalScrollingListCardItemView;
import org.wikipedia.gallery.GalleryActivity;
import org.wikipedia.gallery.ImagePipelineBitmapGetter;
import org.wikipedia.gallery.MediaDownloadReceiver;
import org.wikipedia.history.HistoryEntry;
import org.wikipedia.history.HistoryFragment;
import org.wikipedia.login.LoginActivity;
import org.wikipedia.main.floatingqueue.FloatingQueueView;
import org.wikipedia.navtab.NavTab;
import org.wikipedia.navtab.NavTabFragmentPagerAdapter;
import org.wikipedia.navtab.NavTabLayout;
import org.wikipedia.nearby.NearbyFragment;
import org.wikipedia.page.ExclusiveBottomSheetPresenter;
import org.wikipedia.page.PageActivity;
import org.wikipedia.page.PageTitle;
import org.wikipedia.page.linkpreview.LinkPreviewDialog;
import org.wikipedia.page.tabs.TabActivity;
import org.wikipedia.random.RandomActivity;
import org.wikipedia.readinglist.AddToReadingListDialog;
import org.wikipedia.search.SearchFragment;
import org.wikipedia.search.SearchInvokeSource;
import org.wikipedia.settings.Prefs;
import org.wikipedia.util.ClipboardUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.PermissionUtil;
import org.wikipedia.util.ShareUtil;
import org.wikipedia.util.log.L;
import java.io.File;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnPageChange;
import butterknife.Unbinder;
public class MainFragment extends Fragment implements BackPressedHandler, FeedFragment.Callback,
NearbyFragment.Callback, HistoryFragment.Callback, SearchFragment.Callback, FloatingQueueView.Callback,
LinkPreviewDialog.Callback {
@BindView(R.id.fragment_main_view_pager) ViewPager viewPager;
@BindView(R.id.fragment_main_nav_tab_layout) NavTabLayout tabLayout;
@BindView(R.id.floating_queue_view) FloatingQueueView floatingQueueView;
private Unbinder unbinder;
private ExclusiveBottomSheetPresenter bottomSheetPresenter = new ExclusiveBottomSheetPresenter();
private MediaDownloadReceiver downloadReceiver = new MediaDownloadReceiver();
private MediaDownloadReceiverCallback downloadReceiverCallback = new MediaDownloadReceiverCallback();
// The permissions request API doesn't take a callback, so in the event we have to
// ask for permission to download a featured image from the feed, we'll have to hold
// the image we're waiting for permission to download as a bit of state here. :(
@Nullable private FeaturedImage pendingDownloadImage;
public interface Callback {
void onTabChanged(@NonNull NavTab tab);
void onSearchOpen();
void onSearchClose(boolean shouldFinishActivity);
void updateToolbarElevation(boolean elevate);
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
fragment.setRetainInstance(true);
return fragment;
}
@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_main, container, false);
unbinder = ButterKnife.bind(this, view);
viewPager.setAdapter(new NavTabFragmentPagerAdapter(getChildFragmentManager()));
viewPager.setOffscreenPageLimit(2);
tabLayout.setOnNavigationItemSelectedListener(item -> {
if (getCurrentFragment() instanceof FeedFragment && item.getOrder() == 0) {
((FeedFragment) getCurrentFragment()).scrollToTop();
}
viewPager.setCurrentItem(item.getOrder());
return true;
});
floatingQueueView.setCallback(this);
if (savedInstanceState == null) {
handleIntent(requireActivity().getIntent());
}
return view;
}
@Override
public void onPause() {
super.onPause();
downloadReceiver.setCallback(null);
requireContext().unregisterReceiver(downloadReceiver);
floatingQueueView.animation(true);
}
@Override public void onResume() {
super.onResume();
requireContext().registerReceiver(downloadReceiver,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadReceiver.setCallback(downloadReceiverCallback);
// reset the last-page-viewed timer
Prefs.pageLastShown(0);
// update after returning from PageActivity
floatingQueueView.update();
}
@Override public void onDestroyView() {
unbinder.unbind();
unbinder = null;
super.onDestroyView();
}
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode == Constants.ACTIVITY_REQUEST_VOICE_SEARCH
&& resultCode == Activity.RESULT_OK && data != null
&& data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) != null) {
String searchQuery = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS).get(0);
openSearchFragment(SearchInvokeSource.VOICE, searchQuery);
} else if (requestCode == Constants.ACTIVITY_REQUEST_GALLERY
&& resultCode == GalleryActivity.ACTIVITY_RESULT_PAGE_SELECTED) {
startActivity(data);
} else if (requestCode == Constants.ACTIVITY_REQUEST_LOGIN
&& resultCode == LoginActivity.RESULT_LOGIN_SUCCESS) {
refreshExploreFeed();
FeedbackUtil.showMessage(this, R.string.login_success_toast);
} else if (requestCode == Constants.ACTIVITY_REQUEST_BROWSE_TABS) {
if (WikipediaApp.getInstance().getTabCount() == 0) {
// They browsed the tabs and cleared all of them, without wanting to open a new tab.
return;
}
if (resultCode == TabActivity.RESULT_NEW_TAB) {
HistoryEntry entry = new HistoryEntry(MainPageClient.getMainPageTitle(), HistoryEntry.SOURCE_MAIN_PAGE);
startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.getTitle()));
} else if (resultCode == TabActivity.RESULT_LOAD_FROM_BACKSTACK) {
startActivity(PageActivity.newIntent(requireContext()));
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION:
if (PermissionUtil.isPermitted(grantResults)) {
if (pendingDownloadImage != null) {
download(pendingDownloadImage);
}
} else {
setPendingDownload(null);
L.i("Write permission was denied by user");
FeedbackUtil.showMessage(this,
R.string.gallery_save_image_write_permission_rationale);
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void handleIntent(Intent intent) {
IntentFunnel funnel = new IntentFunnel(WikipediaApp.getInstance());
if (intent.hasExtra(Constants.INTENT_APP_SHORTCUT_SEARCH)) {
openSearchFragment(SearchInvokeSource.APP_SHORTCUTS, null);
} else if (intent.hasExtra(Constants.INTENT_APP_SHORTCUT_RANDOM)) {
startActivity(RandomActivity.newIntent(requireActivity(), RandomActivity.INVOKE_SOURCE_SHORTCUT));
} else if (Intent.ACTION_SEND.equals(intent.getAction())
&& Constants.PLAIN_TEXT_MIME_TYPE.equals(intent.getType())) {
funnel.logShareIntent();
openSearchFragment(SearchInvokeSource.INTENT_SHARE,
intent.getStringExtra(Intent.EXTRA_TEXT));
} else if (Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())
&& Constants.PLAIN_TEXT_MIME_TYPE.equals(intent.getType())
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
funnel.logProcessTextIntent();
openSearchFragment(SearchInvokeSource.INTENT_PROCESS_TEXT,
intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT));
} else if (intent.hasExtra(Constants.INTENT_SEARCH_FROM_WIDGET)) {
funnel.logSearchWidgetTap();
openSearchFragment(SearchInvokeSource.WIDGET, null);
} else if (intent.hasExtra(Constants.INTENT_EXTRA_DELETE_READING_LIST)) {
goToTab(NavTab.READING_LISTS);
} else if (intent.hasExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB)
&& !((tabLayout.getSelectedItemId() == NavTab.EXPLORE.code())
&& intent.getIntExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, NavTab.EXPLORE.code()) == NavTab.EXPLORE.code())) {
goToTab(NavTab.of(intent.getIntExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, NavTab.EXPLORE.code())));
} else if (lastPageViewedWithin(1) && !intent.hasExtra(Constants.INTENT_RETURN_TO_MAIN)) {
startActivity(PageActivity.newIntent(requireContext()));
requireActivity().finish();
}
}
@Override public void onFeedSearchRequested() {
openSearchFragment(SearchInvokeSource.FEED_BAR, null);
}
@Override public void onFeedVoiceSearchRequested() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
try {
startActivityForResult(intent, Constants.ACTIVITY_REQUEST_VOICE_SEARCH);
} catch (ActivityNotFoundException a) {
FeedbackUtil.showMessage(this, R.string.error_voice_search_not_available);
}
}
@Override public void onFeedSelectPage(HistoryEntry entry) {
startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.getTitle()), getTransitionAnimationBundle(entry.getTitle()));
}
@Override public void onFeedSelectPageFromExistingTab(HistoryEntry entry) {
startActivity(PageActivity.newIntentForExistingTab(requireContext(), entry, entry.getTitle()), getTransitionAnimationBundle(entry.getTitle()));
}
@Override public void onFeedAddPageToList(HistoryEntry entry) {
bottomSheetPresenter.show(getChildFragmentManager(),
AddToReadingListDialog.newInstance(entry.getTitle(),
AddToReadingListDialog.InvokeSource.FEED));
}
@Override
public void onFeedRemovePageFromList(@NonNull HistoryEntry entry) {
FeedbackUtil.showMessage(requireActivity(),
getString(R.string.reading_list_item_deleted, entry.getTitle().getDisplayText()));
}
@Override public void onFeedSharePage(HistoryEntry entry) {
ShareUtil.shareText(requireContext(), entry.getTitle());
}
@Override public void onFeedNewsItemSelected(@NonNull NewsItemCard card, @NonNull HorizontalScrollingListCardItemView view) {
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(requireActivity(), view.getImageView(), getString(R.string.transition_news_item));
startActivity(NewsActivity.newIntent(requireActivity(), card.item(), card.wikiSite()), options.toBundle());
}
@Override public void onFeedShareImage(final FeaturedImageCard card) {
final String thumbUrl = card.baseImage().thumbnail().source().toString();
final String fullSizeUrl = card.baseImage().image().source().toString();
new ImagePipelineBitmapGetter(thumbUrl) {
@Override
public void onSuccess(@Nullable Bitmap bitmap) {
if (bitmap != null) {
ShareUtil.shareImage(requireContext(),
bitmap,
new File(thumbUrl).getName(),
ShareUtil.getFeaturedImageShareSubject(requireContext(), card.age()),
fullSizeUrl);
} else {
FeedbackUtil.showMessage(MainFragment.this, getString(R.string.gallery_share_error, card.baseImage().title()));
}
}
}.get();
}
@Override public void onFeedDownloadImage(FeaturedImage image) {
if (!(PermissionUtil.hasWriteExternalStoragePermission(requireContext()))) {
setPendingDownload(image);
requestWriteExternalStoragePermission();
} else {
download(image);
}
}
@Override public void onFeaturedImageSelected(FeaturedImageCard card) {
startActivityForResult(GalleryActivity.newIntent(requireActivity(), card.age(),
card.filename(), card.baseImage(), card.wikiSite(),
GalleryFunnel.SOURCE_FEED_FEATURED_IMAGE), Constants.ACTIVITY_REQUEST_GALLERY);
}
@Override
public void onLoginRequested() {
startActivityForResult(LoginActivity.newIntent(requireContext(), LoginFunnel.SOURCE_NAV),
Constants.ACTIVITY_REQUEST_LOGIN);
}
@Nullable
public Bundle getTransitionAnimationBundle(@NonNull PageTitle pageTitle) {
return pageTitle.getThumbUrl() != null ? ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(),
floatingQueueView.getImageView(), ViewCompat.getTransitionName(floatingQueueView.getImageView())).toBundle() : null;
}
@Override
public void updateToolbarElevation(boolean elevate) {
if (callback() != null) {
callback().updateToolbarElevation(elevate);
}
}
public void requestUpdateToolbarElevation() {
Fragment fragment = getCurrentFragment();
updateToolbarElevation(!(fragment instanceof FeedFragment) || ((FeedFragment) fragment).shouldElevateToolbar());
}
@Override public void onLoading() {
// todo: [overhaul] update loading indicator.
}
@Override public void onLoaded() {
// todo: [overhaul] update loading indicator.
}
@Override public void onLoadPage(@NonNull HistoryEntry entry, @Nullable Location location) {
showLinkPreview(entry, location);
}
@Override public void onLoadPage(@NonNull HistoryEntry entry) {
startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.getTitle()), getTransitionAnimationBundle(entry.getTitle()));
}
@Override public void onClearHistory() {
// todo: [overhaul] clear history.
}
@Override
public void onSearchResultCopyLink(@NonNull PageTitle title) {
copyLink(title.getCanonicalUri());
}
@Override
public void onSearchResultAddToList(@NonNull PageTitle title,
@NonNull AddToReadingListDialog.InvokeSource source) {
bottomSheetPresenter.show(getChildFragmentManager(),
AddToReadingListDialog.newInstance(title, source));
}
@Override
public void onSearchResultShareLink(@NonNull PageTitle title) {
ShareUtil.shareText(requireContext(), title);
}
@Override
public void onSearchSelectPage(@NonNull HistoryEntry entry, boolean inNewTab) {
startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.getTitle()), getTransitionAnimationBundle(entry.getTitle()));
}
@Override
public void onSearchOpen() {
Callback callback = callback();
if (callback != null) {
callback.onSearchOpen();
}
}
@Override
public void onSearchClose(boolean launchedFromIntent) {
SearchFragment fragment = searchFragment();
if (fragment != null) {
closeSearchFragment(fragment);
if (fragment.isLanguageChanged()) {
refreshExploreFeed();
}
}
Callback callback = callback();
if (callback != null) {
callback.onSearchClose(launchedFromIntent);
}
}
@Override
public void onLinkPreviewLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry, boolean inNewTab) {
startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.getTitle()), getTransitionAnimationBundle(entry.getTitle()));
}
@Override
public void onLinkPreviewCopyLink(@NonNull PageTitle title) {
copyLink(title.getCanonicalUri());
}
@Override
public void onLinkPreviewAddToList(@NonNull PageTitle title) {
bottomSheetPresenter.show(getChildFragmentManager(),
AddToReadingListDialog.newInstance(title,
AddToReadingListDialog.InvokeSource.LINK_PREVIEW_MENU));
}
@Override
public void onLinkPreviewShareLink(@NonNull PageTitle title) {
ShareUtil.shareText(requireContext(), title);
}
@Override
public void onFloatingQueueClicked(@NonNull PageTitle title) {
startActivity(PageActivity.newIntentForExistingTab(requireContext(),
new HistoryEntry(title, HistoryEntry.SOURCE_FLOATING_QUEUE), title), getTransitionAnimationBundle(title));
}
@Override
public boolean onBackPressed() {
SearchFragment searchFragment = searchFragment();
if (searchFragment != null && searchFragment.onBackPressed()) {
return true;
}
Fragment fragment = getCurrentFragment();
if (fragment instanceof BackPressedHandler && ((BackPressedHandler) fragment).onBackPressed()) {
return true;
}
return false;
}
public void setBottomNavVisible(boolean visible) {
tabLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
}
public void onGoOffline() {
Fragment fragment = getCurrentFragment();
if (fragment instanceof FeedFragment) {
((FeedFragment) fragment).onGoOffline();
} else if (fragment instanceof HistoryFragment) {
((HistoryFragment) fragment).refresh();
}
}
public void onGoOnline() {
Fragment fragment = getCurrentFragment();
if (fragment instanceof FeedFragment) {
((FeedFragment) fragment).onGoOnline();
} else if (fragment instanceof HistoryFragment) {
((HistoryFragment) fragment).refresh();
}
}
public FloatingQueueView getFloatingQueueView() {
return floatingQueueView;
}
@OnPageChange(R.id.fragment_main_view_pager) void onTabChanged(int position) {
Callback callback = callback();
if (callback != null) {
NavTab tab = NavTab.of(position);
callback.onTabChanged(tab);
}
}
private void showLinkPreview(@NonNull HistoryEntry entry, @Nullable Location location) {
bottomSheetPresenter.show(getChildFragmentManager(), LinkPreviewDialog.newInstance(entry, location));
}
private void copyLink(@NonNull String url) {
ClipboardUtil.setPlainText(requireContext(), null, url);
FeedbackUtil.showMessage(this, R.string.address_copied);
}
private boolean lastPageViewedWithin(int days) {
return TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - Prefs.pageLastShown()) < days;
}
private void download(@NonNull FeaturedImage image) {
setPendingDownload(null);
downloadReceiver.download(requireContext(), image);
FeedbackUtil.showMessage(this, R.string.gallery_save_progress);
}
private void setPendingDownload(@Nullable FeaturedImage image) {
pendingDownloadImage = image;
}
private void requestWriteExternalStoragePermission() {
PermissionUtil.requestWriteStorageRuntimePermissions(this,
Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION);
}
@SuppressLint("CommitTransaction")
private void openSearchFragment(@NonNull SearchInvokeSource source, @Nullable String query) {
Fragment fragment = searchFragment();
if (fragment == null) {
fragment = SearchFragment.newInstance(source, StringUtils.trim(query));
getChildFragmentManager()
.beginTransaction()
.add(R.id.fragment_main_container, fragment)
.commitNowAllowingStateLoss();
}
}
@SuppressLint("CommitTransaction")
private void closeSearchFragment(@NonNull SearchFragment fragment) {
getChildFragmentManager().beginTransaction().remove(fragment).commitNowAllowingStateLoss();
}
@Nullable private SearchFragment searchFragment() {
return (SearchFragment) getChildFragmentManager().findFragmentById(R.id.fragment_main_container);
}
private void cancelSearch() {
SearchFragment fragment = searchFragment();
if (fragment != null) {
fragment.closeSearch();
}
}
private void goToTab(@NonNull NavTab tab) {
tabLayout.setSelectedItemId(tab.code());
cancelSearch();
}
private void refreshExploreFeed() {
Fragment fragment = getCurrentFragment();
if (fragment instanceof FeedFragment) {
((FeedFragment) fragment).refresh();
}
}
public Fragment getCurrentFragment() {
return ((NavTabFragmentPagerAdapter) viewPager.getAdapter()).getCurrentFragment();
}
private class MediaDownloadReceiverCallback implements MediaDownloadReceiver.Callback {
@Override
public void onSuccess() {
FeedbackUtil.showMessage(requireActivity(), R.string.gallery_save_success);
}
}
@Nullable private Callback callback() {
return FragmentUtil.getCallback(this, Callback.class);
}
}
|
3e06077b365e431c932a540cb17bf1dd9ae368d1
| 1,059 |
java
|
Java
|
config-client/src/main/java/com/xkcoding/configclient/controller/IndexController.java
|
yclxiao/springcloud-simple-demo
|
b5de80ab0a5119e577c97ce33a509ecb36877f0a
|
[
"Apache-2.0"
] | 13 |
2018-08-14T07:48:31.000Z
|
2021-06-04T03:04:02.000Z
|
config-client/src/main/java/com/xkcoding/configclient/controller/IndexController.java
|
yclxiao/springcloud-simple-demo
|
b5de80ab0a5119e577c97ce33a509ecb36877f0a
|
[
"Apache-2.0"
] | null | null | null |
config-client/src/main/java/com/xkcoding/configclient/controller/IndexController.java
|
yclxiao/springcloud-simple-demo
|
b5de80ab0a5119e577c97ce33a509ecb36877f0a
|
[
"Apache-2.0"
] | 2 |
2018-08-27T08:06:00.000Z
|
2019-04-17T04:32:51.000Z
| 24.627907 | 72 | 0.741265 | 2,551 |
package com.xkcoding.configclient.controller;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* <p>
* 首页 Controller
* </p>
*
* @package: com.xkcoding.configclient.controller
* @description: 首页 Controller
* @author: yangkai.shen
* @date: Created in 2018/8/14 下午2:55
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@RestController
@RefreshScope
@RequestMapping("/api")
public class IndexController {
@Value("${demo.name}")
private String name;
@Value("${demo.version}")
private String version;
@GetMapping("/info")
public Map<String, Object> info() {
Map<String, Object> ret = Maps.newHashMap();
ret.put("name", name);
ret.put("version", version);
return ret;
}
}
|
3e060837ec6905f00c5298008a7fa5f2932fe2b9
| 2,729 |
java
|
Java
|
examples/appnet-api-server/src/main/java/com/hedera/hashgraph/identity/hcs/example/appnet/agecircuit/model/ProofAgePublicInput.java
|
HorizenLabs/did-sdk-java
|
f9912287c609470cac99c4cad6f899ef33a8ccc9
|
[
"Apache-2.0"
] | null | null | null |
examples/appnet-api-server/src/main/java/com/hedera/hashgraph/identity/hcs/example/appnet/agecircuit/model/ProofAgePublicInput.java
|
HorizenLabs/did-sdk-java
|
f9912287c609470cac99c4cad6f899ef33a8ccc9
|
[
"Apache-2.0"
] | null | null | null |
examples/appnet-api-server/src/main/java/com/hedera/hashgraph/identity/hcs/example/appnet/agecircuit/model/ProofAgePublicInput.java
|
HorizenLabs/did-sdk-java
|
f9912287c609470cac99c4cad6f899ef33a8ccc9
|
[
"Apache-2.0"
] | null | null | null | 31.367816 | 311 | 0.724075 | 2,552 |
package com.hedera.hashgraph.identity.hcs.example.appnet.agecircuit.model;
import com.hedera.hashgraph.identity.hcs.vc.CredentialSubject;
import com.hedera.hashgraph.zeroknowledge.proof.model.ZeroKnowledgeProofPublicInput;
import com.hedera.hashgraph.zeroknowledge.vp.proof.ZeroKnowledgeSignature;
import org.threeten.bp.Instant;
import java.util.List;
public final class ProofAgePublicInput<T extends CredentialSubject> implements ZeroKnowledgeProofPublicInput {
private final List<T> credentialSubject;
private final ZeroKnowledgeSignature<T> zeroKnowledgeSignature;
private final String challenge;
private final String secretKey;
private final String dayLabel;
private final String monthLabel;
private final String yearLabel;
private final int ageThreshold;
private final String holderPublicKey;
private final String authorityPublicKey;
private final String documentId;
private final Instant vcDocumentDate;
public ProofAgePublicInput(List<T> credentialSubject, ZeroKnowledgeSignature<T> zeroKnowledgeSignature, String challenge, String secretKey, String dayLabel, String monthLabel, String yearLabel, int ageThreshold, String holderPublicKey, String authorityPublicKey, String documentId, Instant vcDocumentDate) {
this.credentialSubject = credentialSubject;
this.zeroKnowledgeSignature = zeroKnowledgeSignature;
this.challenge = challenge;
this.secretKey = secretKey;
this.dayLabel = dayLabel;
this.monthLabel = monthLabel;
this.yearLabel = yearLabel;
this.ageThreshold = ageThreshold;
this.holderPublicKey = holderPublicKey;
this.authorityPublicKey = authorityPublicKey;
this.documentId = documentId;
this.vcDocumentDate = vcDocumentDate;
}
public List<T> getCredentialSubject() {
return credentialSubject;
}
public ZeroKnowledgeSignature<T> getZeroKnowledgeSignature() {
return zeroKnowledgeSignature;
}
public String getChallenge() {
return challenge;
}
public String getSecretKey() {
return secretKey;
}
public String getDayLabel() {
return dayLabel;
}
public String getMonthLabel() {
return monthLabel;
}
public String getYearLabel() {
return yearLabel;
}
public int getAgeThreshold() {
return ageThreshold;
}
public String getHolderPublicKey() {
return holderPublicKey;
}
public String getAuthorityPublicKey() {
return authorityPublicKey;
}
public String getDocumentId() {
return documentId;
}
public Instant getVcDocumentDate() {
return vcDocumentDate;
}
}
|
3e0608da4f57506955dee62fb45db7bda31842c4
| 1,792 |
java
|
Java
|
bundles/com.graf.docker.api.client/src/com/graf/docker/client/models/EndpointIPAMConfig.java
|
graf-markus/java-docker-api-client
|
6fd93f3941e218ec59af405ca4a6bd79fffce1a7
|
[
"MIT"
] | 1 |
2021-08-13T03:31:34.000Z
|
2021-08-13T03:31:34.000Z
|
bundles/com.graf.docker.api.client/src/com/graf/docker/client/models/EndpointIPAMConfig.java
|
graf-markus/java-docker-api-client
|
6fd93f3941e218ec59af405ca4a6bd79fffce1a7
|
[
"MIT"
] | 2 |
2020-02-17T17:56:02.000Z
|
2020-02-25T18:39:41.000Z
|
bundles/com.graf.docker.api.client/src/com/graf/docker/client/models/EndpointIPAMConfig.java
|
graf-markus/java-docker-api-client
|
6fd93f3941e218ec59af405ca4a6bd79fffce1a7
|
[
"MIT"
] | null | null | null | 21.082353 | 61 | 0.729911 | 2,553 |
package com.graf.docker.client.models;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class EndpointIPAMConfig {
private String ipv4Address;
private String ipv6Address;
private List<String> linkLocalIPs;
private EndpointIPAMConfig(Builder builder) {
this.ipv4Address = builder.ipv4Address;
this.ipv6Address = builder.ipv6Address;
this.linkLocalIPs = builder.linkLocalIPs;
}
public String getIpv4Address() {
return ipv4Address;
}
public String getIpv6Address() {
return ipv6Address;
}
public List<String> getLinkLocalIPs() {
return linkLocalIPs;
}
public static Builder builder() {
return new Builder();
}
@Override
public String toString() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this);
}
public static class Builder {
private String ipv4Address;
private String ipv6Address;
private List<String> linkLocalIPs;
public Builder() {
}
public Builder ipv4Address(String ipv4Address) {
this.ipv4Address = ipv4Address;
return Builder.this;
}
public Builder ipv6Address(String ipv6Address) {
this.ipv6Address = ipv6Address;
return Builder.this;
}
public Builder linkLocalIPs(List<String> linkLocalIPs) {
if (this.linkLocalIPs == null) {
this.linkLocalIPs = new ArrayList<>();
}
this.linkLocalIPs.addAll(linkLocalIPs);
return Builder.this;
}
public Builder linkLocalIPs(String... linkLocalIPs) {
if (this.linkLocalIPs == null) {
this.linkLocalIPs = new ArrayList<>();
}
this.linkLocalIPs.addAll(Arrays.asList(linkLocalIPs));
return Builder.this;
}
public EndpointIPAMConfig build() {
return new EndpointIPAMConfig(this);
}
}
}
|
3e06090c36f2f2414420300bdf7fac40e2468146
| 2,889 |
java
|
Java
|
sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ProxyShowDatabasesMergedResult.java
|
anquan/sharding-sphere
|
3078488a7327cb7a3961e382f71edaecdb054943
|
[
"Apache-2.0"
] | 1 |
2018-09-12T13:08:51.000Z
|
2018-09-12T13:08:51.000Z
|
sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ProxyShowDatabasesMergedResult.java
|
anquan/sharding-sphere
|
3078488a7327cb7a3961e382f71edaecdb054943
|
[
"Apache-2.0"
] | null | null | null |
sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ProxyShowDatabasesMergedResult.java
|
anquan/sharding-sphere
|
3078488a7327cb7a3961e382f71edaecdb054943
|
[
"Apache-2.0"
] | null | null | null | 30.734043 | 132 | 0.69505 | 2,554 |
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* 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.
* </p>
*/
package io.shardingsphere.core.merger.dal.show;
import io.shardingsphere.core.merger.MergedResult;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.util.Calendar;
import java.util.List;
/**
* Proxy merged result for show databases.
*
* @author chenqingyang
*/
public final class ProxyShowDatabasesMergedResult implements MergedResult {
private List<String> schemas;
private int currentIndex;
public ProxyShowDatabasesMergedResult(final List<String> schemas) {
this.schemas = schemas;
}
@Override
public boolean next() {
if (currentIndex < schemas.size()) {
currentIndex++;
return true;
}
return false;
}
@Override
public Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
if (Blob.class == type || Clob.class == type || Reader.class == type || InputStream.class == type || SQLXML.class == type) {
throw new SQLFeatureNotSupportedException();
}
return schemas.get(currentIndex - 1);
}
@Override
public Object getValue(final String columnLabel, final Class<?> type) {
return new SQLFeatureNotSupportedException();
}
@Override
public Object getCalendarValue(final int columnIndex, final Class<?> type, final Calendar calendar) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Object getCalendarValue(final String columnLabel, final Class<?> type, final Calendar calendar) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public InputStream getInputStream(final int columnIndex, final String type) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public InputStream getInputStream(final String columnLabel, final String type) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean wasNull() throws SQLException {
return false;
}
}
|
3e060945539eff95a064dbe2ca712b170f57f01a
| 1,861 |
java
|
Java
|
src/eugene/architectural/dataaccessobject/CustomerDaoImpl.java
|
Ernestyj/JDesignPatternStudy
|
4576ed6bac7f664a3c704dbee59428e611f6c007
|
[
"MIT"
] | null | null | null |
src/eugene/architectural/dataaccessobject/CustomerDaoImpl.java
|
Ernestyj/JDesignPatternStudy
|
4576ed6bac7f664a3c704dbee59428e611f6c007
|
[
"MIT"
] | null | null | null |
src/eugene/architectural/dataaccessobject/CustomerDaoImpl.java
|
Ernestyj/JDesignPatternStudy
|
4576ed6bac7f664a3c704dbee59428e611f6c007
|
[
"MIT"
] | null | null | null | 31.542373 | 141 | 0.677593 | 2,555 |
package eugene.architectural.dataaccessobject;
/**
* Created by Jian on 2015/8/13.
*/
import java.util.List;
/**
* The data access object (DAO) is an object that provides an abstract interface to some type of database or other persistence mechanism.
* By mapping application calls to the persistence layer, DAO provide some specific data operations without exposing details of the database.
* This isolation supports the Single responsibility principle. It separates what data accesses the application needs, in terms of
* domain-specific objects and data types (the public interface of the DAO), from how these needs can be satisfied with a specific DBMS,
* database schema, etc.
*/
public class CustomerDaoImpl implements CustomerDao {
// Represents the DB structure for our example so we don't have to managed it ourselves
// Note: Normally this would be in the form of an actual database and not part of the Dao Impl.
private List<Customer> customers;
public CustomerDaoImpl(List<Customer> customers) {
this.customers = customers;
}
@Override
public List<Customer> getAllCustomers() {
return customers;
}
@Override
public Customer getCusterById(int id) {
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getId() == id) {
return customers.get(i);
}
}
// No customer found
return null;
}
@Override
public void addCustomer(Customer customer) {
customers.add(customer);
}
@Override
public void updateCustomer(Customer customer) {
if (customers.contains(customer)) {
customers.set(customers.indexOf(customer), customer);
}
}
@Override
public void deleteCustomer(Customer customer) {
customers.remove(customer);
}
}
|
3e06098f265006866f7985fe49ba2f4ed48e9ca0
| 1,061 |
java
|
Java
|
Lab_05_FunctionalProgramming/src/com/company/P01_SortEvenNumbers.java
|
s3valkov/JavaAdvanced
|
89617d779d881b273aa25a45e925bfcd126cb46f
|
[
"Apache-2.0"
] | null | null | null |
Lab_05_FunctionalProgramming/src/com/company/P01_SortEvenNumbers.java
|
s3valkov/JavaAdvanced
|
89617d779d881b273aa25a45e925bfcd126cb46f
|
[
"Apache-2.0"
] | null | null | null |
Lab_05_FunctionalProgramming/src/com/company/P01_SortEvenNumbers.java
|
s3valkov/JavaAdvanced
|
89617d779d881b273aa25a45e925bfcd126cb46f
|
[
"Apache-2.0"
] | 2 |
2019-09-22T16:16:20.000Z
|
2020-06-26T13:01:25.000Z
| 30.314286 | 64 | 0.590009 | 2,556 |
package com.company;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class P01_SortEvenNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] stringNumber = scanner.nextLine().split(", ");
List<Integer> evenNumbers = Arrays.stream(stringNumber)
.map(Integer::parseInt).filter(x -> x % 2 == 0)
.collect(Collectors.toList());
List<String> numbers = evenNumbers.stream()
.map(String::valueOf)
.collect(Collectors.toList());
String evenNums = String.join(", ", numbers);
System.out.println(evenNums);
evenNumbers.sort(Integer::compare);
List<String> sorted = evenNumbers.stream()
.map(String::valueOf)
.collect(Collectors.toList());
String sortedNumbers = String.join(", ", sorted);
System.out.println(sortedNumbers);
}
}
|
3e060b0516319c98baa8b3339c7c23782dd4c21d
| 6,937 |
java
|
Java
|
src/test/java/io/confluent/examples/streams/microservices/OrdersServiceTest.java
|
1123/kafka-streams-examples
|
dfa0f9fc5de7a5244b2cec301990cc711336d455
|
[
"Apache-2.0"
] | 1 |
2018-12-21T06:03:19.000Z
|
2018-12-21T06:03:19.000Z
|
src/test/java/io/confluent/examples/streams/microservices/OrdersServiceTest.java
|
1123/kafka-streams-examples
|
dfa0f9fc5de7a5244b2cec301990cc711336d455
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/io/confluent/examples/streams/microservices/OrdersServiceTest.java
|
1123/kafka-streams-examples
|
dfa0f9fc5de7a5244b2cec301990cc711336d455
|
[
"Apache-2.0"
] | 1 |
2020-10-12T02:29:36.000Z
|
2020-10-12T02:29:36.000Z
| 34.859296 | 101 | 0.714142 | 2,557 |
package io.confluent.examples.streams.microservices;
import io.confluent.examples.streams.avro.microservices.Order;
import io.confluent.examples.streams.avro.microservices.OrderState;
import io.confluent.examples.streams.avro.microservices.Product;
import io.confluent.examples.streams.microservices.domain.Schemas;
import io.confluent.examples.streams.microservices.domain.Schemas.Topics;
import io.confluent.examples.streams.microservices.domain.beans.OrderBean;
import io.confluent.examples.streams.microservices.util.MicroserviceTestUtils;
import io.confluent.examples.streams.microservices.util.Paths;
import org.apache.kafka.test.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import java.net.HttpURLConnection;
import java.util.Collections;
import static io.confluent.examples.streams.avro.microservices.Order.newBuilder;
import static io.confluent.examples.streams.microservices.domain.beans.OrderId.id;
import static io.confluent.examples.streams.microservices.util.MicroserviceUtils.MIN;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.junit.Assert.fail;
public class OrdersServiceTest extends MicroserviceTestUtils {
private OrdersService rest;
private OrdersService rest2;
@BeforeClass
public static void startKafkaCluster() {
Schemas.configureSerdesWithSchemaRegistryUrl(CLUSTER.schemaRegistryUrl());
}
@After
public void shutdown() {
if (rest != null) {
rest.stop();
rest.cleanLocalState();
}
if (rest2 != null) {
rest2.stop();
rest2.cleanLocalState();
}
}
@Before
public void prepareKafkaCluster() throws Exception {
CLUSTER.deleteTopicsAndWait(30000, Topics.ORDERS.name(), "OrdersService-orders-store-changelog");
CLUSTER.createTopic(Topics.ORDERS.name());
Schemas.configureSerdesWithSchemaRegistryUrl(CLUSTER.schemaRegistryUrl());
}
@Test
public void shouldPostOrderAndGetItBack() {
OrderBean bean = new OrderBean(id(1L), 2L, OrderState.CREATED, Product.JUMPERS, 10, 100d);
final Client client = ClientBuilder.newClient();
//Given a rest service
rest = new OrdersService("localhost");
rest.start(CLUSTER.bootstrapServers(), TestUtils.tempDirectory().getPath());
Paths paths = new Paths("localhost", rest.port());
//When we POST an order
Response response = client.target(paths.urlPost())
.request(APPLICATION_JSON_TYPE)
.post(Entity.json(bean));
//Then
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED);
//When GET the bean back via it's location
OrderBean returnedBean = client.target(response.getLocation())
.queryParam("timeout", MIN / 2)
.request(APPLICATION_JSON_TYPE)
.get(new GenericType<OrderBean>() {
});
//Then it should be the bean we PUT
assertThat(returnedBean).isEqualTo(bean);
//When GET the bean back explicitly
returnedBean = client.target(paths.urlGet(1))
.queryParam("timeout", MIN / 2)
.request(APPLICATION_JSON_TYPE)
.get(new GenericType<OrderBean>() {
});
//Then it should be the bean we PUT
assertThat(returnedBean).isEqualTo(bean);
}
@Test
public void shouldGetValidatedOrderOnRequest() {
Order orderV1 = new Order(id(1L), 3L, OrderState.CREATED, Product.JUMPERS, 10, 100d);
OrderBean beanV1 = OrderBean.toBean(orderV1);
final Client client = ClientBuilder.newClient();
//Given a rest service
rest = new OrdersService("localhost");
rest.start(CLUSTER.bootstrapServers(), TestUtils.tempDirectory().getPath());
Paths paths = new Paths("localhost", rest.port());
//When we post an order
client.target(paths.urlPost())
.request(APPLICATION_JSON_TYPE)
.post(Entity.json(beanV1));
//Simulate the order being validated
MicroserviceTestUtils.sendOrders(Collections.singletonList(
newBuilder(orderV1)
.setState(OrderState.VALIDATED)
.build()));
//When we GET the order from the returned location
OrderBean returnedBean = client.target(paths.urlGetValidated(beanV1.getId()))
.queryParam("timeout", MIN / 2)
.request(APPLICATION_JSON_TYPE)
.get(new GenericType<OrderBean>() {
});
//Then status should be Validated
assertThat(returnedBean.getState()).isEqualTo(OrderState.VALIDATED);
}
@Test
public void shouldTimeoutGetIfNoResponseIsFound() {
final Client client = ClientBuilder.newClient();
//Start the rest interface
rest = new OrdersService("localhost");
rest.start(CLUSTER.bootstrapServers(), TestUtils.tempDirectory().getPath());
Paths paths = new Paths("localhost", rest.port());
//Then GET order should timeout
try {
client.target(paths.urlGet(1))
.queryParam("timeout", 100) //Lower the request timeout
.request(APPLICATION_JSON_TYPE)
.get(new GenericType<OrderBean>() {
});
fail("Request should have failed as materialized view has not been updated");
} catch (ServerErrorException e) {
assertThat(e.getMessage()).isEqualTo("HTTP 504 Gateway Timeout");
}
}
@Test
public void shouldGetOrderByIdWhenOnDifferentHost() {
OrderBean order = new OrderBean(id(1L), 4L, OrderState.VALIDATED, Product.JUMPERS, 10, 100d);
final Client client = ClientBuilder.newClient();
//Given two rest servers on different ports
rest = new OrdersService("localhost");
rest.start(CLUSTER.bootstrapServers(), TestUtils.tempDirectory().getPath());
Paths paths1 = new Paths("localhost", rest.port());
rest2 = new OrdersService("localhost");
rest2.start(CLUSTER.bootstrapServers(), TestUtils.tempDirectory().getPath());
Paths paths2 = new Paths("localhost", rest2.port());
//And one order
client.target(paths1.urlPost())
.request(APPLICATION_JSON_TYPE)
.post(Entity.json(order));
//When GET to rest1
OrderBean returnedOrder = client.target(paths1.urlGet(order.getId()))
.queryParam("timeout", MIN / 2)
.request(APPLICATION_JSON_TYPE)
.get(new GenericType<OrderBean>() {
});
//Then we should get the order back
assertThat(returnedOrder).isEqualTo(order);
//When GET to rest2
returnedOrder = client.target(paths2.urlGet(order.getId()))
.queryParam("timeout", MIN / 2)
.request(APPLICATION_JSON_TYPE)
.get(new GenericType<OrderBean>() {
});
//Then we should get the order back also
assertThat(returnedOrder).isEqualTo(order);
}
}
|
3e060be2ed4e74663da7a19d0d03fddb0d8a2b2f
| 8,402 |
java
|
Java
|
app/src/main/java/com/pravrajya/diamond/views/users/main/views/FragmentHome.java
|
ishaileshmishra/stock-market-android-app
|
df700874dacb1d5fe929aa2d9836851135054ef6
|
[
"MIT"
] | 1 |
2022-02-25T11:23:13.000Z
|
2022-02-25T11:23:13.000Z
|
app/src/main/java/com/pravrajya/diamond/views/users/main/views/FragmentHome.java
|
ishaileshmishra/stock-market-android-app
|
df700874dacb1d5fe929aa2d9836851135054ef6
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/pravrajya/diamond/views/users/main/views/FragmentHome.java
|
ishaileshmishra/stock-market-android-app
|
df700874dacb1d5fe929aa2d9836851135054ef6
|
[
"MIT"
] | null | null | null | 34.154472 | 123 | 0.652464 | 2,558 |
package com.pravrajya.diamond.views.users.main.views;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;
import com.fxn.stash.Stash;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.pravrajya.diamond.R;
import com.pravrajya.diamond.utils.Constants;
import com.pravrajya.diamond.utils.ItemDecoration;
import com.pravrajya.diamond.views.users.fragments.BaseFragment;
import com.pravrajya.diamond.views.users.main.adapter.ProductAdapter;
import com.pravrajya.diamond.tables.product.ProductTable;
import com.pravrajya.diamond.utils.ClickListener;
import com.pravrajya.diamond.databinding.ContentMainBinding;
import com.pravrajya.diamond.views.users.main.model.ItemModel;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.realm.Realm;
import io.realm.RealmResults;
import static com.pravrajya.diamond.utils.Constants.DEFAULT_COLOR;
import static com.pravrajya.diamond.utils.Constants.DEFAULT_CUT;
import static com.pravrajya.diamond.utils.Constants.DEFAULT_SIZE;
public class FragmentHome extends BaseFragment {
private String COLOR;
private String CUT;
private String SIZE;
private ContentMainBinding binding;
private RealmResults<ProductTable> dataModel;
private int DELAY_IN_MILLIS = 5000;
private Boolean isRefreshing = true;
private Realm realm;
private ProductAdapter adapter;
private Activity activity;
static FragmentHome newInstance() {
return new FragmentHome();
}
public FragmentHome() { }
@SuppressLint("SetTextI18n")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.content_main, container, false);
activity = (MainActivity)getActivity();
realm = Realm.getDefaultInstance();
COLOR = Stash.getString(Constants.SELECTED_COLOR);
CUT = Stash.getString(Constants.SELECTED_CUT);
SIZE = Stash.getString(Constants.SELECTED_SIZE);
if (!COLOR.equalsIgnoreCase("")) { COLOR = Stash.getString(Constants.SELECTED_COLOR);
} else { COLOR = DEFAULT_COLOR; }
if (!CUT.equalsIgnoreCase("")) { CUT = Stash.getString(Constants.SELECTED_CUT);
} else { CUT = DEFAULT_CUT; }
if (!SIZE.equalsIgnoreCase("")) { SIZE = Stash.getString(Constants.SELECTED_SIZE);
} else { SIZE = DEFAULT_SIZE; }
dataModel = realm.where(ProductTable.class)
.contains("color",COLOR)
.contains("size", SIZE)
.contains("shape",CUT)
.findAll();
loadRecyclerView();
onRefresh();
startAnimGraph();
binding.swipeRefreshLayout.setOnRefreshListener(this::onRefresh);
return binding.getRoot();
}
@Override
public void onStart() {
super.onStart();
onRefresh();
}
private void onRefresh(){
dataModel = realm.where(ProductTable.class)
.contains("color",COLOR)
.contains("size",SIZE)
.contains("shape",CUT)
.findAll();
if (dataModel.isLoaded())
if (dataModel.size() == 0){
binding.headingLayout.setVisibility(View.GONE);
binding.recyclerView.setVisibility(View.GONE);
binding.info.setVisibility(View.VISIBLE);
binding.info.setText("No Products Found");
binding.chart.setVisibility(View.INVISIBLE);
}else {
binding.swipeRefreshLayout.setRefreshing(true);
adapter.notifyDataSetChanged();
adapter.updateData( isRefreshing);
binding.swipeRefreshLayout.setRefreshing(false);
}
}
private void startAnimGraph() {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
LineData data = getData(activity.getResources().getColor(R.color.colorPrimary));
setupChart(binding.chart, data);
handler.postDelayed(this, DELAY_IN_MILLIS);
if (isRefreshing){
activity.runOnUiThread(() -> {
isRefreshing = false;
adapter.updateData(isRefreshing);
});
}else {
activity.runOnUiThread(() -> {
isRefreshing = true;
adapter.updateData(isRefreshing);
});
}
}
};
handler.postDelayed(runnable, DELAY_IN_MILLIS);
}
private void loadRecyclerView() {
adapter = new ProductAdapter(dataModel, isRefreshing);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(activity);
binding.recyclerView.setLayoutManager(mLayoutManager);
binding.recyclerView.setItemAnimator(new DefaultItemAnimator());
binding.recyclerView.addItemDecoration(new ItemDecoration(requireContext()));
binding.recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
binding.recyclerView.addOnItemTouchListener(new ClickListener(activity, binding.recyclerView, (view, position) -> {
ProductTable listItem = dataModel.get(position);
Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
assert listItem != null;
intent.putExtra("id", listItem.getId());
startActivity(intent);
}));
filterTheData();
}
@Override
public void onResume() {
super.onResume();
onRefresh();
}
private void setupChart(LineChart chart, LineData data) {
((LineDataSet) data.getDataSetByIndex(0)).setCircleHoleColor(android.R.color.transparent);
chart.getDescription().setEnabled(false);
chart.setDrawGridBackground(false);
chart.setTouchEnabled(true);
chart.setDragEnabled(true);
chart.setScaleEnabled(true);
chart.setPinchZoom(false);
chart.setViewPortOffsets(10, 0, 10, 0);
chart.setData(data);
Legend legend = chart.getLegend();
legend.setEnabled(false);
chart.getAxisLeft().setEnabled(false);
chart.getAxisLeft().setSpaceTop(40);
chart.getAxisLeft().setSpaceBottom(40);
chart.getAxisRight().setEnabled(false);
chart.getXAxis().setEnabled(false);
chart.animateX(3000);
}
private LineData getData(int color) {
ArrayList<Entry> values = new ArrayList<>();
for (int i = 0; i < 30; i++) {
float val = (float) (Math.random() * (float) 100) + 3;
values.add(new Entry(i, val));
}
LineDataSet set1 = new LineDataSet(values, "DataSet 1");
set1.setLineWidth(1.75f);
set1.setCircleRadius(5f);
set1.setCircleHoleRadius(2.5f);
set1.setColor(color);
set1.setCircleColor(color);
set1.setHighLightColor(color);
set1.setDrawValues(false);
return new LineData(set1);
}
private void filterTheData() {
TextView [] paddViews = new TextView[]{binding.tvLow, binding.tvHigh, binding.tvItem, binding.tvPrice};
for (TextView view : paddViews) {
view.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down_black, 0);
}
binding.tvItem.setOnClickListener(v->{ });
binding.tvHigh.setOnClickListener(v->{ });
binding.tvLow.setOnClickListener(v->{ });
binding.tvPrice.setOnClickListener(v->{ });
}
}
|
3e060cd591da3fd00848f0414f973d294eeca379
| 2,360 |
java
|
Java
|
src/tanbo/wu/data/Menu/Diary.java
|
Libra-Ng/Java_Input-Output
|
e0159e9aad0292361069baf9b3e28f505cad8cde
|
[
"Apache-2.0"
] | null | null | null |
src/tanbo/wu/data/Menu/Diary.java
|
Libra-Ng/Java_Input-Output
|
e0159e9aad0292361069baf9b3e28f505cad8cde
|
[
"Apache-2.0"
] | null | null | null |
src/tanbo/wu/data/Menu/Diary.java
|
Libra-Ng/Java_Input-Output
|
e0159e9aad0292361069baf9b3e28f505cad8cde
|
[
"Apache-2.0"
] | null | null | null | 27.126437 | 98 | 0.509322 | 2,559 |
/**
* @Author:2017110342_吴谭波
* @Description:实现简单的写日记功能
* @Date: 2019/10/18
* @Modified By:2017110342_吴谭波
*/
package tanbo.wu.data.Menu;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
enum Weather{
sunny,rainy,cloudy,windy,snowy
}
enum Mood{
happy,sad,normal
}
public class Diary implements StoreDiary{
private Date date; //日期
private Weather weather; //天气
private Mood mood; //心情
private String title; //标题
private String content; //内容
private int countDiary = 0; //日记的篇数
Diary(Date date, Weather weather, Mood mood, String title, String content) {
this.date = date;
this.weather = weather;
this.mood = mood;
this.title = title;
this.content = content;
}
Diary() {
}
public Date getDate() {
return date;
}
String getTitle() {
return title;
}
public String getContent() {
return content;
}
@Override
public String toString(){
return "时间是:" + date.getDate() + "\n"
+ "天气是:" + weather + "\n"
+ "心情是:" + mood + "\n"
+ "日记标题是:" + title + "\n"
+ "日记内容是:" + content;
}
@Override
public void storeDiary() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("D:/DiaryContent.txt");
// FileOutputStream fileOutputStream1 = new FileOutputStream("D:/DiaryNumber.txt");
String string = this.toString();
byte[] words = string.getBytes();
fileOutputStream.write(words,0,words.length);
countDiary++;
} catch (IOException e){
e.printStackTrace();
}
}
@Override
public void readDiary() throws IOException {
try (FileInputStream fileInputStream = new FileInputStream("D:/DiaryContent.txt")) {
fileInputStream.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
3e060d2875e8a64ed332e59f472a2d27d9d2777b
| 732 |
java
|
Java
|
x-pack/qa/xpack-prefix-rest-compat/src/yamlRestTestV7Compat/java/org/elasticsearch/xpack/test/rest/XPackRestIT.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null |
x-pack/qa/xpack-prefix-rest-compat/src/yamlRestTestV7Compat/java/org/elasticsearch/xpack/test/rest/XPackRestIT.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null |
x-pack/qa/xpack-prefix-rest-compat/src/yamlRestTestV7Compat/java/org/elasticsearch/xpack/test/rest/XPackRestIT.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null | 29.28 | 79 | 0.763661 | 2,560 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.test.rest;
import com.carrotsearch.randomizedtesting.annotations.ParametersFactory;
import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate;
public class XPackRestIT extends AbstractXPackRestTest {
public XPackRestIT(ClientYamlTestCandidate testCandidate) {
super(testCandidate);
}
@ParametersFactory
public static Iterable<Object[]> parameters() throws Exception {
return createParameters();
}
}
|
3e060d41d4a5f3c567b5b156bc0182213af91fcf
| 1,274 |
java
|
Java
|
pax-web-itest/pax-web-itest-container/pax-web-itest-jetty/src/test/java/org/ops4j/pax/web/itest/jetty/war/jsp/JspNoClassesIntegrationTest.java
|
castortech/org.ops4j.pax.web
|
b1e4897ef39a4d6774f10fee372ec423a9a54925
|
[
"ECL-2.0",
"Apache-2.0"
] | 89 |
2015-01-12T14:24:18.000Z
|
2022-03-30T10:28:57.000Z
|
pax-web-itest/pax-web-itest-container/pax-web-itest-jetty/src/test/java/org/ops4j/pax/web/itest/jetty/war/jsp/JspNoClassesIntegrationTest.java
|
castortech/org.ops4j.pax.web
|
b1e4897ef39a4d6774f10fee372ec423a9a54925
|
[
"ECL-2.0",
"Apache-2.0"
] | 240 |
2015-03-19T19:24:13.000Z
|
2022-03-30T14:41:49.000Z
|
pax-web-itest/pax-web-itest-container/pax-web-itest-jetty/src/test/java/org/ops4j/pax/web/itest/jetty/war/jsp/JspNoClassesIntegrationTest.java
|
castortech/org.ops4j.pax.web
|
b1e4897ef39a4d6774f10fee372ec423a9a54925
|
[
"ECL-2.0",
"Apache-2.0"
] | 166 |
2015-01-14T00:31:00.000Z
|
2022-03-22T07:31:33.000Z
| 34.432432 | 86 | 0.769231 | 2,561 |
/*
* Copyright 2021 OPS4J.
*
* 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.ops4j.pax.web.itest.jetty.war.jsp;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.web.itest.container.war.jsp.AbstractJspNoClassesIntegrationTest;
import static org.ops4j.pax.exam.OptionUtils.combine;
@RunWith(PaxExam.class)
public class JspNoClassesIntegrationTest extends AbstractJspNoClassesIntegrationTest {
@Configuration
public Option[] configure() {
Option[] serverOptions = combine(baseConfigure(), paxWebJetty());
Option[] jspOptions = combine(serverOptions, paxWebJsp());
return combine(jspOptions, paxWebExtenderWar());
}
}
|
3e060d7efd337ea25846ebbc730989338e7fd992
| 989 |
java
|
Java
|
tapestry-core/src/test/java/org/apache/tapestry5/integration/app1/pages/PACAnnotationDemo.java
|
shisheng-1/tapestry-5
|
28ac1aebdf09d27611d111c702266b12e10b074c
|
[
"Apache-2.0"
] | 72 |
2015-02-23T16:30:56.000Z
|
2022-03-30T03:42:27.000Z
|
tapestry-core/src/test/java/org/apache/tapestry5/integration/app1/pages/PACAnnotationDemo.java
|
shisheng-1/tapestry-5
|
28ac1aebdf09d27611d111c702266b12e10b074c
|
[
"Apache-2.0"
] | 7 |
2016-03-03T10:21:45.000Z
|
2021-12-02T20:03:17.000Z
|
tapestry-core/src/test/java/org/apache/tapestry5/integration/app1/pages/PACAnnotationDemo.java
|
shisheng-1/tapestry-5
|
28ac1aebdf09d27611d111c702266b12e10b074c
|
[
"Apache-2.0"
] | 87 |
2015-02-20T09:17:50.000Z
|
2022-01-31T12:11:24.000Z
| 29.088235 | 75 | 0.745197 | 2,562 |
// Copyright 2010 The Apache Software Foundation
//
// 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.apache.tapestry5.integration.app1.pages;
import org.apache.tapestry5.annotations.PageActivationContext;
import org.apache.tapestry5.annotations.Property;
public class PACAnnotationDemo
{
@Property
@PageActivationContext
private Integer count;
@Property
private boolean countSet;
void onActivate()
{
countSet = count != null;
}
}
|
3e060e6fd8477d7c97a8268158deb6f203548530
| 5,207 |
java
|
Java
|
ambari-server/src/test/java/org/apache/ambari/server/view/RemoteAmbariClusterTest.java
|
MacgradyHuang/ApacheAmbari
|
961ce825b9e2681bf21819147b0ee72438e0b04a
|
[
"Apache-2.0"
] | 1,664 |
2015-01-03T09:35:21.000Z
|
2022-03-31T04:55:24.000Z
|
ambari-server/src/test/java/org/apache/ambari/server/view/RemoteAmbariClusterTest.java
|
MacgradyHuang/ApacheAmbari
|
961ce825b9e2681bf21819147b0ee72438e0b04a
|
[
"Apache-2.0"
] | 3,018 |
2015-02-19T20:16:10.000Z
|
2021-11-13T20:47:48.000Z
|
ambari-server/src/test/java/org/apache/ambari/server/view/RemoteAmbariClusterTest.java
|
MacgradyHuang/ApacheAmbari
|
961ce825b9e2681bf21819147b0ee72438e0b04a
|
[
"Apache-2.0"
] | 1,673 |
2015-01-06T14:14:42.000Z
|
2022-03-31T07:22:30.000Z
| 39.150376 | 124 | 0.729019 | 2,563 |
/*
* 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.ambari.server.view;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isNull;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ambari.server.orm.entities.RemoteAmbariClusterEntity;
import org.apache.ambari.view.AmbariHttpException;
import org.apache.ambari.view.AmbariStreamProvider;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class RemoteAmbariClusterTest {
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void testGetConfigurationValue() throws Exception {
AmbariStreamProvider clusterStreamProvider = createNiceMock(AmbariStreamProvider.class);
final String desiredConfigsString = "{\"Clusters\": {\"desired_configs\": {\"test-site\": {\"tag\": \"TAG\"}}}}";
final String configurationString = "{\"items\": [{\"properties\": {\"test.property.name\": \"test property value\"}}]}";
final int[] desiredConfigPolls = {0};
final int[] testConfigPolls = {0};
final String clusterPath = "/api/v1/clusters/Test";
expect(clusterStreamProvider.readFrom(eq( clusterPath + "?fields=services/ServiceInfo,hosts,Clusters"),
eq("GET"), (String) isNull(), EasyMock.anyObject())).andAnswer(new IAnswer<InputStream>() {
@Override
public InputStream answer() throws Throwable {
desiredConfigPolls[0] += 1;
return new ByteArrayInputStream(desiredConfigsString.getBytes());
}
}).anyTimes();
expect(clusterStreamProvider.readFrom(eq(clusterPath + "/configurations?(type=test-site&tag=TAG)"),
eq("GET"), (String)isNull(), EasyMock.anyObject())).andAnswer(new IAnswer<InputStream>() {
@Override
public InputStream answer() throws Throwable {
testConfigPolls[0] += 1;
return new ByteArrayInputStream(configurationString.getBytes());
}
}).anyTimes();
RemoteAmbariClusterEntity entity = createNiceMock(RemoteAmbariClusterEntity.class);
replay(clusterStreamProvider,entity);
RemoteAmbariCluster cluster = new RemoteAmbariCluster("Test", clusterPath, clusterStreamProvider);
String value = cluster.getConfigurationValue("test-site", "test.property.name");
assertEquals(value, "test property value");
assertEquals(desiredConfigPolls[0], 1);
assertEquals(testConfigPolls[0], 1);
value = cluster.getConfigurationValue("test-site", "test.property.name");
assertEquals(value, "test property value");
assertEquals(desiredConfigPolls[0], 1); // cache hit
assertEquals(testConfigPolls[0], 1);
}
@Test
public void testGetHostsForServiceComponent() throws IOException, AmbariHttpException {
final String componentHostsString = "{\"host_components\": [{" +
"\"HostRoles\": {" +
"\"cluster_name\": \"Ambari\"," +
"\"host_name\": \"host1\"}}, {" +
"\"HostRoles\": {" +
"\"cluster_name\": \"Ambari\"," +
"\"host_name\": \"host2\"}}]}";
AmbariStreamProvider clusterStreamProvider = createNiceMock(AmbariStreamProvider.class);
String service = "SERVICE";
String component = "COMPONENT";
final String clusterPath = "/api/v1/clusters/Test";
expect(clusterStreamProvider.readFrom(eq(String.format("%s/services/%s/components/%s?" +
"fields=host_components/HostRoles/host_name", clusterPath, service, component)),
eq("GET"), (String) isNull(), EasyMock.anyObject()))
.andReturn(new ByteArrayInputStream(componentHostsString.getBytes()));
RemoteAmbariClusterEntity entity = createNiceMock(RemoteAmbariClusterEntity.class);
replay(clusterStreamProvider,entity);
RemoteAmbariCluster cluster = new RemoteAmbariCluster("Test", clusterPath, clusterStreamProvider);
List<String> hosts = cluster.getHostsForServiceComponent(service,component);
Assert.assertEquals(2, hosts.size());
Assert.assertEquals("host1",hosts.get(0));
Assert.assertEquals("host2",hosts.get(1));
verify(clusterStreamProvider, entity);
}
}
|
3e060efbfa9934d147dd5bc20527f7c3c62f7d46
| 4,273 |
java
|
Java
|
app/src/main/java/com/codepath/apps/restclienttemplate/TweetDetails.java
|
sofiaaj/twitter_mock
|
eecc6ef2522a39e2c444d966996e515c2bfc925e
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/codepath/apps/restclienttemplate/TweetDetails.java
|
sofiaaj/twitter_mock
|
eecc6ef2522a39e2c444d966996e515c2bfc925e
|
[
"MIT"
] | 1 |
2019-07-06T06:21:07.000Z
|
2019-07-06T06:21:07.000Z
|
app/src/main/java/com/codepath/apps/restclienttemplate/TweetDetails.java
|
sofiaaj/twitter_mock
|
eecc6ef2522a39e2c444d966996e515c2bfc925e
|
[
"MIT"
] | null | null | null | 33.912698 | 107 | 0.653405 | 2,564 |
package com.codepath.apps.restclienttemplate;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
public class TweetDetails extends AppCompatActivity implements View.OnClickListener {
Tweet mTweet;
List<Tweet>mTweets;
// Butterknife to get view elements and populate them
@BindView(R.id.ivProfileImage) ImageView ivProfileImage;
@BindView(R.id.tvUserName) TextView tvUserName;
@BindView(R.id.tvBody) TextView tvBody;
@BindView(R.id.tvTime) TextView tvTime;
@BindView (R.id.ivRetweet) ImageView ivRetweet;
@BindView (R.id.ivHeart) ImageView ivHeart;
@BindView(R.id.ivRepost) ImageView ivRepost;
@Override
protected void onCreate(Bundle savedInstanceState) {
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.twitter_blue)));
super.onCreate(savedInstanceState);
setContentView(R.layout.item_tweet);
ButterKnife.bind(this);
// Getting tweet element and populating fields with that data
mTweet = Parcels.unwrap(getIntent().getParcelableExtra("Tweet"));
mTweets = Parcels.unwrap(getIntent().getParcelableExtra("All_Tweets"));
tvUserName.setText(mTweet.user.name);
tvBody.setText(mTweet.body);
tvTime.setText(mTweet.getRelativeTimeAgo(mTweet.createdAt));
String url= mTweet.user.profileImageUrl;
Glide.with(this)
.load(mTweet.user.profileImageUrl)
.apply(RequestOptions.circleCropTransform())
.into(ivProfileImage);
// Setting listeners for elements users can interact with
ivRetweet.setOnClickListener(this);
ivHeart.setOnClickListener(this);
ivRepost.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Able to reply in own account, tagging the original user
if (v.getId() == ivRetweet.getId()) {
Tweet curr = mTweet;
String screenName = curr.user.screenName;
Intent i = new Intent(this, ComposeActivity.class);
i.putExtra("Retweet", true);
i.putExtra("ScreenName", screenName);
startActivity(i);
// Like a tweet
} else if (v.getId() == ivHeart.getId()){
ivHeart.setImageResource(R.drawable.ic_vector_heart);
// Repost a tweet
} else if (v.getId() == ivRepost.getId()){
Tweet curr = mTweet;
sendTweet(curr.body, curr.user.screenName);
}
}
// Send a tweet through the client and update the timeline
private void sendTweet(String body, String name) {
TwitterClient client = TwitterApp.getRestClient(this);
client.sendTweet(body, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
try {
JSONObject responseJson = new JSONObject(new String(responseBody));
Tweet resultTweet = Tweet.fromJSON(responseJson);
mTweets.add(0, resultTweet);
finish();
} catch (JSONException e) {
Log.e("ComposeActivity", "Error parsing response", e);
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
}
|
3e061068ebca7e5e3534afffa97f1bdac782ecfc
| 1,510 |
java
|
Java
|
app/src/main/java/com/githang/statusbar/demo/JianBianActivity.java
|
Zachary46/status-bar-compat-master
|
f65193a55e9f590576c39ab359d217a5e0c63c69
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/githang/statusbar/demo/JianBianActivity.java
|
Zachary46/status-bar-compat-master
|
f65193a55e9f590576c39ab359d217a5e0c63c69
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/githang/statusbar/demo/JianBianActivity.java
|
Zachary46/status-bar-compat-master
|
f65193a55e9f590576c39ab359d217a5e0c63c69
|
[
"Apache-2.0"
] | null | null | null | 36.829268 | 129 | 0.703311 | 2,565 |
package com.githang.statusbar.demo;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.githang.statusbar.StatusBarCompat;
import com.githang.statusbarcompat.demo.R;
public class JianBianActivity extends AppCompatActivity {
public static int statusBarHeight = 0;
Toolbar toolbar;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jian_bian);
getStatusBarHeight();
toolbar= (Toolbar) findViewById(R.id.toolbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
toolbar.setPadding(toolbar.getPaddingLeft(), statusBarHeight, toolbar.getPaddingRight(), toolbar.getPaddingBottom());
}
setSupportActionBar(toolbar);
StatusBarCompat.setTranslucent(getWindow(),true);//true表示浸入状态栏
}
private void getStatusBarHeight() {
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
statusBarHeight = getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
3e0611cd8a8ac551229aac2e32447250951148f2
| 592 |
java
|
Java
|
src/main/java/awesome/jigsaw/util/JigsawUtil.java
|
demondevilhades/jigsaw
|
4906d2d266273eaa1e686630da06b433c90bd026
|
[
"MIT"
] | null | null | null |
src/main/java/awesome/jigsaw/util/JigsawUtil.java
|
demondevilhades/jigsaw
|
4906d2d266273eaa1e686630da06b433c90bd026
|
[
"MIT"
] | null | null | null |
src/main/java/awesome/jigsaw/util/JigsawUtil.java
|
demondevilhades/jigsaw
|
4906d2d266273eaa1e686630da06b433c90bd026
|
[
"MIT"
] | null | null | null | 19.733333 | 127 | 0.611486 | 2,566 |
package awesome.jigsaw.util;
import java.awt.image.BufferedImage;
import awesome.jigsaw.entity.JPiece;
/**
*
* @author awesome
*/
public interface JigsawUtil {
/**
*
* @param ptkBufferedImage
* @return
*/
public JPiece init(final BufferedImage ptkBufferedImage);
/**
*
* @param picBufferedImage
* @param startX
* @param startY
* @param jPiece
* @return
*/
public BufferedImage[] cut(final BufferedImage picBufferedImage, final int startX, final int startY, final JPiece jPiece);
}
|
3e0612b34e6626b06076ed6e8066d3f607d008f9
| 7,526 |
java
|
Java
|
java/com/google/gerrit/server/project/testing/Util.java
|
ycj211/gerrit_chinese
|
6daa275bb3337f7e4c277740319826ba0829646f
|
[
"Apache-2.0"
] | null | null | null |
java/com/google/gerrit/server/project/testing/Util.java
|
ycj211/gerrit_chinese
|
6daa275bb3337f7e4c277740319826ba0829646f
|
[
"Apache-2.0"
] | 2 |
2019-01-18T01:14:30.000Z
|
2019-01-18T01:17:30.000Z
|
java/com/google/gerrit/server/project/testing/Util.java
|
ycj211/gerrit_chinese
|
6daa275bb3337f7e4c277740319826ba0829646f
|
[
"Apache-2.0"
] | null | null | null | 33.008772 | 100 | 0.707149 | 2,567 |
// Copyright (C) 2013 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.google.gerrit.server.project.testing;
import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.common.data.LabelFunction;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.common.data.LabelValue;
import com.google.gerrit.common.data.Permission;
import com.google.gerrit.common.data.PermissionRange;
import com.google.gerrit.common.data.PermissionRule;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.project.ProjectConfig;
import java.util.Arrays;
public class Util {
public static final AccountGroup.UUID ADMIN = new AccountGroup.UUID("test.admin");
public static final AccountGroup.UUID DEVS = new AccountGroup.UUID("test.devs");
public static final LabelType codeReview() {
return category(
"Code-Review",
value(2, "我觉得没问题,已验证"),
value(1, "我觉得没问题,但仍需验证"),
value(0, "不评分"),
value(-1, "我认为这次提交不可被合并"),
value(-2, "不得合并"));
}
public static final LabelType verified() {
return category("Verified", value(1, "Verified"), value(0, "No score"), value(-1, "Fails"));
}
public static final LabelType patchSetLock() {
LabelType label =
category("Patch-Set-Lock", value(1, "Patch Set Locked"), value(0, "Patch Set Unlocked"));
label.setFunction(LabelFunction.PATCH_SET_LOCK);
return label;
}
public static LabelValue value(int value, String text) {
return new LabelValue((short) value, text);
}
public static LabelType category(String name, LabelValue... values) {
return new LabelType(name, Arrays.asList(values));
}
public static PermissionRule newRule(ProjectConfig project, AccountGroup.UUID groupUUID) {
GroupReference group = new GroupReference(groupUUID, groupUUID.get());
group = project.resolve(group);
return new PermissionRule(group);
}
public static PermissionRule allow(
ProjectConfig project,
String permissionName,
int min,
int max,
AccountGroup.UUID group,
String ref) {
PermissionRule rule = newRule(project, group);
rule.setMin(min);
rule.setMax(max);
return grant(project, permissionName, rule, ref);
}
public static PermissionRule allowExclusive(
ProjectConfig project,
String permissionName,
int min,
int max,
AccountGroup.UUID group,
String ref) {
PermissionRule rule = newRule(project, group);
rule.setMin(min);
rule.setMax(max);
return grant(project, permissionName, rule, ref, true);
}
public static PermissionRule block(
ProjectConfig project,
String permissionName,
int min,
int max,
AccountGroup.UUID group,
String ref) {
PermissionRule rule = newRule(project, group);
rule.setMin(min);
rule.setMax(max);
PermissionRule r = grant(project, permissionName, rule, ref);
r.setBlock();
return r;
}
public static PermissionRule allow(
ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
return grant(project, permissionName, newRule(project, group), ref);
}
public static PermissionRule allow(
ProjectConfig project,
String permissionName,
AccountGroup.UUID group,
String ref,
boolean exclusive) {
return grant(project, permissionName, newRule(project, group), ref, exclusive);
}
public static PermissionRule allow(
ProjectConfig project, String capabilityName, AccountGroup.UUID group) {
PermissionRule rule = newRule(project, group);
project
.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
.getPermission(capabilityName, true)
.add(rule);
if (GlobalCapability.hasRange(capabilityName)) {
PermissionRange.WithDefaults range = GlobalCapability.getRange(capabilityName);
if (range != null) {
rule.setRange(range.getDefaultMin(), range.getDefaultMax());
}
}
return rule;
}
public static PermissionRule remove(
ProjectConfig project, String capabilityName, AccountGroup.UUID group) {
PermissionRule rule = newRule(project, group);
project
.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
.getPermission(capabilityName, true)
.remove(rule);
return rule;
}
public static PermissionRule remove(
ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
PermissionRule rule = newRule(project, group);
project.getAccessSection(ref, true).getPermission(permissionName, true).remove(rule);
return rule;
}
public static PermissionRule block(
ProjectConfig project, String capabilityName, AccountGroup.UUID group) {
PermissionRule rule = newRule(project, group);
project
.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
.getPermission(capabilityName, true)
.add(rule);
return rule;
}
public static PermissionRule block(
ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
PermissionRule r = grant(project, permissionName, newRule(project, group), ref);
r.setBlock();
return r;
}
public static PermissionRule blockLabel(
ProjectConfig project, String labelName, AccountGroup.UUID group, String ref) {
return blockLabel(project, labelName, -1, 1, group, ref);
}
public static PermissionRule blockLabel(
ProjectConfig project,
String labelName,
int min,
int max,
AccountGroup.UUID group,
String ref) {
PermissionRule r = grant(project, Permission.LABEL + labelName, newRule(project, group), ref);
r.setBlock();
r.setRange(min, max);
return r;
}
public static PermissionRule deny(
ProjectConfig project, String permissionName, AccountGroup.UUID group, String ref) {
PermissionRule r = grant(project, permissionName, newRule(project, group), ref);
r.setDeny();
return r;
}
public static void doNotInherit(ProjectConfig project, String permissionName, String ref) {
project
.getAccessSection(ref, true) //
.getPermission(permissionName, true) //
.setExclusiveGroup(true);
}
private static PermissionRule grant(
ProjectConfig project, String permissionName, PermissionRule rule, String ref) {
return grant(project, permissionName, rule, ref, false);
}
private static PermissionRule grant(
ProjectConfig project,
String permissionName,
PermissionRule rule,
String ref,
boolean exclusive) {
Permission permission = project.getAccessSection(ref, true).getPermission(permissionName, true);
if (exclusive) {
permission.setExclusiveGroup(exclusive);
}
permission.add(rule);
return rule;
}
private Util() {}
}
|
3e06130a1e1adaf74c65cd40b1f0f30b6ab6879f
| 2,031 |
java
|
Java
|
app/src/main/java/com/onimus/munote/repository/database/RecordSpinnerNotesYearAdapter.java
|
MurilloComino/Munotes
|
887934e4b1cbe9579730f1deb71728e268885d1a
|
[
"Apache-2.0"
] | 1 |
2020-05-31T08:50:11.000Z
|
2020-05-31T08:50:11.000Z
|
app/src/main/java/com/onimus/munote/repository/database/RecordSpinnerNotesYearAdapter.java
|
MurilloComino/Munotes
|
887934e4b1cbe9579730f1deb71728e268885d1a
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/onimus/munote/repository/database/RecordSpinnerNotesYearAdapter.java
|
MurilloComino/Munotes
|
887934e4b1cbe9579730f1deb71728e268885d1a
|
[
"Apache-2.0"
] | null | null | null | 24.878049 | 113 | 0.663235 | 2,568 |
/*
*
* * Created by Murillo Comino on 09/02/19 12:26
* * Github: github.com/MurilloComino
* * StackOverFlow: pt.stackoverflow.com/users/128573
* * Email: [email protected]
* *
* * Copyright (c) 2019 . All rights reserved.
* * Last modified 09/02/19 12:11
*
*/
package com.onimus.munote.repository.database;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.onimus.munote.R;
import com.onimus.munote.repository.dao.NotesDao;
import java.util.ArrayList;
import java.util.Objects;
public class RecordSpinnerNotesYearAdapter extends BaseAdapter {
private final Context context;
private final int layout;
private final ArrayList<HMAuxNotes> hmAux;
public RecordSpinnerNotesYearAdapter(Context context, int layout, ArrayList<HMAuxNotes> hmAux) {
this.hmAux = hmAux;
this.context = context;
this.layout = layout;
}
@Override
public int getCount() {
return hmAux.size();
}
@Override
public Object getItem(int i) {
return hmAux.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
private class ViewHolder {
TextView cel_year;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = Objects.requireNonNull(inflater).inflate(layout, viewGroup, false);
holder.cel_year = row.findViewById(R.id.cel_year);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
//monta a listview
HMAuxNotes model = hmAux.get(i);
holder.cel_year.setText(model.get(NotesDao.YEAR));
return row;
}
}
|
3e06141887a9c5d5522c9a0f7e6f7442824caf78
| 2,619 |
java
|
Java
|
examples/spring-hateoas/src/test/java/com/blazebit/persistence/examples/spring/hateoas/repository/SampleTest.java
|
sullrich84/blaze-persistence
|
f5a374fedf8cb1a24c769e37de56bd44e91afcf3
|
[
"ECL-2.0",
"Apache-2.0"
] | 884 |
2015-02-17T16:29:05.000Z
|
2022-03-31T05:01:09.000Z
|
examples/spring-hateoas/src/test/java/com/blazebit/persistence/examples/spring/hateoas/repository/SampleTest.java
|
sullrich84/blaze-persistence
|
f5a374fedf8cb1a24c769e37de56bd44e91afcf3
|
[
"ECL-2.0",
"Apache-2.0"
] | 1,105 |
2015-01-07T08:49:17.000Z
|
2022-03-31T09:40:50.000Z
|
examples/spring-hateoas/src/test/java/com/blazebit/persistence/examples/spring/hateoas/repository/SampleTest.java
|
sullrich84/blaze-persistence
|
f5a374fedf8cb1a24c769e37de56bd44e91afcf3
|
[
"ECL-2.0",
"Apache-2.0"
] | 66 |
2015-03-12T16:43:39.000Z
|
2022-03-22T06:55:15.000Z
| 41.571429 | 108 | 0.790378 | 2,569 |
/*
* Copyright 2014 - 2021 Blazebit.
*
* 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.blazebit.persistence.examples.spring.hateoas.repository;
import com.blazebit.persistence.examples.spring.hateoas.model.Cat;
import com.blazebit.persistence.integration.view.spring.EnableEntityViews;
import com.blazebit.persistence.spring.data.impl.repository.BlazePersistenceRepositoryFactoryBean;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration;
import org.springframework.data.web.config.SpringDataWebConfiguration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Christian Beikov
* @since 1.2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SampleTest.TestConfig.class, HateoasAwareSpringDataWebConfiguration.class})
public class SampleTest extends AbstractSampleTest {
@Autowired
private CatRepository catRepository;
@Test
public void sampleTest() {
final Page<Cat> page = catRepository.findAll(null, null);
Assert.assertEquals(6, page.getNumberOfElements());
}
@Configuration
@ComponentScan("com.blazebit.persistence.examples.spring.hateoas")
@ImportResource({"/META-INF/test-config.xml"})
@EnableEntityViews(basePackages = { "com.blazebit.persistence.examples.spring.hateoas.view"})
@EnableJpaRepositories(
basePackages = "com.blazebit.persistence.examples.spring.hateoas.repository",
repositoryFactoryBeanClass = BlazePersistenceRepositoryFactoryBean.class)
static class TestConfig {
}
}
|
3e06150657791fad8b94ac97665cadd8ff9fe2b1
| 3,010 |
java
|
Java
|
rabbitmq/src/main/java/com/lvdreamer/rabbitmq/consumer/TopicRabbitMqConsumer.java
|
lvdreamer/CodeNotes
|
757085c937024c1d5196be4caa216f8504c60388
|
[
"MIT"
] | null | null | null |
rabbitmq/src/main/java/com/lvdreamer/rabbitmq/consumer/TopicRabbitMqConsumer.java
|
lvdreamer/CodeNotes
|
757085c937024c1d5196be4caa216f8504c60388
|
[
"MIT"
] | null | null | null |
rabbitmq/src/main/java/com/lvdreamer/rabbitmq/consumer/TopicRabbitMqConsumer.java
|
lvdreamer/CodeNotes
|
757085c937024c1d5196be4caa216f8504c60388
|
[
"MIT"
] | null | null | null | 43.623188 | 107 | 0.649834 | 2,570 |
package com.lvdreamer.rabbitmq.consumer;
import com.lvdreamer.rabbitmq.RabbitConfig;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class TopicRabbitMqConsumer {
private final static Logger logger = LoggerFactory.getLogger(TopicRabbitMqConsumer.class);
@RabbitHandler
@RabbitListener(containerFactory = "manualAckRabbitListenerContainerFactory", bindings = @QueueBinding(
value = @Queue(value = RabbitConfig.TOPIC_QUEUE_ONE,
durable = "true"),
exchange = @Exchange(value = RabbitConfig.TOPIC_EXCHANGE,
ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC), key = "*.one"))
public void receive(String data, Message message, Channel channel) {
logger.info("Consumer[1] receive data : {}", data);
logger.debug("Consumer[1] message data : {}", message);
try {
//休眠3秒钟观察状态
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (IOException e) {
logger.error("ack确认异常", e);
}
}
@RabbitHandler
@RabbitListener(containerFactory = "manualAckRabbitListenerContainerFactory", bindings = @QueueBinding(
value = @Queue(value = RabbitConfig.TOPIC_QUEUE_ONE,
durable = "true"),
exchange = @Exchange(value = RabbitConfig.TOPIC_EXCHANGE,
ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC), key = "*.one"))
public void receive2(String data, Message message, Channel channel) {
logger.info("Consumer[2] receive data : {}", data);
logger.debug("Consumer[2] message data : {}", message);
try {
//休眠3秒钟观察状态
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (IOException e) {
logger.error("ack确认异常", e);
}
}
@RabbitHandler
@RabbitListener(containerFactory = "manualAckRabbitListenerContainerFactory", bindings = @QueueBinding(
value = @Queue(value = RabbitConfig.TOPIC_QUEUE_TWO,
durable = "true"),
exchange = @Exchange(value = RabbitConfig.TOPIC_EXCHANGE,
ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC), key = "*.one"))
public void receive3(String data, Message message, Channel channel) {
logger.info("Consumer[3] receive data : {}", data);
logger.debug("Consumer[3] message data : {}", message);
try {
//休眠3秒钟观察状态
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (IOException e) {
logger.error("ack确认异常", e);
}
}
}
|
3e061592f93f936a02d16029d153c7f8e2b44173
| 470 |
java
|
Java
|
src/main/java/com/github/brawaru/vanillafixes/VanillaFixes.java
|
Brawaru/VanillaFixes
|
fa3d30affb7f5adf98dd707e66109feadac19524
|
[
"MIT"
] | null | null | null |
src/main/java/com/github/brawaru/vanillafixes/VanillaFixes.java
|
Brawaru/VanillaFixes
|
fa3d30affb7f5adf98dd707e66109feadac19524
|
[
"MIT"
] | 1 |
2020-11-30T15:01:25.000Z
|
2020-12-09T01:55:16.000Z
|
src/main/java/com/github/brawaru/vanillafixes/VanillaFixes.java
|
Brawaru/VanillaFixes
|
fa3d30affb7f5adf98dd707e66109feadac19524
|
[
"MIT"
] | null | null | null | 23.5 | 69 | 0.721277 | 2,571 |
package com.github.brawaru.vanillafixes;
import com.github.brawaru.vanillafixes.fixes.dirtypath.DirtyPath;
import com.github.brawaru.vanillafixes.fixes.doubledoors.DoubleDoors;
import org.bukkit.plugin.java.JavaPlugin;
public final class VanillaFixes extends JavaPlugin {
@Override
public void onEnable() {
new DoubleDoors(this);
new DirtyPath(this);
}
@Override
public void onDisable() {
// Plugin shutdown logic
}
}
|
3e0616a10691bc6c16743325934323a9fe96a3ca
| 2,170 |
java
|
Java
|
src/main/java/io/vacco/oruzka/core/OzReflect.java
|
vaccovecrana/ufn
|
fb0bcf4c3187c29fe560a10000ce45ab0a59d885
|
[
"MIT"
] | null | null | null |
src/main/java/io/vacco/oruzka/core/OzReflect.java
|
vaccovecrana/ufn
|
fb0bcf4c3187c29fe560a10000ce45ab0a59d885
|
[
"MIT"
] | 3 |
2020-09-25T11:23:38.000Z
|
2021-12-25T05:08:28.000Z
|
src/main/java/io/vacco/oruzka/core/OzReflect.java
|
vaccovecrana/ufn
|
fb0bcf4c3187c29fe560a10000ce45ab0a59d885
|
[
"MIT"
] | 1 |
2021-07-11T15:50:26.000Z
|
2021-07-11T15:50:26.000Z
| 27.820513 | 67 | 0.626728 | 2,572 |
package io.vacco.oruzka.core;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class OzReflect {
public static Class<?> toWrapperClass(Class<?> type) {
if (!type.isPrimitive()) return type;
else if (int.class.equals(type)) { return Integer.class; }
else if (double.class.equals(type)) { return Double.class; }
else if (char.class.equals(type)) { return Character.class; }
else if (boolean.class.equals(type)) { return Boolean.class; }
else if (long.class.equals(type)) { return Long.class; }
else if (float.class.equals(type)) { return Float.class; }
else if (short.class.equals(type)) { return Short.class; }
else if (byte.class.equals(type)) { return Byte.class; }
return type;
}
public static boolean isWrapperType(Class<?> type) {
return type == Boolean.class
|| type == Integer.class
|| type == Character.class
|| type == Byte.class
|| type == Short.class
|| type == Double.class
|| type == Long.class
|| type == Float.class;
}
public static boolean isPrimitiveOrWrapper(final Class<?> type) {
if (type == null) { return false; }
return type.isPrimitive() || isWrapperType(type);
}
public static boolean isInteger(Object o) {
return o instanceof Integer
|| o instanceof Byte
|| o instanceof Short
|| o instanceof Long;
}
public static boolean isRational(Object o) {
return o instanceof Double || o instanceof Float;
}
public static boolean isBoolean(Object o) {
return o instanceof Boolean;
}
public static boolean isEnum(Object o) {
return o instanceof Enum<?>;
}
public static boolean isTextual(Object o) {
return o instanceof String
|| o instanceof Character;
}
public static boolean isCollection(Object o) {
return o instanceof List<?>
|| o instanceof Map<?, ?>
|| o instanceof Set<?>
|| o != null && o.getClass().isArray();
}
public static boolean isBaseType(Object o) {
return isInteger(o)
|| isRational(o)
|| isTextual(o)
|| isEnum(o)
|| isBoolean(o);
}
}
|
3e0616b9bb191850f8a8bf12f7fd090d8d5feb21
| 2,298 |
java
|
Java
|
src/main/java/org/organicdesign/dataOrient/chapter3/PChapter3.java
|
GlenKPeterson/DataOrientedExamples
|
ff14060b779cf0586ba429ccf1e5d48d171ae403
|
[
"Apache-2.0"
] | 1 |
2021-06-22T08:02:49.000Z
|
2021-06-22T08:02:49.000Z
|
src/main/java/org/organicdesign/dataOrient/chapter3/PChapter3.java
|
GlenKPeterson/DataOrientedExamples
|
ff14060b779cf0586ba429ccf1e5d48d171ae403
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/organicdesign/dataOrient/chapter3/PChapter3.java
|
GlenKPeterson/DataOrientedExamples
|
ff14060b779cf0586ba429ccf1e5d48d171ae403
|
[
"Apache-2.0"
] | 1 |
2021-03-01T20:51:25.000Z
|
2021-03-01T20:51:25.000Z
| 43.358491 | 120 | 0.560487 | 2,573 |
package org.organicdesign.dataOrient.chapter3;
import org.organicdesign.fp.collections.ImList;
import org.organicdesign.fp.tuple.Tuple3;
import java.util.Map;
import static org.organicdesign.fp.StaticImports.tup;
class PChapter3 {
public static ImList<String> pAuthorNames(PCatalog catalogData, PBook book) {
var authorIds = book.authorIds();
return authorIds.map(authorId -> catalogData.authorsById()
.get(authorId)
.name())
.toImList();
}
public static Tuple3<String,String,ImList<String>> pBookInfo(PCatalog catalogData, PBook book) {
return tup(book.title(), book.isbn(), pAuthorNames(catalogData, book));
}
public static PBookInfo pBookInfo2(PCatalog catalogData, PBook book) {
return new PBookInfo(book.title(), book.isbn(), pAuthorNames(catalogData, book));
}
public static ImList<Tuple3<String,String,ImList<String>>> pSearchBooksByTitle(PCatalog catalogData, String query) {
var allBooks = catalogData.booksByIsbn();
var matchingBooks = allBooks.filter(kv -> kv.getValue()
.title()
.contains(query));
return matchingBooks.map(kv -> pBookInfo(catalogData, kv.getValue())).toImList();
}
public static ImList<PBookInfo> pSearchBooksByTitle2(PCatalog catalogData, String query) {
var allBooks = catalogData.booksByIsbn();
var matchingBooks = allBooks.filter(kv -> kv.getValue()
.title()
.contains(query));
return matchingBooks.map(kv -> pBookInfo2(catalogData, kv.getValue())).toImList();
}
public static ImList<PBookInfo> pSearchBooksByTitle3(PCatalog catalogData, String query) {
return catalogData.booksByIsbn()
.map(Map.Entry::getValue)
.filter(book -> book
.title()
.contains(query))
.map(book -> pBookInfo2(catalogData, book)).toImList();
}
}
|
3e06180094260b4747b00fdd20360b10096cce65
| 1,923 |
java
|
Java
|
src/main/java/org/mym/ksuite/service/kong/payload/process/PluginPayloadProcess.java
|
coxon/K-Suite
|
9b578071c927ce893d08c59af3f7e6a5b840e6e6
|
[
"Apache-2.0"
] | 1 |
2021-09-02T01:32:00.000Z
|
2021-09-02T01:32:00.000Z
|
src/main/java/org/mym/ksuite/service/kong/payload/process/PluginPayloadProcess.java
|
coxon/K-Suite
|
9b578071c927ce893d08c59af3f7e6a5b840e6e6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/mym/ksuite/service/kong/payload/process/PluginPayloadProcess.java
|
coxon/K-Suite
|
9b578071c927ce893d08c59af3f7e6a5b840e6e6
|
[
"Apache-2.0"
] | null | null | null | 28.701493 | 95 | 0.676027 | 2,574 |
package org.mym.ksuite.service.kong.payload.process;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.mym.ksuite.em.KongEntity;
import org.mym.ksuite.service.kong.IKongPluginModelSv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
/**
* 不同插件在不同Kong版本的config.anonymous 的schema要求各不一样,必须独立处理
* @author zhangchao
*/
@Service
@Slf4j
public class PluginPayloadProcess implements IKongPayloadProcess {
private static final String CONFIG = "config";
private static final String CONFIG_ANONYMOUS = "anonymous";
private static final String CONFIG_NAME = "name";
private static final String FIELD_NONE_VALUE = "none_value";
@Autowired
IKongPluginModelSv kongPluginModelSv;
@Override
public KongEntity apply() {
return KongEntity.PLUGINS;
}
@Override
public void process(HttpMethod httpMethod, JSONObject payload) {
if (payload == null) {
return;
}
if (!payload.containsKey(CONFIG)){
return;
}
JSONObject config = payload.getJSONObject(CONFIG);
if (!config.containsKey(CONFIG_ANONYMOUS)) {
return;
}
String anonymous = config.getString(CONFIG_ANONYMOUS);
if (anonymous != null) {
return;
}
String name = payload.getString(CONFIG_NAME);
JSONObject pluginModel = kongPluginModelSv.getPluginModel(name);
if (pluginModel==null){
return;
}
JSONObject fieldModel = kongPluginModelSv.getPluginField(pluginModel,CONFIG_ANONYMOUS);
if (fieldModel==null){
return;
}
if (fieldModel.containsKey(FIELD_NONE_VALUE)){
config.put(CONFIG_ANONYMOUS,fieldModel.get(FIELD_NONE_VALUE));
}
return;
}
}
|
3e06180e1f13511b6700519ac0b076ed6a282786
| 6,088 |
java
|
Java
|
NotificationHubs/src/com/windowsazure/messaging/Notification.java
|
Neofonie/azure-notificationhubs-java-backend
|
718825a2e5bb5ea604bf0cd6c639977a0a4a4adf
|
[
"Apache-2.0"
] | null | null | null |
NotificationHubs/src/com/windowsazure/messaging/Notification.java
|
Neofonie/azure-notificationhubs-java-backend
|
718825a2e5bb5ea604bf0cd6c639977a0a4a4adf
|
[
"Apache-2.0"
] | null | null | null |
NotificationHubs/src/com/windowsazure/messaging/Notification.java
|
Neofonie/azure-notificationhubs-java-backend
|
718825a2e5bb5ea604bf0cd6c639977a0a4a4adf
|
[
"Apache-2.0"
] | null | null | null | 25.906383 | 88 | 0.674113 | 2,575 |
package com.windowsazure.messaging;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.http.entity.ContentType;
/**
*
* Class representing a generic notification.
*
*/
public class Notification {
private Map<String, String> headers = new HashMap<String, String>();
private String body;
private ContentType contentType;
/**
* Utility method to set up a native notification for WNS. Sets the
* X-WNS-Type headers based on the body provided. If you want to send raw
* notifications you have to set the X-WNS header and ContentType after creating this
* notification or use createWindowsRawNotification method
*
* @param body
* @return
*/
public static Notification createWindowsNotification(String body) {
Notification n = new Notification();
n.body = body;
n.headers.put("ServiceBusNotification-Format", "windows");
if (body.contains("<toast>"))
n.headers.put("X-WNS-Type", "wns/toast");
if (body.contains("<tile>"))
n.headers.put("X-WNS-Type", "wns/tile");
if (body.contains("<badge>"))
n.headers.put("X-WNS-Type", "wns/badge");
if (body.startsWith("<")) {
n.contentType = ContentType.APPLICATION_XML;
}
return n;
}
/**
* Utility method to set up a native notification for WNS. Sets the
* X-WNS-Type header to "wns/raw" in order of sending of raw notification.
*
* @param body
* @return
*/
public static Notification createWindowsRawNotification(String body) {
Notification n = new Notification();
n.body = body;
n.headers.put("ServiceBusNotification-Format", "windows");
n.headers.put("X-WNS-Type", "wns/raw");
n.contentType = ContentType.APPLICATION_OCTET_STREAM;
return n;
}
/**
* Utility method to set up a native notification for APNs.
* An expiry Date of 1 day is set by default.
* @param body
* @return
*/
public static Notification createAppleNotifiation(String body) {
Date now = new Date();
Date tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
return createAppleNotification(body, tomorrow);
}
/**
* Utility method to set up a native notification for APNs.
* Enables to set the expiry date of the notification for the APNs QoS.
* @param body
* @param expiry - the expiration date of this notification.
* a null value will be interpreted as 0 seconds.
* @return
*/
public static Notification createAppleNotification(String body, Date expiry) {
Notification n = new Notification();
n.body = body;
n.contentType = ContentType.APPLICATION_JSON;
n.headers.put("ServiceBusNotification-Format", "apple");
if(expiry != null){
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String expiryString = formatter.format(expiry.getTime());
n.headers.put("ServiceBusNotification-Apns-Expiry", expiryString);
}
return n;
}
/**
* Utility method to set up a native notification for GCM.
*
* @param body
* @return
*/
public static Notification createGcmNotifiation(String body) {
Notification n = new Notification();
n.body = body;
n.contentType = ContentType.APPLICATION_JSON;
n.headers.put("ServiceBusNotification-Format", "gcm");
return n;
}
/**
* Utility method to set up a native notification for ADM.
*
* @param body
* @return
*/
public static Notification createAdmNotifiation(String body) {
Notification n = new Notification();
n.body = body;
n.contentType = ContentType.APPLICATION_JSON;
n.headers.put("ServiceBusNotification-Format", "adm");
return n;
}
/**
* Utility method to set up a native notification for Baidu PNS.
*
* @param body
* @return
*/
public static Notification createBaiduNotifiation(String body) {
Notification n = new Notification();
n.body = body;
n.contentType = ContentType.APPLICATION_JSON;
n.headers.put("ServiceBusNotification-Format", "baidu");
return n;
}
/**
* Utility method to set up a native notification for MPNS. Sets the
* X-WindowsPhone-Target and X-NotificationClass headers based on the body
* provided. Raw notifications are not supported for MPNS.
*
* @param body
* @return
*/
public static Notification createMpnsNotifiation(String body) {
Notification n = new Notification();
n.body = body;
n.headers.put("ServiceBusNotification-Format", "windowsphone");
if (body.contains("<wp:Toast>")) {
n.headers.put("X-WindowsPhone-Target", "toast");
n.headers.put("X-NotificationClass", "2");
}
if (body.contains("<wp:Tile>")) {
n.headers.put("X-WindowsPhone-Target", "tile");
n.headers.put("X-NotificationClass", "1");
}
if (body.startsWith("<")) {
n.contentType = ContentType.APPLICATION_XML;
}
return n;
}
/**
* Utility method to create a notification object representing a template notification.
*
* @param properties
* @return
*/
public static Notification createTemplateNotification(
Map<String, String> properties) {
Notification n = new Notification();
StringBuffer buf = new StringBuffer();
buf.append("{");
for (Iterator<String> iterator = properties.keySet().iterator(); iterator
.hasNext();) {
String key = iterator.next();
buf.append("\"" + key + "\":\"" + properties.get(key) + "\"");
if (iterator.hasNext())
buf.append(",");
}
buf.append("}");
n.body = buf.toString();
n.contentType = ContentType.APPLICATION_JSON;
n.headers.put("ServiceBusNotification-Format", "template");
return n;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public ContentType getContentType() {
return contentType;
}
public void setContentType(ContentType contentType) {
this.contentType = contentType;
}
}
|
3e06185a94c5dfe18fc538e1409893aa3b8a99b2
| 1,563 |
java
|
Java
|
modules/iot-catalogue-elements/iot-catalogue-elements-api/src/main/java/com/iot_catalogue/service/SubscriptionServiceWrapper.java
|
unparallel-innovation/iot-catalogue-plugin-liferay
|
222c2eec5272d8e97fd1bf3a4f000507afe6b90c
|
[
"Apache-2.0"
] | null | null | null |
modules/iot-catalogue-elements/iot-catalogue-elements-api/src/main/java/com/iot_catalogue/service/SubscriptionServiceWrapper.java
|
unparallel-innovation/iot-catalogue-plugin-liferay
|
222c2eec5272d8e97fd1bf3a4f000507afe6b90c
|
[
"Apache-2.0"
] | 1 |
2022-03-15T11:11:42.000Z
|
2022-03-15T11:11:42.000Z
|
modules/iot-catalogue-elements/iot-catalogue-elements-api/src/main/java/com/iot_catalogue/service/SubscriptionServiceWrapper.java
|
unparallel-innovation/iot-catalogue-plugin-liferay
|
222c2eec5272d8e97fd1bf3a4f000507afe6b90c
|
[
"Apache-2.0"
] | null | null | null | 28.418182 | 80 | 0.777991 | 2,576 |
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.iot_catalogue.service;
import com.liferay.portal.kernel.service.ServiceWrapper;
/**
* Provides a wrapper for {@link SubscriptionService}.
*
* @author Brian Wing Shun Chan
* @see SubscriptionService
* @generated
*/
public class SubscriptionServiceWrapper
implements ServiceWrapper<SubscriptionService>, SubscriptionService {
public SubscriptionServiceWrapper(SubscriptionService subscriptionService) {
_subscriptionService = subscriptionService;
}
/**
* Returns the OSGi service identifier.
*
* @return the OSGi service identifier
*/
@Override
public String getOSGiServiceIdentifier() {
return _subscriptionService.getOSGiServiceIdentifier();
}
@Override
public SubscriptionService getWrappedService() {
return _subscriptionService;
}
@Override
public void setWrappedService(SubscriptionService subscriptionService) {
_subscriptionService = subscriptionService;
}
private SubscriptionService _subscriptionService;
}
|
3e0619ba06bdf39f09b3828aea7f70d5ab0c2fdd
| 1,398 |
java
|
Java
|
src/main/java/com/crossover/ivolunteer/presentation/dto/EnderecoDto.java
|
team-crossover/ivolunteer-api
|
46ab68fa7646762946254d542a2a4e34f004636a
|
[
"MIT"
] | null | null | null |
src/main/java/com/crossover/ivolunteer/presentation/dto/EnderecoDto.java
|
team-crossover/ivolunteer-api
|
46ab68fa7646762946254d542a2a4e34f004636a
|
[
"MIT"
] | null | null | null |
src/main/java/com/crossover/ivolunteer/presentation/dto/EnderecoDto.java
|
team-crossover/ivolunteer-api
|
46ab68fa7646762946254d542a2a4e34f004636a
|
[
"MIT"
] | null | null | null | 23.694915 | 57 | 0.644492 | 2,577 |
package com.crossover.ivolunteer.presentation.dto;
import com.crossover.ivolunteer.business.entity.Endereco;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class EnderecoDto {
private Long id;
@NotBlank
private String uf;
@NotBlank
private String cidade;
@NotBlank
private String cep;
@NotBlank
private String bairro;
@NotBlank
private String complemento1;
private String complemento2;
public EnderecoDto(Endereco endereco) {
this.id = endereco.getId();
this.uf = endereco.getUf();
this.cidade = endereco.getCidade();
this.cep = endereco.getCep();
this.bairro = endereco.getBairro();
this.complemento1 = endereco.getComplemento1();
this.complemento2 = endereco.getComplemento2();
}
public Endereco toEntity() {
return Endereco.builder()
.id(id)
.uf(getUf())
.cidade(getCidade())
.cep(getCep())
.bairro(getBairro())
.complemento1(getComplemento1())
.complemento2(getComplemento2())
.build();
}
}
|
3e061a0cb9a7d8a57bcb7831233c87154da62e02
| 1,118 |
java
|
Java
|
player-app/src/main/java/org/gameontext/player/JsonProvider.java
|
WASdev/gameon-player
|
c51ba9d9a47a160a36ff72281b845d4fc79291be
|
[
"Apache-2.0"
] | 3 |
2016-12-08T03:51:29.000Z
|
2019-09-10T09:07:27.000Z
|
player-app/src/main/java/org/gameontext/player/JsonProvider.java
|
WASdev/gameon-player
|
c51ba9d9a47a160a36ff72281b845d4fc79291be
|
[
"Apache-2.0"
] | 39 |
2015-10-29T13:01:29.000Z
|
2020-10-08T17:39:50.000Z
|
player-app/src/main/java/org/gameontext/player/JsonProvider.java
|
WASdev/gameon-player
|
c51ba9d9a47a160a36ff72281b845d4fc79291be
|
[
"Apache-2.0"
] | 11 |
2015-10-19T13:15:10.000Z
|
2019-09-10T09:07:28.000Z
| 36.064516 | 81 | 0.661002 | 2,578 |
/*******************************************************************************
* Copyright (c) 2016 IBM Corp.
*
* 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.gameontext.player;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class JsonProvider extends JacksonJsonProvider {
}
|
3e061b3d3398c957d807bfc6dde316821285afae
| 1,276 |
java
|
Java
|
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/action/v1/distrox/DistroXCreateAction.java
|
klcopp/cloudbreak
|
1e4bd868a56306e2da19e5181458dc47701828d8
|
[
"Apache-2.0"
] | null | null | null |
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/action/v1/distrox/DistroXCreateAction.java
|
klcopp/cloudbreak
|
1e4bd868a56306e2da19e5181458dc47701828d8
|
[
"Apache-2.0"
] | 1 |
2021-02-24T09:19:56.000Z
|
2021-02-24T09:19:56.000Z
|
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/action/v1/distrox/DistroXCreateAction.java
|
klcopp/cloudbreak
|
1e4bd868a56306e2da19e5181458dc47701828d8
|
[
"Apache-2.0"
] | null | null | null | 44 | 125 | 0.757837 | 2,579 |
package com.sequenceiq.it.cloudbreak.action.v1.distrox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.StackV4Response;
import com.sequenceiq.it.cloudbreak.CloudbreakClient;
import com.sequenceiq.it.cloudbreak.action.Action;
import com.sequenceiq.it.cloudbreak.context.TestContext;
import com.sequenceiq.it.cloudbreak.dto.distrox.DistroXTestDto;
import com.sequenceiq.it.cloudbreak.log.Log;
public class DistroXCreateAction implements Action<DistroXTestDto, CloudbreakClient> {
private static final Logger LOGGER = LoggerFactory.getLogger(DistroXCreateAction.class);
@Override
public DistroXTestDto action(TestContext testContext, DistroXTestDto testDto, CloudbreakClient client) throws Exception {
Log.whenJson(LOGGER, " Distrox create request: ", testDto.getRequest());
StackV4Response stackV4Response = client.getCloudbreakClient()
.distroXV1Endpoint()
.post(testDto.getRequest());
testDto.setFlow("Distrox create", stackV4Response.getFlowIdentifier());
testDto.setResponse(stackV4Response);
Log.whenJson(LOGGER, " Distrox create response: ", stackV4Response);
return testDto;
}
}
|
3e061c5d4c415e48bf63aad69c8abee55e13bfaa
| 2,146 |
java
|
Java
|
src/com/spaceman/dimensionJump/fancyMessage/language/subCommands/Test.java
|
SofitNixes/DimensionJump
|
d665ace5317108b1a5ab07934be7338e0374cc85
|
[
"MIT"
] | null | null | null |
src/com/spaceman/dimensionJump/fancyMessage/language/subCommands/Test.java
|
SofitNixes/DimensionJump
|
d665ace5317108b1a5ab07934be7338e0374cc85
|
[
"MIT"
] | null | null | null |
src/com/spaceman/dimensionJump/fancyMessage/language/subCommands/Test.java
|
SofitNixes/DimensionJump
|
d665ace5317108b1a5ab07934be7338e0374cc85
|
[
"MIT"
] | null | null | null | 45.659574 | 161 | 0.716682 | 2,580 |
package com.spaceman.dimensionJump.fancyMessage.language.subCommands;
import com.spaceman.dimensionJump.commandHandler.SubCommand;
import com.spaceman.dimensionJump.fancyMessage.TextType;
import com.spaceman.dimensionJump.fancyMessage.colorTheme.ColorTheme;
import com.spaceman.dimensionJump.fancyMessage.language.Language;
import org.bukkit.entity.Player;
import org.json.simple.JSONObject;
import java.util.Collection;
import java.util.stream.Collectors;
import static com.spaceman.dimensionJump.fancyMessage.Message.command;
import static com.spaceman.dimensionJump.fancyMessage.Message.translateKeyPrefix;
import static com.spaceman.dimensionJump.fancyMessage.MessageUtils.getOrDefaultCaseInsensitive;
import static com.spaceman.dimensionJump.fancyMessage.TextComponent.textComponent;
import static com.spaceman.dimensionJump.fancyMessage.colorTheme.ColorTheme.sendErrorTheme;
public class Test extends SubCommand {
@Override
public Collection<String> tabList(Player player, String[] args) {
JSONObject translation = Language.getServerLang();
return (Collection<String>) translation.keySet().stream().collect(Collectors.toList());
}
@Override
public void run(String[] args, Player player) {
// command language test <id>
if (args.length == 3) {
JSONObject translation = Language.getPlayerLang(player.getUniqueId());
String raw = args[2];
if (translation == null) {
ColorTheme.formatInfoTranslation(translateKeyPrefix + ".language.test", raw, textComponent(raw).setType(TextType.TRANSLATE)).sendMessage(player);
} else if (getOrDefaultCaseInsensitive(translation, raw, null) != null) {
String translated = (String) translation.get(raw);
ColorTheme.sendInfoTranslation(player, translateKeyPrefix + ".language.test", raw, translated);
} else {
sendErrorTheme(player, "%s is not used as translation id", raw);
}
} else {
sendErrorTheme(player, "Usage: %s", "/" + command + " language test <id>");
}
}
}
|
3e061dabb8b496e66495c41dde8b4840fe025fe2
| 232 |
java
|
Java
|
Main.java
|
codelarosa/java-game
|
8896633110a11a2297c47fca9f84e55f9b50a6d0
|
[
"MIT"
] | null | null | null |
Main.java
|
codelarosa/java-game
|
8896633110a11a2297c47fca9f84e55f9b50a6d0
|
[
"MIT"
] | null | null | null |
Main.java
|
codelarosa/java-game
|
8896633110a11a2297c47fca9f84e55f9b50a6d0
|
[
"MIT"
] | null | null | null | 16.571429 | 44 | 0.547414 | 2,582 |
/**
* Created by Delarosa on January 5, 2022;
*/
public class Main extends Engine {
public static void main(String[] args) {
Main app = new Main();
Engine.debug = false;
app.start();
}
}
|
3e061e011cd79cc80e3394bfabc7a38cb3edb404
| 2,109 |
java
|
Java
|
mmtk/src/org/mmtk/plan/SimpleMutator.java
|
qinsoon/rjava-compiler
|
7f0269ac68afd8c8cfe868254e3e9bbc97208c55
|
[
"MIT"
] | 1 |
2019-03-23T04:35:02.000Z
|
2019-03-23T04:35:02.000Z
|
mmtk/src/org/mmtk/plan/SimpleMutator.java
|
qinsoon/rjava-compiler
|
7f0269ac68afd8c8cfe868254e3e9bbc97208c55
|
[
"MIT"
] | null | null | null |
mmtk/src/org/mmtk/plan/SimpleMutator.java
|
qinsoon/rjava-compiler
|
7f0269ac68afd8c8cfe868254e3e9bbc97208c55
|
[
"MIT"
] | 1 |
2020-12-08T06:17:40.000Z
|
2020-12-08T06:17:40.000Z
| 27.038462 | 79 | 0.644381 | 2,583 |
/*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.mmtk.plan;
import org.mmtk.utility.Log;
import org.mmtk.vm.VM;
import org.rjava.restriction.rulesets.MMTk;
import org.vmmagic.pragma.*;
/**
* This class (and its sub-classes) implement <i>per-mutator thread</i>
* behavior and state.<p>
*
* MMTk assumes that the VM instantiates instances of MutatorContext
* in thread local storage (TLS) for each application thread. Accesses
* to this state are therefore assumed to be low-cost during mutator
* time.<p>
*
* @see MutatorContext
*/
@MMTk
public abstract class SimpleMutator extends MutatorContext {
/****************************************************************************
*
* Collection.
*/
/**
* Perform a per-mutator collection phase. This is executed by
* one collector thread on behalf of a mutator thread.
*/
@Override
@Inline
public void collectionPhase(short phaseId, boolean primary) {
if (phaseId == Simple.PREPARE_STACKS) {
if (!Plan.stacksPrepared()) {
VM.collection.prepareMutator(this);
}
flushRememberedSets();
return;
}
if (phaseId == Simple.PREPARE) {
los.prepare(true);
lgcode.prepare(true);
smcode.prepare();
nonmove.prepare();
VM.memory.collectorPrepareVMSpace();
return;
}
if (phaseId == Simple.RELEASE) {
los.release(true);
lgcode.release(true);
smcode.release();
nonmove.release();
VM.memory.collectorReleaseVMSpace();
return;
}
Log.write("Per-mutator phase \""); Phase.getPhase(phaseId).logPhase();
Log.writeln("\" not handled.");
VM.assertions.fail("Per-mutator phase not handled!");
}
}
|
3e061f817f4b8467d3fe75029adc9d5209b9f52b
| 4,470 |
java
|
Java
|
dmlint-core/src/main/java/com/heaven7/java/data/mediator/lint/PropertyDetector.java
|
leobert-lan/data-mediator
|
4564c3f0266ecf310252a8f68081762734a99c12
|
[
"Apache-2.0"
] | 74 |
2017-09-11T11:51:56.000Z
|
2019-12-13T05:12:30.000Z
|
dmlint-core/src/main/java/com/heaven7/java/data/mediator/lint/PropertyDetector.java
|
leobert-lan/data-mediator
|
4564c3f0266ecf310252a8f68081762734a99c12
|
[
"Apache-2.0"
] | 4 |
2017-10-29T03:25:04.000Z
|
2017-12-04T05:57:13.000Z
|
dmlint-core/src/main/java/com/heaven7/java/data/mediator/lint/PropertyDetector.java
|
leobert-lan/data-mediator
|
4564c3f0266ecf310252a8f68081762734a99c12
|
[
"Apache-2.0"
] | 9 |
2017-09-15T09:54:08.000Z
|
2021-09-08T09:26:55.000Z
| 36.341463 | 122 | 0.621924 | 2,584 |
package com.heaven7.java.data.mediator.lint;
import com.android.tools.lint.client.api.UElementHandler;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiModifierList;
import org.jetbrains.uast.UClass;
import org.jetbrains.uast.UElement;
import org.jetbrains.uast.UMethod;
import java.util.*;
import static com.heaven7.java.data.mediator.lint.PropertyUtils.getProp;
import static com.heaven7.java.data.mediator.lint.PropertyUtils.getPropInfoWithSupers;
/**
* Created by heaven7 on 2017/11/29 0029.
*/
public class PropertyDetector extends Detector implements Detector.UastScanner {
static final Issue ISSUE_PROP = Issue.create("com.heaven7.java.data.mediator.lint",
"Lint Data-Mediator-Property",
"help you fast find incorrect methods for data-module",
Category.CORRECTNESS, 6,
Severity.WARNING,
new Implementation(PropertyDetector.class, Scope.JAVA_FILE_SCOPE)
);
@Override
public List<Class<? extends UElement>> getApplicableUastTypes() {
return Collections.<Class<? extends UElement>>singletonList(UClass.class);
}
@Override
public UElementHandler createUastHandler(JavaContext context) {
return new UElementHandlerImpl(context);
}
private static class UElementHandlerImpl extends UElementHandler{
private static final String NAME_KEEP = "com.heaven7.java.data.mediator.Keep";
private static final String NAME_IMPL_METHOD = "com.heaven7.java.data.mediator.ImplMethod";
final JavaContext context;
UElementHandlerImpl(JavaContext context) {
this.context = context;
}
static boolean hasPropInfo(Collection<PropInfo> coll, String method){
for(PropInfo info : coll){
if(info.getGetMethodName().equals(method) ||
info.getSetMethodName().equals(method) ||
info.getEditorMethodName().equals(method)){
return true;
}
}
return false;
}
@Override
public void visitClass(UClass uClass) {
//only check interface
if(!uClass.isInterface()){
return;
}
Set<PropInfo> infos = getPropInfoWithSupers(uClass);
if(infos.isEmpty()){
return;
}
//check method is relative of any field
for(UMethod method: uClass.getMethods()){
PsiModifierList list = method.getModifierList();
PsiAnnotation pa_keep = list.findAnnotation(NAME_KEEP);
PsiAnnotation pa_impl = list.findAnnotation(NAME_IMPL_METHOD);
if (pa_keep == null && pa_impl == null) {
if(!hasPropInfo(infos, method.getName())){
report(method);
}
}
}
}
private void report(UMethod method){
String prop = getProp(method.getName());
context.report(ISSUE_PROP,
context.getLocation(method.getPsi()), "this method '"+ method.getName()
+"' is not generate for any 'propName' value of @Field,\n you should either add annotation " +
"@Keep/@ImplMethod or add @Field(prop= \""+ prop+"\") for it.**");
}
}
static class PropInfo{
final String prop;
final boolean is_boolean;
final String nameOfMethod;
public PropInfo(String prop, boolean is_boolean) {
this.prop = prop;
this.is_boolean = is_boolean;
this.nameOfMethod = prop.substring(0, 1).toUpperCase() + prop.substring(1);
}
public String getGetMethodName(){
return is_boolean ? "is" + nameOfMethod : "get" + nameOfMethod;
}
public String getSetMethodName(){
return "set" + nameOfMethod;
}
public String getEditorMethodName(){
return "begin" + nameOfMethod + "Editor";
}
}
}
|
3e061fd2bbe3c3c8b18f8d3f6b3c32471f39587e
| 1,274 |
java
|
Java
|
src/main/gen/com/intellij/plugin/powershell/psi/impl/PowerShellAdditiveExpressionImplGen.java
|
Dimi1010/intellij-powershell
|
e9cfe907fdf252dc7fb59398f26b56c6fe2c86fc
|
[
"Apache-2.0"
] | 35 |
2019-04-30T11:41:54.000Z
|
2022-01-25T07:28:36.000Z
|
src/main/gen/com/intellij/plugin/powershell/psi/impl/PowerShellAdditiveExpressionImplGen.java
|
Dimi1010/intellij-powershell
|
e9cfe907fdf252dc7fb59398f26b56c6fe2c86fc
|
[
"Apache-2.0"
] | 58 |
2019-04-25T13:23:21.000Z
|
2022-03-27T21:16:21.000Z
|
src/main/gen/com/intellij/plugin/powershell/psi/impl/PowerShellAdditiveExpressionImplGen.java
|
Dimi1010/intellij-powershell
|
e9cfe907fdf252dc7fb59398f26b56c6fe2c86fc
|
[
"Apache-2.0"
] | 8 |
2020-03-14T08:29:46.000Z
|
2022-01-24T14:13:42.000Z
| 31.073171 | 126 | 0.795133 | 2,585 |
// This is a generated file. Not intended for manual editing.
package com.intellij.plugin.powershell.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.plugin.powershell.psi.PowerShellTypes.*;
import com.intellij.plugin.powershell.psi.*;
public class PowerShellAdditiveExpressionImplGen extends PowerShellExpressionImplGen implements PowerShellAdditiveExpression {
public PowerShellAdditiveExpressionImplGen(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull PowerShellVisitor visitor) {
visitor.visitAdditiveExpression(this);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof PowerShellVisitor) accept((PowerShellVisitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public List<PowerShellComment> getCommentList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, PowerShellComment.class);
}
@Override
@NotNull
public List<PowerShellExpression> getExpressionList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, PowerShellExpression.class);
}
}
|
3e062093448c34c9157c350e578fa5cdd50f3beb
| 10,792 |
java
|
Java
|
src/main/java/com/sbytestream/Splitter.java
|
siddharthbarman/Java-File-Splitter
|
ea27a65858146ed00d36eb82beff08ae47d1b50c
|
[
"MIT"
] | null | null | null |
src/main/java/com/sbytestream/Splitter.java
|
siddharthbarman/Java-File-Splitter
|
ea27a65858146ed00d36eb82beff08ae47d1b50c
|
[
"MIT"
] | null | null | null |
src/main/java/com/sbytestream/Splitter.java
|
siddharthbarman/Java-File-Splitter
|
ea27a65858146ed00d36eb82beff08ae47d1b50c
|
[
"MIT"
] | null | null | null | 40.268657 | 149 | 0.539288 | 2,586 |
package com.sbytestream;
import java.io.*;
public class Splitter {
public static void help() {
System.out.println("Splits or join files.");
System.out.println();
System.out.println("Syntax:");
System.out.println("splitter -mode -n size_in_bytes -i filepath -o filepath");
System.out.println();
System.out.println("Split example:");
System.out.println("splitter -s -n 1024 -i example.zip -o ./output/splitted");
System.out.println("The example will split the input file example.zip into multiple files of 1 KB size.");
System.out.println("The split files will be stored in a folder named output, the split files will be named");
System.out.println("splitted.001, splitted.002, spitted.003 and so on.");
System.out.println();
System.out.println("Join example:");
System.out.println("splitter -j -i splitted.001 -o ./output/joined.zip");
System.out.println("The example will join all the files starting with 001 and create a new file named joined.zip in a folder named output");
}
public static void main(String[] args) {
if (args.length == 0) {
help();
return;
}
try {
new Splitter().run(args);
}
catch(Exception e) {
System.out.println("Something went wrong! Exception:");
System.out.println(e.getMessage());
}
}
public void run(String[] args) throws IOException, AppException {
CmdLineParser cmd = new CmdLineParser(args);
ValidationResult r = validate(cmd);
if (!r.isResult()) {
System.out.println(r.getMessage());
return;
}
String input = cmd.getParamValue(FLAG_INPUT_FILE);
String output = cmd.getParamValue(FLAG_OUTPUT_FILE);
if (cmd.hasFlag(FLAG_MODE_SPLIT)) {
File infile = new File(input);
if (!infile.exists() || !infile.isFile()) {
System.out.println("Input file does not exist or is not a file.");
return;
}
if (infile.length() < INTERNAL_BUFFER_SIZE) {
System.out.println("File too small! Size of the input file should at least 4096 bytes.");
return;
}
File outfile = new File(output);
if (outfile.exists()) {
System.out.println("Output file already exists.");
return;
}
int chunkSize = Integer.parseInt(cmd.getParamValue(FLAG_SIZE));
if (infile.length() / chunkSize > 999) {
System.out.println("Chunk size too small, maximum 999 chunks can be created.");
return;
}
split(input , output, chunkSize);
}
else if (cmd.hasFlag(FLAG_MODE_JOIN)) {
File infile = new File(input);
if (!infile.exists() || !infile.isFile()) {
System.out.println("Input file does not exist or is not a file.");
return;
}
File outfile = new File(output);
if (outfile.exists()) {
System.out.println("Output file already exists.");
return;
}
join(input, output);
}
}
public ValidationResult validate(CmdLineParser cmd) {
if (!cmd.hasFlag(FLAG_MODE_SPLIT) && !cmd.hasFlag(FLAG_MODE_JOIN)) {
return new ValidationResult(false, "mode has not been specified. Use either -s or -j.");
}
if (cmd.hasFlag(FLAG_MODE_SPLIT)) {
String sizeString = cmd.getParamValue(FLAG_SIZE);
if (sizeString == null) {
return new ValidationResult(false, "Size has not been specified. Use the -n option.");
}
try {
int size = Integer.parseInt(sizeString);
if (size < INTERNAL_BUFFER_SIZE) {
return new ValidationResult(false, "Size must be equal or greater than 4096 bytes.");
}
if (size % INTERNAL_BUFFER_SIZE != 0) {
return new ValidationResult(false, "Size must multiples of 4096 bytes.");
}
}
catch (NumberFormatException e) {
return new ValidationResult(false, "Invalid size has been specified.");
}
}
if (cmd.getParamValue(FLAG_INPUT_FILE) == null) {
return new ValidationResult(false,"Input file not specified.");
}
if (cmd.getParamValue(FLAG_OUTPUT_FILE) == null) {
return new ValidationResult(false,"Output file not specified.");
}
return new ValidationResult(true, null);
}
public static String getFileName(String filename, int chunkNumber) {
return String.format("%s.%03d", filename, chunkNumber);
}
private void split(String input, String output, int size) throws IOException {
byte[] buffer = new byte[INTERNAL_BUFFER_SIZE];
int bytesRead = 0;
int bytesLeftForChunk = size;
int chunkNo = 0;
FileOutputStream fos = null;
long totalBytesWritten = 0;
try (FileInputStream fis = new FileInputStream(input)) {
String outputPath = null;
while ((bytesRead = fis.read(buffer)) != -1) {
if (bytesLeftForChunk == size) {
chunkNo++;
outputPath = getFileName(output, chunkNo);
if (new File(outputPath).exists()) {
System.out.println(String.format("%s already exists. Quitting.", outputPath));
return;
}
fos = new FileOutputStream(outputPath);
}
if (bytesRead < INTERNAL_BUFFER_SIZE) {
byte[] lastChunkBuffer = java.util.Arrays.copyOf(buffer, bytesRead);
fos.write(lastChunkBuffer);
fos.close();
bytesLeftForChunk = bytesLeftForChunk - bytesRead;
System.out.println(String.format("%s (%d)", outputPath, size - bytesLeftForChunk));
bytesLeftForChunk = 0;
totalBytesWritten += bytesRead;
}
else {
fos.write(buffer);
totalBytesWritten += INTERNAL_BUFFER_SIZE;
bytesLeftForChunk = bytesLeftForChunk - bytesRead;
if (bytesLeftForChunk == 0) {
fos.close();
System.out.println(String.format("%s (%d)", outputPath, size - bytesLeftForChunk));
bytesLeftForChunk = size;
}
}
}
System.out.println(String.format("Total bytes written: %d, chunks created: %d", totalBytesWritten, chunkNo));
}
if (chunkNo > 0) {
int indexOfSlash = output.lastIndexOf(File.separatorChar);
String outputFilenameOnly;
if (indexOfSlash == -1 ) {
// we have just a filename
outputFilenameOnly = output;
}
else {
// take the filename only
outputFilenameOnly = output.substring(indexOfSlash + 1);
}
writeManifest(output + ".split", new ManifestData(chunkNo, outputFilenameOnly));
}
}
private void join(String input, String output) throws IOException, AppException {
ManifestData manifest = readManifest(input);
String pathWithoutExtension = PathUtils.getFilePathWithoutExtension(input);
long totalSize = 0;
try (FileOutputStream writer = new FileOutputStream(output)) {
for (int chunk = 1; chunk <= manifest.getChunks(); chunk++) {
String chunkFilename = getFileName(pathWithoutExtension, chunk);
totalSize += appendContentTo(chunkFilename, writer);
System.out.println(chunkFilename);
}
}
System.out.println(String.format("Joined file: %s, bytes read and written: %d", output, totalSize));
}
private long appendContentTo(String sourceFile, FileOutputStream writer) throws IOException {
try (FileInputStream reader = new FileInputStream(sourceFile)) {
long totalBytesWritten = 0;
byte[] buffer = new byte[INTERNAL_BUFFER_SIZE];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1) {
if (bytesRead < INTERNAL_BUFFER_SIZE) {
byte[] lastChunkBuffer = java.util.Arrays.copyOf(buffer, bytesRead);
writer.write(lastChunkBuffer);
totalBytesWritten += bytesRead;
}
else {
writer.write(buffer);
totalBytesWritten += INTERNAL_BUFFER_SIZE;
}
}
return totalBytesWritten;
}
}
private void writeManifest(String filepath, ManifestData data) throws IOException {
try (FileWriter manifest = new FileWriter(filepath)) {
manifest.write(data.toString());
}
}
private ManifestData readManifest(String filepath) throws IOException, AppException {
try (BufferedReader manifest = new BufferedReader(new FileReader(filepath))) {
String line = null;
ManifestData data = new ManifestData();
while ((line = manifest.readLine()) != null) {
String[] lines = line.split(":");
if (lines.length != 2) {
throw new AppException("Invalid manifest file");
}
String key = lines[0].trim();
String val = lines[1].trim();
if (key.equalsIgnoreCase("chunks")) {
data.setChunks(Integer.parseInt(val));
}
else if (key.equalsIgnoreCase("filename")) {
data.setFilename(val);
}
}
return data;
}
}
public static final String FLAG_MODE_SPLIT = "s";
public static final String FLAG_MODE_JOIN = "j";
public static final String FLAG_SIZE = "n";
public static final String FLAG_INPUT_FILE = "i";
public static final String FLAG_OUTPUT_FILE = "o";
public static int INTERNAL_BUFFER_SIZE = 1024 * 4;
}
|
3e0620ec4b983f3c0bda6a5eaf4bbc4cc1897963
| 303 |
java
|
Java
|
supermarket/src/test/java/com/vvlhw/supermarket/entity/TestOrder.java
|
LiuKW/JavaEE_Cloud_Market
|
5bead6831efa866f0f661b4d3aee79e95e09637d
|
[
"Apache-2.0"
] | null | null | null |
supermarket/src/test/java/com/vvlhw/supermarket/entity/TestOrder.java
|
LiuKW/JavaEE_Cloud_Market
|
5bead6831efa866f0f661b4d3aee79e95e09637d
|
[
"Apache-2.0"
] | null | null | null |
supermarket/src/test/java/com/vvlhw/supermarket/entity/TestOrder.java
|
LiuKW/JavaEE_Cloud_Market
|
5bead6831efa866f0f661b4d3aee79e95e09637d
|
[
"Apache-2.0"
] | null | null | null | 16.833333 | 60 | 0.69637 | 2,587 |
package com.vvlhw.supermarket.entity;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TestOrder {
@Test
void testOrder()
{
UserOrder order = new UserOrder();
System.out.println(order);
}
}
|
3e06220e8f4d5095364f20bcb330631ace98a357
| 156 |
java
|
Java
|
spring-test/src/main/java/org/springframework/demo/bean/MyFactoryBean.java
|
Force-oneself/spring-framework-master
|
5b73653ff4d6323daad01f79474eae7d6eee3d1d
|
[
"Apache-2.0"
] | 1 |
2021-01-21T16:18:12.000Z
|
2021-01-21T16:18:12.000Z
|
spring-test/src/main/java/org/springframework/demo/bean/MyFactoryBean.java
|
Force-oneself/spring-framework-master
|
5b73653ff4d6323daad01f79474eae7d6eee3d1d
|
[
"Apache-2.0"
] | null | null | null |
spring-test/src/main/java/org/springframework/demo/bean/MyFactoryBean.java
|
Force-oneself/spring-framework-master
|
5b73653ff4d6323daad01f79474eae7d6eee3d1d
|
[
"Apache-2.0"
] | null | null | null | 14.181818 | 38 | 0.711538 | 2,588 |
package org.springframework.demo.bean;
/**
* @author Force-oneself
* @description MyFactoryBean
* @date 2021-07-13
**/
public class MyFactoryBean {
}
|
3e0622d4a0152bbe63a8c0797bc1f177a0fbfe7a
| 20,456 |
java
|
Java
|
src/main/java/dev/zomo/acmd/acmd.java
|
ZomoXYZ/Admin-Commands
|
f948cdc27e81833379182604f3654e7b6821dd2d
|
[
"MIT"
] | 1 |
2021-06-28T22:18:19.000Z
|
2021-06-28T22:18:19.000Z
|
src/main/java/dev/zomo/acmd/acmd.java
|
ZomoXYZ/Admin-Commands
|
f948cdc27e81833379182604f3654e7b6821dd2d
|
[
"MIT"
] | null | null | null |
src/main/java/dev/zomo/acmd/acmd.java
|
ZomoXYZ/Admin-Commands
|
f948cdc27e81833379182604f3654e7b6821dd2d
|
[
"MIT"
] | null | null | null | 35.637631 | 124 | 0.553578 | 2,589 |
package dev.zomo.acmd;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.logging.Logger;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.attribute.Attribute;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import dev.zomo.MCCommands.CommandMain;
import dev.zomo.MCLang.Lang;
import dev.zomo.MCLang.LangTemplate;
import dev.zomo.acmd.back.back;
import dev.zomo.acmd.ban.BanInfo;
import dev.zomo.acmd.ban.ban;
import dev.zomo.mcpremium.dataType.PlayerLookupData;
import dev.zomo.mcpremium.MCPPlayer;
public class acmd extends JavaPlugin {
public static JavaPlugin plugin = null;
public static Logger logger = null;
public static Lang lang = null;
public static HashMap<Player, playerSave> adminMode = new HashMap<Player, playerSave>();
private static final String[] TIMETYPES = { "s", "m", "h", "d", "w" };
private static final int[] TIMELENGTHS = { 1000, 60000, 3600000, 86400000, 604800000 };
public static final HashMap<String, Integer> TimeLengths = new HashMap<String, Integer>();
@Override
public void onEnable() {
plugin = this;
logger = this.getLogger();
lang = new Lang(this, "en_us");
ban.enable();
getServer().getPluginManager().registerEvents(new dev.zomo.acmd.ban.events(), this);
getServer().getPluginManager().registerEvents(new dev.zomo.acmd.back.events(), this);
getServer().getPluginManager().registerEvents(new freeze(), this);
getServer().getPluginManager().registerEvents(new dev.zomo.acmd.strippedlog(), this);
for (int i = 0; i < TIMETYPES.length && i < TIMELENGTHS.length; i++)
TimeLengths.put(TIMETYPES[i], TIMELENGTHS[i]);
new CommandMain(getCommand("fcmd"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(null, args, true, true);
if (data.players.size() == 0)
sendMessage(sender, "general.missingplayer");
else {
Player target = (Player) data.players.get(0);
String command = String.join(" ", data.args);
target.performCommand(command);
LangTemplate template = new LangTemplate()
.add("target", target.getDisplayName())
.add("command", command);
sendMessage(sender, "fcmd", template, true);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("fcmd", template)));
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("base"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(sender, args, false, false);
if (data.players.size() == 0)
sendMessage(sender, "general.missingplayer");
else {
for (OfflinePlayer target : data.players) {
Location base = target.getBedSpawnLocation();
String displayName = target.getName();
if (target instanceof Player)
displayName = ((Player) target).getDisplayName();
LangTemplate template = new LangTemplate()
.add("target", displayName)
.add("x", base.getBlockX())
.add("y", base.getBlockY())
.add("z", base.getBlockZ());
sendMessage(sender, "base", template, false);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("base", template)));
}
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("vanish"), (CommandSender sender, ArrayList<String> args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
vanish.toggle(player);
if (vanish.is(player))
//sender.sendMessage(LangTemplate.escapeColors(lang.string("vanish.enable")));
sendMessage(sender, "vanish.enable", true);
else
//sender.sendMessage(LangTemplate.escapeColors(lang.string("vanish.disable")));
sendMessage(sender, "vanish.disable", true);
}
return true;
});
new CommandMain(getCommand("fly"), (CommandSender sender, ArrayList<String> args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
player.setAllowFlight(!player.getAllowFlight());
if (player.getAllowFlight())
//sender.sendMessage(LangTemplate.escapeColors(lang.string("fly.enable")));
sendMessage(sender, "fly.enable", true);
else
//sender.sendMessage(LangTemplate.escapeColors(lang.string("fly.disable")));
sendMessage(sender, "fly.disable", true);
}
return true;
});
new CommandMain(getCommand("god"), (CommandSender sender, ArrayList<String> args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
player.setInvulnerable(!player.isInvulnerable());
if (player.isInvulnerable())
//sender.sendMessage(LangTemplate.escapeColors(lang.string("god.enable")));
sendMessage(sender, "god.enable", true);
else
//sender.sendMessage(LangTemplate.escapeColors(lang.string("god.disable")));
sendMessage(sender, "god.disable", true);
}
return true;
});
new CommandMain(getCommand("top"), (CommandSender sender, ArrayList<String> args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
Location location = player.getLocation();
int yval = 0;
for (int i = 0; i < player.getWorld().getMaxHeight(); i++) {
Block block = new Location(player.getWorld(), location.getBlockX(), i, location.getBlockZ()).getBlock();
if (block.getType() != Material.AIR) {
yval = i + 1;
}
}
player.teleport(
new Location(player.getWorld(), location.getBlockX() + 0.5, yval, location.getBlockZ() + 0.5));
sendMessage(sender, "top", false);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("top")));
}
return true;
});
new CommandMain(getCommand("flyspeed"), (CommandSender sender, ArrayList<String> args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
String key = "";
if (args.size() == 0)
key = "get";
else {
float flyspeed = Float.parseFloat(args.get(0)) / 10;
flyspeed = Math.max(-1, Math.min(1, flyspeed));
player.setFlySpeed(flyspeed);
key = "set";
}
LangTemplate template = new LangTemplate()
.add("speed", String.valueOf(player.getFlySpeed()*10));
sendMessage(sender, "flyspeed." + key, template, false);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("flyspeed." + key, template)));
}
return true;
});
new CommandMain(getCommand("sethealth"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(sender, args);
if (data.players.size() > 0 && data.args.size() > 0) {
Player target = (Player) data.players.get(0);
double health = Double.valueOf(data.args.get(0));
health = Math.max(0,
Math.min(target.getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue(), health));
target.setHealth(health);
LangTemplate template = new LangTemplate().add("target", target.getDisplayName()).add("health",
String.valueOf(health));
sendMessage(sender, "sethealth", template, true);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("sethealth", template)));
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("sethunger"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(sender, args);
if (data.players.size() > 0 && data.args.size() > 0) {
Player target = (Player) data.players.get(0);
if (target != null) {
int hunger = Integer.valueOf(data.args.get(0));
hunger = Math.max(0, Math.min(20, hunger));
target.setFoodLevel(hunger);
LangTemplate template = new LangTemplate()
.add("target", target.getDisplayName())
.add("hunger", String.valueOf(hunger));
sendMessage(sender, "sethunger", template, true);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("sethunger", template)));
}
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("freeze"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(sender, args, true, false);
if (data.players.size() > 0) {
int mode = 0;
if (data.args.size() > 0) {
if (data.args.get(0).toLowerCase().equals("y"))
mode = 1;
else if (data.args.get(0).toLowerCase().equals("n"))
mode = 2;
}
for (OfflinePlayer otarget : data.players) {
Player target = (Player) otarget;
switch(mode) {
case 0:
freeze.toggle(target);
break;
case 1:
freeze.add(target);
break;
case 2:
freeze.remove(target);
}
LangTemplate template = new LangTemplate()
.add("target", target.getName());
if (freeze.is(target))
sendMessage(sender, "freeze.enable", template, true);
else
sendMessage(sender, "freeze.disable", template, true);
}
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("frozen"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(sender, args, true, false);
if (data.players.size() > 0) {
for (OfflinePlayer otarget : data.players) {
Player target = (Player) otarget;
LangTemplate template = new LangTemplate()
.add("target", target.getName())
.add("frozen", freeze.is(target));
sendMessage(sender, "frozen", template, true);
}
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("admin"), (CommandSender sender, ArrayList<String> args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
if (adminMode.containsKey(player)) {
adminMode.get(player).revertPlayer();
adminMode.remove(player);
sendMessage(sender, "admin.disable", true);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("admin.disable")));
} else {
playerSave data = new playerSave(player);
adminMode.put(player, data);
data.clearPlayer();
player.setGameMode(GameMode.CREATIVE);
sendMessage(sender, "admin.enable", true);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("admin.enable")));
}
}
return true;
});
new CommandMain(getCommand("back"), (CommandSender sender, ArrayList<String> args) -> {
if (sender instanceof Player) {
Player player = (Player) sender;
back.sendBack(player);
sendMessage(sender, "back", false);
}
return true;
});
new CommandMain(getCommand("tempban"), (CommandSender sender, ArrayList<String> args) -> {
return ban.execute(sender, args, true);
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("ban"), (CommandSender sender, ArrayList<String> args) -> {
return ban.execute(sender, args, false);
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("unban"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(null, args, false, true);
if (data.players.size() == 0)
sendMessage(sender, "general.missingplayer");
else {
LangTemplate template = new LangTemplate()
.add("username", data.players.get(0).getName());
if (ban.removeBan(data.players.get(0).getUniqueId()))
sendMessage(sender, "ban.unban", template, true);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("ban.unban", template)));
else
sendMessage(sender, "ban.notbanned", template, false);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("ban.notbanned", template)));
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
new CommandMain(getCommand("baninfo"), (CommandSender sender, ArrayList<String> args) -> {
PlayerLookupData data = playerParse(null, args, false, true);
if (data.players.size() == 0)
sendMessage(sender, "general.missingplayer");
else if (ban.isBanned(data.players.get(0).getUniqueId()) > 0) {
BanInfo info = ban.banInfo(data.players.get(0).getUniqueId());
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
LangTemplate template = new LangTemplate()
.add("target", info.target.getName())
.add("mod", info.mod.getName())
.add("from", df.format(info.from))
.add("until", df.format(info.until))
.add("remaining", timeToString(info.getRemaining()))
.add("reason", info.reason);
sendMessage(sender, "ban.baninfo", template, false);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("ban.baninfo", template)));
} else {
LangTemplate template = new LangTemplate()
.add("username", data.players.get(0).getName());
sendMessage(sender, "ban.notbanned", template, false);
//sender.sendMessage(LangTemplate.escapeColors(lang.string("ban.notbanned", template)));
}
return true;
}).autocomplete(new dev.zomo.mcpremium.dataType.CommandtabCompleteNameInterface());
}
public static void sendMessage(CommandSender sender, String id, LangTemplate template, boolean shouldLog) {
if (shouldLog) {
String modname = "CONSOLE";
if (sender instanceof Player)
modname = sender.getName();
template.add("mod", modname);
actionlog.log(LangTemplate.escapeColors(lang.string("log." + id, template), true));
}
sender.sendMessage(LangTemplate.escapeColors(lang.string(id, template)));
}
public static void sendMessage(CommandSender sender, String id, LangTemplate template) {
sendMessage(sender, id, template, false);
}
public static void sendMessage(CommandSender sender, String id, boolean shouldLog) {
sendMessage(sender, id, new LangTemplate(), shouldLog);
}
public static void sendMessage(CommandSender sender, String id) {
sendMessage(sender, id, false);
}
public static PlayerLookupData playerParse(Player defaultTo, ArrayList<String> args, boolean onlineOnly,
boolean unambiguous) {
PlayerLookupData data = MCPPlayer.playerLookup(args);
if (data.players.size() == 0)
data.addPlayer(defaultTo);
else if (unambiguous && data.players.size() > 1) {
data = new PlayerLookupData();
data.addArgs(args);
}
if (onlineOnly) {
ArrayList<OfflinePlayer> checkPlayers = data.players;
data.clearPlayers();
for (OfflinePlayer p : checkPlayers)
if (p instanceof Player)
data.addPlayer(p);
}
return data;
}
public static long timeParse(String time) {
long retTime = 0;
long tempTime = 0;
for (String ch : Arrays.asList(time.split(""))) {
try {
tempTime = Integer.parseInt(ch) + (tempTime * 10);
} catch (NumberFormatException ex) {
if (TimeLengths.containsKey(ch)) {
retTime += tempTime*TimeLengths.get(ch);
tempTime = 0;
}
}
}
retTime += tempTime;
return retTime;
}
public static String timeToString(long time) {
ArrayList<String> ret = new ArrayList<String>();
long remainingtime = time;
for (int i = TIMETYPES.length-1; i >= 0; i--) {
if (remainingtime > TIMELENGTHS[i]) {
long times = Math.floorDiv(remainingtime, TIMELENGTHS[i]);
remainingtime %= TIMELENGTHS[i];
ret.add(String.valueOf(times) + TIMETYPES[i]);
}
}
return String.join(" ", ret);
}
public static PlayerLookupData playerParse(Player defaultTo, ArrayList<String> args) {
return playerParse(defaultTo, args, true, false);
}
public static PlayerLookupData playerParse(CommandSender sender, ArrayList<String> args, boolean onlineOnly,
boolean unambiguous) {
Player defaultTo = null;
if (sender instanceof Player)
defaultTo = (Player) sender;
return playerParse(defaultTo, args, true, false);
}
public static PlayerLookupData playerParse(CommandSender sender, ArrayList<String> args) {
Player defaultTo = null;
if (sender instanceof Player)
defaultTo = (Player) sender;
return playerParse(defaultTo, args, true, false);
}
}
|
3e06231ace39bd3422a3a952c642dfe78bbb3122
| 1,129 |
java
|
Java
|
qmall-search/src/main/java/com/qjx/qmall/search/vo/SearchResult.java
|
hostgov/qmall
|
8ae43750e1dedff9ab3a55546f1eb1e2a4b11136
|
[
"Apache-2.0"
] | null | null | null |
qmall-search/src/main/java/com/qjx/qmall/search/vo/SearchResult.java
|
hostgov/qmall
|
8ae43750e1dedff9ab3a55546f1eb1e2a4b11136
|
[
"Apache-2.0"
] | null | null | null |
qmall-search/src/main/java/com/qjx/qmall/search/vo/SearchResult.java
|
hostgov/qmall
|
8ae43750e1dedff9ab3a55546f1eb1e2a4b11136
|
[
"Apache-2.0"
] | null | null | null | 18.816667 | 54 | 0.73605 | 2,590 |
package com.qjx.qmall.search.vo;
import com.qjx.qmall.common.to.es.SkuEsModel;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* Ryan
* 2021-11-06-17:43
*/
@Data
public class SearchResult {
//查询到的所有商品信息
private List<SkuEsModel> products;
private Integer pageNum; //当前页码
private Long total; //总记录数
private Integer totalPages; // 总页码
private List<Integer> pageNavs;
private List<BrandVo> brands; //当前查询到的记过所有涉及到的品牌
private List<CatalogVo> catalogs; //当前查询到的结果,所有涉及到的分类
private List<AttrVo> attrs; //当前查询到的结果,所有涉及到的属性
//面包屑导航
private List<NavVo> navs = new ArrayList<>();
private List<Long> attrIds = new ArrayList<>();
@Data
public static class NavVo{
private String navName;
private String navValue;
private String link;
}
@Data
public static class BrandVo{
private Long brandId;
private String brandName;
private String BrandImg;
}
@Data
public static class AttrVo {
private Long attrId;
private String attrName;
private List<String> attrValue;
}
@Data
public static class CatalogVo {
private Long catalogId;
private String catalogName;
}
}
|
3e062328fd3040470b5b0e3f7e8711feb2c6d539
| 1,884 |
java
|
Java
|
modules/client-tests/src/com/haulmont/cuba/client/testsupport/TestMetadataClient.java
|
tausendschoen/cuba
|
e4342d4e840b54b85ff3851e76c2c01b7987b33a
|
[
"Apache-2.0"
] | 1,337 |
2016-03-24T09:32:00.000Z
|
2022-03-31T16:46:59.000Z
|
modules/client-tests/src/com/haulmont/cuba/client/testsupport/TestMetadataClient.java
|
tausendschoen/cuba
|
e4342d4e840b54b85ff3851e76c2c01b7987b33a
|
[
"Apache-2.0"
] | 2,911 |
2016-04-28T14:36:19.000Z
|
2022-03-22T06:09:57.000Z
|
modules/client-tests/src/com/haulmont/cuba/client/testsupport/TestMetadataClient.java
|
tausendschoen/cuba
|
e4342d4e840b54b85ff3851e76c2c01b7987b33a
|
[
"Apache-2.0"
] | 271 |
2016-04-15T03:29:20.000Z
|
2022-03-27T01:05:43.000Z
| 35.54717 | 135 | 0.742038 | 2,591 |
/*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.client.testsupport;
import com.haulmont.cuba.core.global.ExtendedEntities;
import com.haulmont.cuba.core.global.GlobalConfig;
import com.haulmont.cuba.core.sys.DatatypeRegistryImpl;
import com.haulmont.cuba.core.sys.MetadataImpl;
import com.haulmont.cuba.core.sys.MetadataLoader;
import java.util.List;
import java.util.Map;
public class TestMetadataClient extends MetadataImpl {
protected Map<String, List<String>> packages;
public TestMetadataClient(Map<String, List<String>> packages, TestViewRepositoryClient viewRepository, GlobalConfig globalConfig) {
this.packages = packages;
this.viewRepository = viewRepository;
viewRepository.setMetadata(this);
extendedEntities = new ExtendedEntities(this);
tools = new TestMetadataTools(this);
datatypeRegistry = new DatatypeRegistryImpl();
config = globalConfig;
}
@Override
protected void initMetadata() {
MetadataLoader metadataLoader = new TestMetadataLoader(packages);
((TestMetadataLoader) metadataLoader).setDatatypeRegistry(datatypeRegistry);
metadataLoader.loadMetadata();
rootPackages = metadataLoader.getRootPackages();
this.session = metadataLoader.getSession();
}
}
|
3e06235bddb8513d6c25d3721c83b25ca8f0b2ae
| 167 |
java
|
Java
|
java/sum-of-odd-numbers/solution.java
|
hiljusti/codewars-solutions
|
1a423e8cb0fbcac94738f6e51dc333f057b0a731
|
[
"WTFPL"
] | 2 |
2020-02-22T08:47:51.000Z
|
2021-05-21T22:21:55.000Z
|
java/sum-of-odd-numbers/solution.java
|
hiljusti/codewars-solutions
|
1a423e8cb0fbcac94738f6e51dc333f057b0a731
|
[
"WTFPL"
] | null | null | null |
java/sum-of-odd-numbers/solution.java
|
hiljusti/codewars-solutions
|
1a423e8cb0fbcac94738f6e51dc333f057b0a731
|
[
"WTFPL"
] | 1 |
2021-11-09T17:22:10.000Z
|
2021-11-09T17:22:10.000Z
| 18.555556 | 57 | 0.670659 | 2,592 |
// https://www.codewars.com/kata/55fd2d567d94ac3bc9000064
class RowSumOddNumbers {
public static int rowSumOddNumbers(int n) {
return n * n * n;
}
}
|
3e062379d8a409cda25b7aa06a611f0f9aa9ac71
| 1,001 |
java
|
Java
|
backend/src/main/java/jp/bootware/spaspring/infrastructure/auth/model/Authority.java
|
bootware-dev/matching-service-base
|
2690dd7195ef637793fccc2667cebf49f0d58b2b
|
[
"Apache-2.0"
] | null | null | null |
backend/src/main/java/jp/bootware/spaspring/infrastructure/auth/model/Authority.java
|
bootware-dev/matching-service-base
|
2690dd7195ef637793fccc2667cebf49f0d58b2b
|
[
"Apache-2.0"
] | null | null | null |
backend/src/main/java/jp/bootware/spaspring/infrastructure/auth/model/Authority.java
|
bootware-dev/matching-service-base
|
2690dd7195ef637793fccc2667cebf49f0d58b2b
|
[
"Apache-2.0"
] | null | null | null | 29.441176 | 101 | 0.788212 | 2,593 |
package jp.bootware.spaspring.infrastructure.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Set;
@Entity
public class Authority implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "authority_seq")
@SequenceGenerator(name = "authority_seq", sequenceName = "authority_sequence", allocationSize = 1)
private Long id;
@Column(length = 100, unique = true)
@NotNull
private String name;
@JsonIgnore
@ToString.Exclude
@ManyToMany(mappedBy = "authorities", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<UserInfo> userInfos;
public GrantedAuthority grantedAuthority() {
return new SimpleGrantedAuthority(this.name);
}
}
|
3e0623ad309e5c7d645c0da3152fcebd11e33461
| 466 |
java
|
Java
|
java_practice/src/com/company/Main.java
|
phamhongphuc1999/CollectionCode
|
410f7b421d99627b002bc0b1184eeff57e3bc3e2
|
[
"Apache-2.0"
] | null | null | null |
java_practice/src/com/company/Main.java
|
phamhongphuc1999/CollectionCode
|
410f7b421d99627b002bc0b1184eeff57e3bc3e2
|
[
"Apache-2.0"
] | null | null | null |
java_practice/src/com/company/Main.java
|
phamhongphuc1999/CollectionCode
|
410f7b421d99627b002bc0b1184eeff57e3bc3e2
|
[
"Apache-2.0"
] | null | null | null | 21.181818 | 61 | 0.60515 | 2,594 |
package com.company;
import com.company.Bai2.Bai2;
import com.company.Bai2.Employee;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Bai1 bai1 = new Bai1();
// bai1.RunApp();
ArrayList<Employee> list = new ArrayList<Employee>();
list.add(new Employee(1, "Tai1", 20));
list.add(new Employee(2, "Tai2", 30));
Bai2 bai2 = new Bai2(list);
bai2.RunApp();
}
}
|
3e0623c9a69c007093c1764c5f332e81b5f7d0ae
| 1,236 |
java
|
Java
|
tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bindy/MyRoutes.java
|
dpocock/camel
|
85a5bfbf31ae0bf3bfc9bc5dfb43f5155bc53502
|
[
"Apache-2.0"
] | 1 |
2017-03-26T14:52:02.000Z
|
2017-03-26T14:52:02.000Z
|
tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bindy/MyRoutes.java
|
dpocock/camel
|
85a5bfbf31ae0bf3bfc9bc5dfb43f5155bc53502
|
[
"Apache-2.0"
] | null | null | null |
tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bindy/MyRoutes.java
|
dpocock/camel
|
85a5bfbf31ae0bf3bfc9bc5dfb43f5155bc53502
|
[
"Apache-2.0"
] | 1 |
2020-07-18T13:12:42.000Z
|
2020-07-18T13:12:42.000Z
| 35.314286 | 75 | 0.711974 | 2,595 |
/**
* 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.camel.itest.osgi.bindy;
import org.apache.camel.builder.RouteBuilder;
/**
*
*/
public class MyRoutes extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:unmarshal").unmarshal("myBindy")
.split(simple("body")).to("mock:bindy-unmarshal");
from("direct:marshal").marshal("myBindy")
.to("mock:bindy-marshal");
}
}
|
3e062417aaaf3377da9533aa6046c7e49e88ef67
| 4,965 |
java
|
Java
|
TarasTelischuk/src/test/java/company/controller/MainControllerProxyTest.java
|
presly808/aco23
|
3ebe01a03d86c38da00f13e58d7a931acbd36957
|
[
"MIT"
] | null | null | null |
TarasTelischuk/src/test/java/company/controller/MainControllerProxyTest.java
|
presly808/aco23
|
3ebe01a03d86c38da00f13e58d7a931acbd36957
|
[
"MIT"
] | 2 |
2018-01-23T11:32:34.000Z
|
2018-02-07T16:15:05.000Z
|
TarasTelischuk/src/test/java/company/controller/MainControllerProxyTest.java
|
presly808/aco23
|
3ebe01a03d86c38da00f13e58d7a931acbd36957
|
[
"MIT"
] | null | null | null | 37.900763 | 103 | 0.688016 | 2,596 |
package company.controller;
import company.db.AppDb;
import company.model.Employee;
import company.model.Manager;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import static org.junit.Assert.*;
public class MainControllerProxyTest {
@Test
public void addEmployee() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
Employee withId = mainController.addEmployee(new Employee("Ivan", 3000));
assertThat(withId.getId(), CoreMatchers.not(0));
}
@Test
public void getAllEmployees() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
mainController.addEmployee(new Employee("Ivan", 3000));
mainController.addEmployee(new Employee("Ivan", 3000));
assertThat(mainController.getAllEmployees().size(), CoreMatchers.equalTo(2));
}
@Test
public void calculateSalary() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
Employee withId = mainController.addEmployee(new Employee("Ivan", 3000));
assertThat(mainController.calculateSalary(withId), CoreMatchers.equalTo(3000));
}
@Test
public void calculateSalaries() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
Manager man = new Manager("anton", 5000);
man.addSubworker(new Employee("1", 1000));
man.addSubworker(new Employee("2", 1000));
mainController.addEmployee(man);
mainController.addEmployee(new Employee("anton", 3000));
mainController.addEmployee(new Employee("Andrey", 3000));
mainController.addEmployee(new Employee("Ivan", 3000));
assertThat(mainController.calculateSalaries(), CoreMatchers.equalTo(9000 + 5100));
}
@Test
public void getById() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
Employee withId = mainController.addEmployee(new Employee("Ivan", 3000));
mainController.addEmployee(new Employee("Ivan", 3000));
assertThat(mainController.getById(withId.getId()), CoreMatchers.equalTo(withId));
}
@Test
public void findWithFilter() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
mainController.addEmployee(new Employee("anton", 3000));
mainController.addEmployee(new Employee("Andrey", 3000));
mainController.addEmployee(new Employee("Ivan", 3000));
assertThat(mainController.findWithFilter("an").size(), CoreMatchers.equalTo(3));
}
@Test
public void filterWithPredicate() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
Employee emp1 = new Employee("anton", 1000);
emp1.setBirthday(new GregorianCalendar(1990, 4, 22));
emp1.setStartWorkDate(new Date());
Employee emp2 = new Employee("Andrey", 3000);
emp2.setBirthday(new GregorianCalendar(1985, 4, 22));
emp2.setStartWorkDate(new Date(new GregorianCalendar(2017, 4, 22).toInstant().toEpochMilli()));
Employee emp3 = new Employee("Ivan", 4000);
emp3.setBirthday(new GregorianCalendar(1990, 4, 22));
emp3.setStartWorkDate(new Date(new GregorianCalendar(2017, 4, 22).toInstant().toEpochMilli()));
mainController.addEmployee(emp1);
mainController.addEmployee(emp2);
mainController.addEmployee(emp3);
List<Employee> result = mainController.filterWithPredicate((employee -> {
boolean res = true;
if (employee.getSalary() < 3000) {
return false;
}
return res;
}), Comparator.comparing(Employee::getName));
assertThat(result, CoreMatchers.hasItem(emp2));
assertThat(result, CoreMatchers.hasItem(emp3));
assertThat(result.get(0).getName(), CoreMatchers.equalTo("Andrey"));
}
@Test
public void fireWorker() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
Employee emp1 = new Employee("anton", 1000);
emp1.setBirthday(new GregorianCalendar(1990, 4, 22));
emp1.setStartWorkDate(new Date());
mainController.addEmployee(emp1);
assertThat(mainController.fireWorker(emp1.getId()), CoreMatchers.equalTo(emp1));
}
@Test
public void areWorkersEqual() throws Exception {
MainControllerImpl mainController = new MainControllerImpl(new AppDb());
Employee em1 = mainController.addEmployee(new Employee("Ivan", 3000));
Employee em2 = mainController.addEmployee(new Employee("Ivan", 3000));
assertFalse(mainController.areWorkersEqual(em1.getId(),em2.getId()));
}
}
|
3e0624b641d4f52814b0292c372ca422c04b3c98
| 743 |
java
|
Java
|
android/app/src/main/java/cn/toside/music/mobile/lyric/LyricEvent.java
|
songbangyan/lx-music-mobile
|
515ba9a8c1e5085cd45bd415bf6d7442dd14615a
|
[
"Apache-2.0"
] | 1 |
2022-03-13T01:31:07.000Z
|
2022-03-13T01:31:07.000Z
|
android/app/src/main/java/cn/toside/music/mobile/lyric/LyricEvent.java
|
dm0925/lx-music-mobile
|
4609b4c1cf753bcd31e2b3c249d24a4837ede9be
|
[
"Apache-2.0"
] | null | null | null |
android/app/src/main/java/cn/toside/music/mobile/lyric/LyricEvent.java
|
dm0925/lx-music-mobile
|
4609b4c1cf753bcd31e2b3c249d24a4837ede9be
|
[
"Apache-2.0"
] | 1 |
2022-03-26T03:55:58.000Z
|
2022-03-26T03:55:58.000Z
| 30.958333 | 88 | 0.79004 | 2,597 |
package cn.toside.music.mobile.lyric;
import android.util.Log;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class LyricEvent {
final String SET_VIEW_POSITION = "set-position";
private final ReactApplicationContext reactContext;
LyricEvent(ReactApplicationContext reactContext) { this.reactContext = reactContext; }
public void sendEvent(String eventName, @Nullable WritableMap params) {
Log.d("Lyric", "senEvent: " + eventName);
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
}
|
3e0625906730aab1271136c662d45fdafa247d2b
| 5,981 |
java
|
Java
|
src/main/java/com/solostudios/omnivoxscraper/impl/calendar/OmniCalendarImpl.java
|
solonovamax/Omnivox-Scraper
|
fcbc1a223477a172af5f3e3fd4eeb851fd6fa71d
|
[
"MIT"
] | 4 |
2020-12-02T20:37:03.000Z
|
2021-12-28T17:40:26.000Z
|
src/main/java/com/solostudios/omnivoxscraper/impl/calendar/OmniCalendarImpl.java
|
solonovamax/Omnivox-Scraper
|
fcbc1a223477a172af5f3e3fd4eeb851fd6fa71d
|
[
"MIT"
] | null | null | null |
src/main/java/com/solostudios/omnivoxscraper/impl/calendar/OmniCalendarImpl.java
|
solonovamax/Omnivox-Scraper
|
fcbc1a223477a172af5f3e3fd4eeb851fd6fa71d
|
[
"MIT"
] | 1 |
2021-03-20T15:27:03.000Z
|
2021-03-20T15:27:03.000Z
| 43.977941 | 139 | 0.653904 | 2,598 |
package com.solostudios.omnivoxscraper.impl.calendar;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.solostudios.omnivoxscraper.api.calendar.OmniCalendar;
import com.solostudios.omnivoxscraper.api.calendar.OmniDay;
import com.solostudios.omnivoxscraper.api.calendar.OmniSemester;
import com.solostudios.omnivoxscraper.api.calendar.events.OmniClass;
import com.solostudios.omnivoxscraper.impl.OmniScraperImpl;
import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import net.fortuna.ical4j.model.component.VEvent;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author solonovamax
*/
@Slf4j
@ToString
@EqualsAndHashCode
@SuppressWarnings("unused")
public class OmniCalendarImpl implements OmniCalendar {
@ToString.Exclude
private final OmniScraperImpl scraper;
private final List<OmniSemesterImpl> semesters;
public OmniCalendarImpl(OmniScraperImpl scraper) {
this.scraper = scraper;
this.semesters = new ArrayList<>();
}
@SneakyThrows(JsonProcessingException.class)
public void loadPage(HtmlPage loadCalendarPage) {
try {
List<HtmlOption> semesterOptions = ((HtmlSelect) loadCalendarPage.getElementByName("AnSession")).getOptions();
logger.info("Detected {} semesters, constructing now.", semesterOptions.size());
for (HtmlOption semesterElement : semesterOptions) {
OmniSemesterImpl semester = getSemester(semesterElement, loadCalendarPage);
semesters.add(semester);
}
logger.debug("Computed semesters: {}", new ObjectMapper().registerModule(new JavaTimeModule())
// .writerWithDefaultPrettyPrinter()
.writeValueAsString(semesters));
} catch (ElementNotFoundException e) {
logger.error("Could not find the AnSession element. " +
"This most likely means that you have some unread documents from the college. " +
"Please read them before continuing. " +
"If this is not the case, then I fucked up something, so please open a support ticket.", e);
System.exit(1);
}
}
@SneakyThrows(IOException.class)
private OmniSemesterImpl getSemester(HtmlOption semesterElement, HtmlPage loadCalendarPage) {
// String semesterAction = ((HtmlForm) coursePage.getFirstByXPath(
// "//*[@id=\"tblContenuSSO\"]/table/tbody/tr/td/table/tbody/tr/td/form")).getActionAttribute();
// Pattern refPattern = Pattern.compile("Horaire\\.ovx\\?Ref=(\\d*)&C=VAN&L=(?:ANG|FRA)");
// Matcher refMatcher = refPattern.matcher(semesterAction);
// if (!refMatcher.matches()) {
// throw new IllegalArgumentException(
// "OmniScraper was served a bad URL! The URL on the Course Schedule page must match the regex " +
// "\"Horaire\\.ovx\\?Ref=(\\d*)&C=VAN&L=ANG\"");
// }
// String ref = refMatcher.group(1);
URL semesterUrl = new URL("https://" + scraper.getSubdomain() + "-estd.omnivox.ca/estd/hrre/" + "Horaire.ovx");
WebRequest semesterRequest = new WebRequest(semesterUrl, HttpMethod.POST);
List<NameValuePair> semesterParams = new ArrayList<>();
semesterParams.add(new NameValuePair("AnSession", semesterElement.getValueAttribute()));
semesterParams.add(new NameValuePair("Confirm", "Obtain+my+schedule"));
semesterRequest.setRequestParameters(semesterParams);
HtmlPage schedulePage = scraper.getWebClient().getPage(semesterRequest);
semesterElement.getEnclosingSelect().setSelectedAttribute(semesterElement, true);
String season = semesterElement.getTextContent().replaceAll("(.*) \\d\\d\\d\\d", "$1").trim();
int semesterId = Integer.parseInt(semesterElement.getValueAttribute());
int year = Integer.parseInt(semesterElement.getTextContent().replaceAll(".* (\\d\\d\\d\\d)", "$1").trim());
logger.debug("Constructing semester with ID {}.", semesterId);
return new OmniSemesterImpl(schedulePage, semesterId, season, year, semesterElement.isDefaultSelected());
}
@Override
public List<OmniSemester> getAvailableSemesters() {
return semesters.stream()
.filter(s -> s.getClassList().isEmpty())
.map(s -> (OmniSemester) s)
.collect(Collectors.toList());
}
@Override
public Optional<OmniSemester> getCurrentSemester() {
return semesters.stream() //there is only one where isCurrent is true.
.filter(OmniSemester::isCurrent)
.map(s -> (OmniSemester) s)
.findAny();
}
@Override
public List<OmniClass> getClassesToday() {
return null;
}
@Override
public OmniDay getDay(LocalDate date) {
return null;
}
@Override
public List<VEvent> iCalendarEvents() {
return null;
}
}
|
3e062644716cac27ee2896a785ae0a7a407e1306
| 1,091 |
java
|
Java
|
java/mayakpush/mkp.server/src/main/java/net/vexelon/mkp/server/conf/Configuration.java
|
petarov/sandbox
|
9e8288f38de08c96674573aff63ffeb9823fad70
|
[
"MIT"
] | null | null | null |
java/mayakpush/mkp.server/src/main/java/net/vexelon/mkp/server/conf/Configuration.java
|
petarov/sandbox
|
9e8288f38de08c96674573aff63ffeb9823fad70
|
[
"MIT"
] | 7 |
2020-10-13T07:29:25.000Z
|
2022-01-29T10:28:48.000Z
|
java/mayakpush/mkp.server/src/main/java/net/vexelon/mkp/server/conf/Configuration.java
|
petarov/sandbox
|
9e8288f38de08c96674573aff63ffeb9823fad70
|
[
"MIT"
] | null | null | null | 15.585714 | 55 | 0.651696 | 2,599 |
/*
* Copyright (C) 2014 Vexelon.NET Services
* http://vexelon.net
*/
package net.vexelon.mkp.server.conf;
import java.math.BigInteger;
public interface Configuration {
/**
*
* @throws ConfigException
*/
void load() throws ConfigException;
/**
* Clears all currently loaded options and reload them
* @throws ConfigException
*/
void reload() throws ConfigException;
/**
* Size of all loaded options
* @return <code>Integer</code>
*/
int getOptionsCount();
/**
* Get raw configuration value
* @param option
* @return
* @throws NullPointerException
*/
Object getValue(Options option);
/**
*
* @param option
* @return
* @throws NullPointerException
*/
String getString(Options option);
/**
*
* @param option
* @return
* @throws NullPointerException
*/
long getLong(Options option);
/**
*
* @param option
* @return
* @throws NullPointerException
*/
int getInt(Options option);
/**
*
* @param option
* @return
* @throws NullPointerException
*/
BigInteger getBigInteger(Options option);
}
|
3e06271e47e51bfc22c99a3fc2d8a4ebf3ded0c0
| 11,455 |
java
|
Java
|
helix-core/src/main/java/org/apache/helix/tools/commandtools/ZKLogFormatter.java
|
bfreuden/helix
|
c819915150f861e45ef5678e1f2b3ee3277697e9
|
[
"Apache-2.0"
] | 381 |
2015-02-15T09:26:13.000Z
|
2022-03-30T20:42:47.000Z
|
helix-core/src/main/java/org/apache/helix/tools/commandtools/ZKLogFormatter.java
|
bfreuden/helix
|
c819915150f861e45ef5678e1f2b3ee3277697e9
|
[
"Apache-2.0"
] | 1,616 |
2015-02-14T16:41:05.000Z
|
2022-03-31T23:41:14.000Z
|
helix-core/src/main/java/org/apache/helix/tools/commandtools/ZKLogFormatter.java
|
bfreuden/helix
|
c819915150f861e45ef5678e1f2b3ee3277697e9
|
[
"Apache-2.0"
] | 214 |
2015-01-27T07:18:52.000Z
|
2022-03-16T02:03:55.000Z
| 33.592375 | 96 | 0.644697 | 2,600 |
package org.apache.helix.tools.commandtools;
/*
* 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.
*/
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.DataNode;
import org.apache.zookeeper.server.DataTree;
import org.apache.zookeeper.server.persistence.FileHeader;
import org.apache.zookeeper.server.persistence.FileSnap;
import org.apache.zookeeper.server.persistence.FileTxnLog;
import org.apache.zookeeper.server.util.SerializeUtils;
import org.apache.zookeeper.txn.TxnHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ZKLogFormatter {
private static final Logger LOG = LoggerFactory.getLogger(ZKLogFormatter.class);
private static DateFormat dateTimeInstance = DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.LONG);
private static HexBinaryAdapter adapter = new HexBinaryAdapter();
private static String fieldDelim = ":";
private static String fieldSep = " ";
static BufferedWriter bw = null;
/**
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length != 2 && args.length != 3) {
System.err.println("USAGE: LogFormatter <log|snapshot> log_file");
System.exit(2);
}
if (args.length == 3) {
bw = new BufferedWriter(new FileWriter(new File(args[2])));
}
if (args[0].equals("log")) {
readTransactionLog(args[1]);
} else if (args[0].equals("snapshot")) {
readSnapshotLog(args[1]);
}
if (bw != null) {
bw.close();
}
}
private static void readSnapshotLog(String snapshotPath) throws Exception {
FileInputStream fis = new FileInputStream(snapshotPath);
BinaryInputArchive ia = BinaryInputArchive.getArchive(fis);
Map<Long, Integer> sessions = new HashMap<Long, Integer>();
DataTree dt = new DataTree();
FileHeader header = new FileHeader();
header.deserialize(ia, "fileheader");
if (header.getMagic() != FileSnap.SNAP_MAGIC) {
throw new IOException("mismatching magic headers " + header.getMagic() + " != "
+ FileSnap.SNAP_MAGIC);
}
SerializeUtils.deserializeSnapshot(dt, ia, sessions);
if (bw != null) {
bw.write(sessions.toString());
bw.newLine();
} else {
System.out.println(sessions);
}
traverse(dt, 1, "/");
}
/*
* Level order traversal
*/
private static void traverse(DataTree dt, int startId, String startPath) throws Exception {
LinkedList<Pair> queue = new LinkedList<Pair>();
queue.add(new Pair(startPath, startId));
while (!queue.isEmpty()) {
Pair pair = queue.removeFirst();
String path = pair._path;
DataNode head = dt.getNode(path);
Stat stat = new Stat();
byte[] data = null;
try {
data = dt.getData(path, stat, null);
} catch (NoNodeException e) {
e.printStackTrace();
}
// print the node
format(startId, pair, head, data);
Set<String> children = head.getChildren();
if (children != null) {
for (String child : children) {
String childPath;
if (path.endsWith("/")) {
childPath = path + child;
} else {
childPath = path + "/" + child;
}
queue.add(new Pair(childPath, startId));
}
}
startId = startId + 1;
}
}
static class Pair {
private final String _path;
private final int _parentId;
public Pair(String path, int parentId) {
_path = path;
_parentId = parentId;
}
}
private static void format(int id, Pair pair, DataNode head, byte[] data) throws Exception {
String dataStr = "";
if (data != null) {
dataStr = new String(data).replaceAll("[\\s]+", "");
}
StringBuffer sb = new StringBuffer();
// @formatter:off
sb.append("id").append(fieldDelim).append(id).append(fieldSep);
sb.append("parent").append(fieldDelim).append(pair._parentId).append(fieldSep);
sb.append("path").append(fieldDelim).append(pair._path).append(fieldSep);
sb.append("session").append(fieldDelim)
.append("0x" + Long.toHexString(head.stat.getEphemeralOwner())).append(fieldSep);
sb.append("czxid").append(fieldDelim).append("0x" + Long.toHexString(head.stat.getCzxid()))
.append(fieldSep);
sb.append("ctime").append(fieldDelim).append(head.stat.getCtime()).append(fieldSep);
sb.append("mtime").append(fieldDelim).append(head.stat.getMtime()).append(fieldSep);
sb.append("cmzxid").append(fieldDelim).append("0x" + Long.toHexString(head.stat.getMzxid()))
.append(fieldSep);
sb.append("pzxid").append(fieldDelim).append("0x" + Long.toHexString(head.stat.getPzxid()))
.append(fieldSep);
sb.append("aversion").append(fieldDelim).append(head.stat.getAversion()).append(fieldSep);
sb.append("cversion").append(fieldDelim).append(head.stat.getCversion()).append(fieldSep);
sb.append("version").append(fieldDelim).append(head.stat.getVersion()).append(fieldSep);
sb.append("data").append(fieldDelim).append(dataStr).append(fieldSep);
// @formatter:on
if (bw != null) {
bw.write(sb.toString());
bw.newLine();
} else {
System.out.println(sb);
}
}
private static void readTransactionLog(String logfilepath) throws FileNotFoundException,
IOException, EOFException {
FileInputStream fis = new FileInputStream(logfilepath);
BinaryInputArchive logStream = BinaryInputArchive.getArchive(fis);
FileHeader fhdr = new FileHeader();
fhdr.deserialize(logStream, "fileheader");
if (fhdr.getMagic() != FileTxnLog.TXNLOG_MAGIC) {
System.err.println("Invalid magic number for " + logfilepath);
System.exit(2);
}
if (bw != null) {
bw.write("ZooKeeper Transactional Log File with dbid " + fhdr.getDbid()
+ " txnlog format version " + fhdr.getVersion());
bw.newLine();
} else {
System.out.println("ZooKeeper Transactional Log File with dbid " + fhdr.getDbid()
+ " txnlog format version " + fhdr.getVersion());
}
int count = 0;
while (true) {
long crcValue;
byte[] bytes;
try {
crcValue = logStream.readLong("crcvalue");
bytes = logStream.readBuffer("txnEntry");
} catch (EOFException e) {
if (bw != null) {
bw.write("EOF reached after " + count + " txns.");
bw.newLine();
} else {
System.out.println("EOF reached after " + count + " txns.");
}
break;
}
if (bytes.length == 0) {
// Since we preallocate, we define EOF to be an
// empty transaction
if (bw != null) {
bw.write("EOF reached after " + count + " txns.");
bw.newLine();
} else {
System.out.println("EOF reached after " + count + " txns.");
}
return;
}
Checksum crc = new Adler32();
crc.update(bytes, 0, bytes.length);
if (crcValue != crc.getValue()) {
throw new IOException("CRC doesn't match " + crcValue + " vs " + crc.getValue());
}
TxnHeader hdr = new TxnHeader();
Record txn = SerializeUtils.deserializeTxn(bytes, hdr);
if (bw != null) {
bw.write(formatTransaction(hdr, txn));
bw.newLine();
} else {
System.out.println(formatTransaction(hdr, txn));
}
if (logStream.readByte("EOR") != 'B') {
LOG.error("Last transaction was partial.");
throw new EOFException("Last transaction was partial.");
}
count++;
}
}
static String op2String(int op) {
switch (op) {
case OpCode.notification:
return "notification";
case OpCode.create:
return "create";
case OpCode.delete:
return "delete";
case OpCode.exists:
return "exists";
case OpCode.getData:
return "getDate";
case OpCode.setData:
return "setData";
case OpCode.getACL:
return "getACL";
case OpCode.setACL:
return "setACL";
case OpCode.getChildren:
return "getChildren";
case OpCode.getChildren2:
return "getChildren2";
case OpCode.ping:
return "ping";
case OpCode.createSession:
return "createSession";
case OpCode.closeSession:
return "closeSession";
case OpCode.error:
return "error";
default:
return "unknown " + op;
}
}
private static String formatTransaction(TxnHeader header, Record txn) {
StringBuilder sb = new StringBuilder();
sb.append("time").append(fieldDelim).append(header.getTime());
sb.append(fieldSep).append("session").append(fieldDelim).append("0x")
.append(Long.toHexString(header.getClientId()));
sb.append(fieldSep).append("cxid").append(fieldDelim).append("0x")
.append(Long.toHexString(header.getCxid()));
sb.append(fieldSep).append("zxid").append(fieldDelim).append("0x")
.append(Long.toHexString(header.getZxid()));
sb.append(fieldSep).append("type").append(fieldDelim).append(op2String(header.getType()));
if (txn != null) {
try {
byte[] data = null;
for (PropertyDescriptor pd : Introspector.getBeanInfo(txn.getClass())
.getPropertyDescriptors()) {
if (pd.getName().equalsIgnoreCase("data")) {
data = (byte[]) pd.getReadMethod().invoke(txn);
continue;
}
if (pd.getReadMethod() != null && !"class".equals(pd.getName())) {
sb.append(fieldSep).append(pd.getDisplayName()).append(fieldDelim)
.append(pd.getReadMethod().invoke(txn).toString().replaceAll("[\\s]+", ""));
}
}
if (data != null) {
sb.append(fieldSep).append("data").append(fieldDelim)
.append(new String(data).replaceAll("[\\s]+", ""));
}
} catch (Exception e) {
LOG.error("Error while retrieving bean property values for " + txn.getClass(), e);
}
}
return sb.toString();
}
}
|
3e06273b355ad83e243c7ab1bffcff3de77ef9f0
| 3,004 |
java
|
Java
|
beast/src/test/java/edu/pse/beast/api/codegen/cbmc/CodeAndCBMCGenerationTest.java
|
VeriVote/beast
|
2f8ab7dcfb1f7bcf980b8c23b3c3687867598014
|
[
"MIT"
] | 2 |
2017-02-13T15:26:08.000Z
|
2017-02-21T16:07:48.000Z
|
beast/src/test/java/edu/pse/beast/api/codegen/cbmc/CodeAndCBMCGenerationTest.java
|
NikolaiLMS/PSE-Wahlverfahren-Implementierung
|
2f8ab7dcfb1f7bcf980b8c23b3c3687867598014
|
[
"MIT"
] | 42 |
2017-02-13T10:04:21.000Z
|
2017-03-20T04:12:28.000Z
|
beast/src/test/java/edu/pse/beast/api/codegen/cbmc/CodeAndCBMCGenerationTest.java
|
Skypr/BEAST
|
2f8ab7dcfb1f7bcf980b8c23b3c3687867598014
|
[
"MIT"
] | 5 |
2017-02-13T10:36:20.000Z
|
2017-03-20T21:53:43.000Z
| 38.025316 | 96 | 0.680093 | 2,601 |
package edu.pse.beast.api.codegen.cbmc;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import edu.pse.beast.api.CreationHelper;
import edu.pse.beast.api.codegen.cbmc.info.GeneratedCodeInfo;
import edu.pse.beast.api.codegen.init.InitVoteHelper;
import edu.pse.beast.api.codegen.init.SymbVarInitVoteHelper;
import edu.pse.beast.api.cparser.AntlrCLoopParser;
import edu.pse.beast.api.cparser.ExtractedCLoop;
import edu.pse.beast.api.io.PathHandler;
import edu.pse.beast.api.method.CElectionDescription;
import edu.pse.beast.api.method.VotingInputType;
import edu.pse.beast.api.method.VotingOutputType;
import edu.pse.beast.api.property.PropertyDescription;
import edu.pse.beast.api.runner.propertycheck.process.cbmc.CBMCArgumentHelper;
/**
* TODO: Write documentation.
*
* @author Holger Klein
*
*/
public class CodeAndCBMCGenerationTest {
private static final String VOTING = "voting";
private static final String BORDA = "borda";
private static final String REINFORCE = "reinforce";
private static final String PRE = "_pre";
private static final String POST = "_post";
private static final String EMPTY = "";
private static final Map<String, String> TEMPLATES =
new LinkedHashMap<String, String>();
private String getTemplate(final String key) {
assert key != null;
return PathHandler.getTemplate(key, TEMPLATES, EMPTY, this.getClass());
}
@Test
public void generateCodeAndCBMCCall() {
final String bordaCode = getTemplate(BORDA);
final CElectionDescription descr =
new CElectionDescription(VotingInputType.PREFERENCE,
VotingOutputType.CANDIDATE_LIST,
BORDA);
descr.getVotingFunction().setCode(bordaCode);
final CodeGenOptions codeGenOptions = new CodeGenOptions();
final List<ExtractedCLoop> loops =
AntlrCLoopParser.findLoops(VOTING, bordaCode, codeGenOptions);
descr.getVotingFunction().setExtractedLoops(loops);
final String pre = getTemplate(REINFORCE + PRE);
final String post = getTemplate(REINFORCE + POST);
final PropertyDescription propDescr =
CreationHelper.createSimpleCondList(REINFORCE, pre, post).get(0);
final int v = 5;
final int c = 5;
final int s = 5;
final InitVoteHelper initVoteHelper = new SymbVarInitVoteHelper();
final GeneratedCodeInfo codeInfo =
CBMCCodeGenerator.generateCodeForPropertyCheck(descr, propDescr, codeGenOptions,
initVoteHelper);
System.out.println(codeInfo.getCode());
System.out.println(
codeInfo.getLoopBoundHandler().generateCBMCString(v, c, s));
System.out.println(
CBMCArgumentHelper.getConstCommands(codeGenOptions, v, c, s));
}
}
|
3e06274bef2d86693c24d7690f7daea5cb046acb
| 1,868 |
java
|
Java
|
Data/Juliet-Java/Juliet-Java-v103/000/134/171/CWE23_Relative_Path_Traversal__Property_71a.java
|
b19e93n/PLC-Pyramid
|
6d5b57be6995a94ef7402144cee965862713b031
|
[
"MIT"
] | null | null | null |
Data/Juliet-Java/Juliet-Java-v103/000/134/171/CWE23_Relative_Path_Traversal__Property_71a.java
|
b19e93n/PLC-Pyramid
|
6d5b57be6995a94ef7402144cee965862713b031
|
[
"MIT"
] | null | null | null |
Data/Juliet-Java/Juliet-Java-v103/000/134/171/CWE23_Relative_Path_Traversal__Property_71a.java
|
b19e93n/PLC-Pyramid
|
6d5b57be6995a94ef7402144cee965862713b031
|
[
"MIT"
] | null | null | null | 29.1875 | 143 | 0.671306 | 2,602 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__Property_71a.java
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-71a.tmpl.java
*/
/*
* @description
* CWE: 23 Relative Path Traversal
* BadSource: Property Read data from a system property
* GoodSource: A hardcoded string
* Sinks: readFile
* BadSink : no validation
* Flow Variant: 71 Data flow: data passed as an Object reference argument from one method to another in different classes in the same package
*
* */
import java.io.*;
public class CWE23_Relative_Path_Traversal__Property_71a extends AbstractTestCase
{
public void bad() throws Throwable
{
String data;
/* get system property user.home */
/* POTENTIAL FLAW: Read data from a system property */
data = System.getProperty("user.home");
(new CWE23_Relative_Path_Traversal__Property_71b()).badSink((Object)data );
}
public void good() throws Throwable
{
goodG2B();
}
/* goodG2B() - use goodsource and badsink */
private void goodG2B() throws Throwable
{
String data;
/* FIX: Use a hardcoded string */
data = "foo";
(new CWE23_Relative_Path_Traversal__Property_71b()).goodG2BSink((Object)data );
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
3e0627bc60d5252e5d1f72a654d1cf1e5c807991
| 3,540 |
java
|
Java
|
OsmAnd/src/net/osmand/plus/activities/PluginsActivity.java
|
jsmakaayb/Osmand
|
445d31fd2c938821caf381ea8b026b990e580443
|
[
"MIT"
] | 1,176 |
2018-06-24T11:43:56.000Z
|
2021-11-08T12:56:16.000Z
|
OsmAnd/src/net/osmand/plus/activities/PluginsActivity.java
|
jsmakaayb/Osmand
|
445d31fd2c938821caf381ea8b026b990e580443
|
[
"MIT"
] | null | null | null |
OsmAnd/src/net/osmand/plus/activities/PluginsActivity.java
|
jsmakaayb/Osmand
|
445d31fd2c938821caf381ea8b026b990e580443
|
[
"MIT"
] | null | null | null | 31.052632 | 133 | 0.748588 | 2,603 |
package net.osmand.plus.activities;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class PluginsActivity extends OsmandListActivity {
public static final int ACTIVE_PLUGINS_LIST_MODIFIED = 1;
private List<OsmandPlugin> availablePlugins;
private Set<String> clickedPlugins = new LinkedHashSet<String>();
private Set<String> restartPlugins = new LinkedHashSet<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
((OsmandApplication) getApplication()).applyTheme(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.plugins);
getSupportActionBar().setTitle(R.string.plugins_screen);
availablePlugins = OsmandPlugin.getAvailablePlugins();
List<OsmandPlugin> enabledPlugins = OsmandPlugin.getEnabledPlugins();
for(OsmandPlugin p : enabledPlugins) {
restartPlugins.add(p.getId());
}
setListAdapter(new OsmandPluginsAdapter(availablePlugins));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
click(position);
}
private void click(int position) {
OsmandPlugin item = getListAdapter().getItem(position);
boolean enable = !restartPlugins.contains(item.getId());
boolean ok = OsmandPlugin.enablePlugin(((OsmandApplication) getApplication()), item, enable);
if (ok) {
if (!enable) {
restartPlugins.remove(item.getId());
} else {
restartPlugins.add(item.getId());
}
setResult(ACTIVE_PLUGINS_LIST_MODIFIED);
}
clickedPlugins.add(item.getId());
getListAdapter().notifyDataSetChanged();
}
@Override
public OsmandPluginsAdapter getListAdapter() {
return (OsmandPluginsAdapter) super.getListAdapter();
}
protected class OsmandPluginsAdapter extends ArrayAdapter<OsmandPlugin> {
public OsmandPluginsAdapter(List<OsmandPlugin> plugins) {
super(PluginsActivity.this, R.layout.plugins_list_item, plugins);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = getLayoutInflater();
v = inflater.inflate(net.osmand.plus.R.layout.plugins_list_item, parent, false);
}
OsmandPlugin plugin = getItem(position);
boolean toBeEnabled = restartPlugins.contains(plugin.getId());
final View row = v;
CheckBox ch = (CheckBox) row.findViewById(R.id.check_item);
ch.setOnClickListener(null);
ch.setChecked(toBeEnabled);
ch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
click(position);
}
});
TextView nameView = (TextView) row.findViewById(R.id.plugin_name);
nameView.setText(plugin.getName());
nameView.setContentDescription(plugin.getName() + " " + getString(toBeEnabled ? R.string.item_checked : R.string.item_unchecked));
TextView description = (TextView) row.findViewById(R.id.plugin_descr);
description.setText(plugin.getDescription());
description.setVisibility(clickedPlugins.contains(plugin.getId()) ||
!restartPlugins.contains(plugin.getId()) ? View.VISIBLE : View.GONE);
return row;
}
}
}
|
3e0628fd9cb76aad612354a63b4ff38a331a2ff1
| 761 |
java
|
Java
|
jxfw-reporting-xsl-fo/src/main/java/ru/croc/ctp/jxfw/reporting/xslfo/paramprocessors/ReportAbstractParamProcessor.java
|
croc-code/jxfw
|
7af05aa6579a8dfd0e83c918b0e46195eb0802cf
|
[
"Apache-2.0"
] | 12 |
2021-11-08T08:08:44.000Z
|
2022-02-21T15:42:25.000Z
|
jxfw-reporting-xsl-fo/src/main/java/ru/croc/ctp/jxfw/reporting/xslfo/paramprocessors/ReportAbstractParamProcessor.java
|
crocinc/jxfw
|
da93ee21e4e586219eeefc8441e472f7136266d1
|
[
"Apache-2.0"
] | null | null | null |
jxfw-reporting-xsl-fo/src/main/java/ru/croc/ctp/jxfw/reporting/xslfo/paramprocessors/ReportAbstractParamProcessor.java
|
crocinc/jxfw
|
da93ee21e4e586219eeefc8441e472f7136266d1
|
[
"Apache-2.0"
] | 1 |
2022-03-02T14:05:28.000Z
|
2022-03-02T14:05:28.000Z
| 34.590909 | 116 | 0.787122 | 2,604 |
package ru.croc.ctp.jxfw.reporting.xslfo.paramprocessors;
import ru.croc.ctp.jxfw.reporting.xslfo.layouts.ReportLayoutData;
import ru.croc.ctp.jxfw.reporting.xslfo.types.AbstractParamProcessorClass;
/**
* Абстрактный обработчик параметров.
*/
public abstract class ReportAbstractParamProcessor implements IReportParamProcessor {
@Override
public void process(AbstractParamProcessorClass processorProfile, ReportLayoutData processorData) {
doProcess(processorProfile, processorData);
}
/**
* Абстрактная реализация.
* @param processorProfile профиль процессора
* @param processorData данные
*/
protected abstract void doProcess(AbstractParamProcessorClass processorProfile, ReportLayoutData processorData);
}
|
3e0629ed49c5c41daeb0a9589eca1d7a72393762
| 2,915 |
java
|
Java
|
activiti-cloud-modeling-service/activiti-cloud-services-modeling/activiti-cloud-services-modeling-api/src/main/java/org/activiti/cloud/modeling/api/process/Extensions.java
|
allureyc/activiti-cloud
|
be9f7562e6ae314225b04cc3eb174befab02cbbc
|
[
"Apache-2.0"
] | 46 |
2020-02-25T11:17:20.000Z
|
2022-03-14T06:02:17.000Z
|
activiti-cloud-modeling-service/activiti-cloud-services-modeling/activiti-cloud-services-modeling-api/src/main/java/org/activiti/cloud/modeling/api/process/Extensions.java
|
allureyc/activiti-cloud
|
be9f7562e6ae314225b04cc3eb174befab02cbbc
|
[
"Apache-2.0"
] | 483 |
2020-02-27T09:28:05.000Z
|
2022-03-29T10:29:49.000Z
|
activiti-cloud-modeling-service/activiti-cloud-services-modeling/activiti-cloud-services-modeling-api/src/main/java/org/activiti/cloud/modeling/api/process/Extensions.java
|
allureyc/activiti-cloud
|
be9f7562e6ae314225b04cc3eb174befab02cbbc
|
[
"Apache-2.0"
] | 26 |
2020-03-30T10:19:18.000Z
|
2022-03-04T10:02:44.000Z
| 33.125 | 134 | 0.727616 | 2,605 |
/*
* Copyright 2017-2020 Alfresco 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 org.activiti.cloud.modeling.api.process;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Model extensions
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_NULL)
public class Extensions {
@JsonProperty("properties")
private Map<String, ProcessVariable> processVariables = new HashMap<>();
@JsonProperty("mappings")
private Map<String, Map<ServiceTaskActionType, Map<String, ProcessVariableMapping>>> variablesMappings = new HashMap<>();
@JsonProperty("constants")
private Map<String, Map<String, Constant>> constants = new HashMap<>();
@JsonProperty("templates")
private TemplatesDefinition templates = new TemplatesDefinition();
public Map<String, ProcessVariable> getProcessVariables() {
return processVariables;
}
public void setProcessVariables(Map<String, ProcessVariable> processVariables) {
this.processVariables = processVariables;
}
public Map<String, Map<ServiceTaskActionType, Map<String, ProcessVariableMapping>>> getVariablesMappings() {
return variablesMappings;
}
public void setVariablesMappings(Map<String, Map<ServiceTaskActionType, Map<String, ProcessVariableMapping>>> variablesMappings) {
this.variablesMappings = variablesMappings;
}
public Map<String, Map<String, Constant>> getConstants() {
return constants;
}
public void setConstants(Map<String, Map<String, Constant>> constants) {
this.constants = constants;
}
public TemplatesDefinition getTemplates() {
return templates;
}
public void setTemplates(TemplatesDefinition templates) {
this.templates = templates;
}
public Map<String,Object> getAsMap() {
Map<String,Object> extensions = new HashMap<>();
extensions.put("properties",this.processVariables);
extensions.put("mappings",this.variablesMappings);
extensions.put("constants",this.constants);
extensions.put("templates",this.templates);
return extensions;
}
}
|
3e062a0e172c9fee68196058ad655627a6b50a55
| 4,962 |
java
|
Java
|
optional-kubernetes-engine/image-recognition/src/main/java/com/eshaul/gcpnext/demo/HelloController.java
|
etanshaul/skaffold-jib-debug
|
b4f6e48128c8125a1ad316302a48814678256b5a
|
[
"Apache-2.0"
] | null | null | null |
optional-kubernetes-engine/image-recognition/src/main/java/com/eshaul/gcpnext/demo/HelloController.java
|
etanshaul/skaffold-jib-debug
|
b4f6e48128c8125a1ad316302a48814678256b5a
|
[
"Apache-2.0"
] | null | null | null |
optional-kubernetes-engine/image-recognition/src/main/java/com/eshaul/gcpnext/demo/HelloController.java
|
etanshaul/skaffold-jib-debug
|
b4f6e48128c8125a1ad316302a48814678256b5a
|
[
"Apache-2.0"
] | null | null | null | 40.672131 | 188 | 0.634422 | 2,606 |
package com.eshaul.gcpnext.demo;
import com.google.cloud.vision.v1.*;
import com.google.cloud.vision.v1.Image;
import com.google.common.collect.Lists;
import com.google.protobuf.ByteString;
import io.grpc.internal.IoUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;
@RestController
public class HelloController {
@RequestMapping("/java")
public String index() {
// String extractedText = "nothing";
// try {
// extractedText = extractText();
// } catch (Exception e) {
// extractedText = e.getMessage();
// e.printStackTrace();
// }
// return extractedText;
return "java";
}
@RequestMapping(value = "/image", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage() {
FileInputStream image = null;
byte[] imageBytes = null;
try {
image = new FileInputStream(extractText());
imageBytes = IoUtils.toByteArray(image);
} catch (IOException e) {
e.printStackTrace();
}
// byte[] image = imageService.getImage(id);
// image.
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(imageBytes);
}
private File extractText() throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
StringBuilder result = new StringBuilder();
ByteString imgBytes = ByteString.readFrom(getClass().getResourceAsStream("/images/k8s.png"));
File newFile = Paths.get(new File(getClass().getResource("/images/k8s.png").getFile()).getParent(), "k8s-woo.png").toFile();
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
List<BoundingPoly> boundingPolies = Lists.newArrayList();
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
out.printf("Error: %s\n", res.getError().getMessage());
// return "failed";
return null;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
// todo find the text who's bounding box is the largest > title
// https://cloud.google.com/vision/docs/detecting-fulltext to extract blocks/paragraphs
for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
result.append(annotation.getDescription() + ":");
out.printf("Text: %s\n", annotation.getDescription());
out.printf("Position : %s\n", annotation.getBoundingPoly());
boundingPolies.add(annotation.getBoundingPoly());
}
}
// String currentDir = new File(".").getAbsolutePath();
// System.out.println("current path: ------- " + currentDir);
BufferedImage bimg = ImageIO.read(new File(getClass().getResource("/images/k8s.png").getFile()));
writeImageWithBoundingPolys(bimg, boundingPolies);
boolean written = ImageIO.write(bimg, "png", newFile); //Paths.get("/Users/eshaul/k8s-new").toFile());//new File(getClass().getResource("/images/k8s-bounding.png").getFile()));
System.out.println("written-------------------" + written +":" + newFile.getAbsolutePath());
}
// return result.toString();
return newFile;
}
private void writeImageWithBoundingPolys(BufferedImage img, List<BoundingPoly> polys) throws IOException {
Graphics2D gfx = img.createGraphics();
gfx.setStroke(new BasicStroke(5));
gfx.setColor(new Color(0x00ff00));
for (BoundingPoly poly: polys) {
Polygon jpoly = new Polygon();
for (Vertex vertex: poly.getVerticesList()) {
jpoly.addPoint(vertex.getX(), vertex.getY());
}
gfx.draw(jpoly);
}
}
}
|
3e062a1a7f2cbd86ae1e3bedd0f1be0850fbebe8
| 839 |
java
|
Java
|
src/java/com/bean/BoatBean.java
|
Faiq98/JavaEE-BoatMSTI
|
915ef7a9ba05f95ce27097f9a4f62e411ce1a1be
|
[
"Apache-2.0"
] | null | null | null |
src/java/com/bean/BoatBean.java
|
Faiq98/JavaEE-BoatMSTI
|
915ef7a9ba05f95ce27097f9a4f62e411ce1a1be
|
[
"Apache-2.0"
] | null | null | null |
src/java/com/bean/BoatBean.java
|
Faiq98/JavaEE-BoatMSTI
|
915ef7a9ba05f95ce27097f9a4f62e411ce1a1be
|
[
"Apache-2.0"
] | null | null | null | 19.511628 | 60 | 0.63528 | 2,607 |
package com.bean;
public class BoatBean {
private String boatID;
private TourismCompanyBean companyID;
private String boatType;
private int boatCapacity;
public String getBoatID() {
return boatID;
}
public void setBoatID(String boatID) {
this.boatID = boatID;
}
public TourismCompanyBean getCompanyID() {
return companyID;
}
public void setCompanyID(TourismCompanyBean companyID) {
this.companyID = companyID;
}
public String getBoatType() {
return boatType;
}
public void setBoatType(String boatType) {
this.boatType = boatType;
}
public int getBoatCapacity() {
return boatCapacity;
}
public void setBoatCapacity(int boatCapacity) {
this.boatCapacity = boatCapacity;
}
}
|
3e062b66d6fb9545851b8a2da5785ca7f62f7691
| 3,421 |
java
|
Java
|
src/com/codebrig/beam/connection/traversal/punch/udp/server/handlers/ConnectionHandler.java
|
abraaocaldas/Beam
|
ae8df5fe939f6fd106330b13645b877efe2051cd
|
[
"MIT"
] | null | null | null |
src/com/codebrig/beam/connection/traversal/punch/udp/server/handlers/ConnectionHandler.java
|
abraaocaldas/Beam
|
ae8df5fe939f6fd106330b13645b877efe2051cd
|
[
"MIT"
] | null | null | null |
src/com/codebrig/beam/connection/traversal/punch/udp/server/handlers/ConnectionHandler.java
|
abraaocaldas/Beam
|
ae8df5fe939f6fd106330b13645b877efe2051cd
|
[
"MIT"
] | null | null | null | 39.930233 | 119 | 0.735585 | 2,608 |
/*
* Copyright © 2014-2015 CodeBrig, LLC.
* http://www.codebrig.com/
*
* Beam - Client/Server & P2P Networking Library
*
* ====
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ====
*/
package com.codebrig.beam.connection.traversal.punch.udp.server.handlers;
import com.codebrig.beam.Communicator;
import com.codebrig.beam.connection.traversal.punch.udp.messages.UDPPunchMessage;
import static com.codebrig.beam.connection.traversal.punch.udp.messages.UDPPunchMessageType.CONNECTION_CONNECT_MESSAGE;
import static com.codebrig.beam.connection.traversal.punch.udp.messages.UDPPunchMessageType.CONNECTION_LISTEN_MESSAGE;
import com.codebrig.beam.connection.traversal.punch.udp.server.NATDevice;
import com.codebrig.beam.connection.traversal.punch.udp.server.NATDeviceHolder;
import com.codebrig.beam.connection.traversal.punch.udp.server.UDPPunchServer;
import com.codebrig.beam.handlers.LegacyHandler;
import com.codebrig.beam.messages.LegacyMessage;
/**
*
* @author Brandon Fergerson <[email protected]>
*/
public class ConnectionHandler extends LegacyHandler
{
private UDPPunchServer punchServer;
public ConnectionHandler () {
super (CONNECTION_LISTEN_MESSAGE, CONNECTION_CONNECT_MESSAGE);
}
@Override
public LegacyMessage messageReceived (Communicator comm, LegacyMessage message) {
UDPPunchMessage msg = new UDPPunchMessage (message);
String peerIdentifier = msg.getPeerIdentifier ();
String accessCode = msg.getAccessCode ();
if (message.getType () == CONNECTION_LISTEN_MESSAGE) {
NATDevice device = new NATDevice (comm);
device.addConnection (accessCode, 0); //no port neccessary as we will do the punching
NATDeviceHolder deviceHolder = punchServer.getNATDeviceHolder ();
deviceHolder.addNATDevice (peerIdentifier, device);
} else {
String requestPeerIdentifier = msg.getRequestPeerIdentifier ();
NATDeviceHolder deviceHolder = punchServer.getNATDeviceHolder ();
NATDevice device = deviceHolder.getNATDevice (requestPeerIdentifier, accessCode);
if (device != null) {
device.getCommunicator ().queue (msg);
}
}
return null;
}
@Override
public void passObject (Object passObject) {
punchServer = (UDPPunchServer) passObject;
}
}
|
3e062b7751bea948201650e6b09e7808a1a60580
| 617 |
java
|
Java
|
dex_src/com/bumptech/glide/load/engine/b/d.java
|
megahertz0/android_thunder
|
3304c95a751ac228362bc53b47ed92e292510155
|
[
"MIT"
] | 11 |
2018-08-05T16:00:47.000Z
|
2021-11-18T02:55:40.000Z
|
dex_src/com/bumptech/glide/load/engine/b/d.java
|
megahertz0/android_thunder
|
3304c95a751ac228362bc53b47ed92e292510155
|
[
"MIT"
] | null | null | null |
dex_src/com/bumptech/glide/load/engine/b/d.java
|
megahertz0/android_thunder
|
3304c95a751ac228362bc53b47ed92e292510155
|
[
"MIT"
] | 9 |
2017-02-05T16:24:32.000Z
|
2021-11-18T02:55:42.000Z
| 22.035714 | 87 | 0.564019 | 2,609 |
package com.bumptech.glide.load.engine.b;
import java.io.File;
// compiled from: DiskLruCacheFactory.java
public class d implements com.bumptech.glide.load.engine.b.a.a {
private final int a;
private final a b;
// compiled from: DiskLruCacheFactory.java
public static interface a {
File a();
}
public d(a aVar) {
this.a = 262144000;
this.b = aVar;
}
public final a a() {
File a = this.b.a();
if (a == null) {
return null;
}
return (a.mkdirs() || (a.exists() && a.isDirectory())) ? e.a(a, this.a) : null;
}
}
|
3e062dcb38f0f54cf15e0ece0e2ecba696e09db4
| 2,699 |
java
|
Java
|
src/test/java/com/lorepo/icplayer/client/page/mockup/PlayerControllerMockup.java
|
KasiaSk/icplayer
|
1335c10789909b8eab41b1455536f92670d1df9f
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/lorepo/icplayer/client/page/mockup/PlayerControllerMockup.java
|
KasiaSk/icplayer
|
1335c10789909b8eab41b1455536f92670d1df9f
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/lorepo/icplayer/client/page/mockup/PlayerControllerMockup.java
|
KasiaSk/icplayer
|
1335c10789909b8eab41b1455536f92670d1df9f
|
[
"Apache-2.0"
] | null | null | null | 18.613793 | 74 | 0.726936 | 2,610 |
package com.lorepo.icplayer.client.page.mockup;
import java.util.HashMap;
import com.lorepo.icplayer.client.IPlayerController;
import com.lorepo.icplayer.client.content.services.ScoreService;
import com.lorepo.icplayer.client.content.services.StateService;
import com.lorepo.icplayer.client.module.api.player.IContent;
import com.lorepo.icplayer.client.module.api.player.IScoreService;
import com.lorepo.icplayer.client.module.api.player.IStateService;
import com.lorepo.icplayer.client.ui.PlayerView;
public class PlayerControllerMockup implements IPlayerController {
private IScoreService scoreService;
private StateService stateService;
public PlayerControllerMockup() {
scoreService = new ScoreService(true);
stateService = new StateService();
}
@Override
public IContent getModel() {
// TODO Auto-generated method stub
return null;
}
@Override
public IScoreService getScoreService() {
return scoreService;
}
@Override
public int getCurrentPageIndex() {
// TODO Auto-generated method stub
return 0;
}
@Override
public IStateService getStateService() {
return stateService;
}
@Override
public void switchToPage(String pageName) {
// TODO Auto-generated method stub
}
@Override
public void switchToPrevPage() {
// TODO Auto-generated method stub
}
@Override
public void switchToNextPage() {
// TODO Auto-generated method stub
}
@Override
public long getTimeElapsed() {
// TODO Auto-generated method stub
return 0;
}
@Override
public PlayerView getView() {
// TODO Auto-generated method stub
return null;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void showPopup(String pageName, String additionalClasses) {
// TODO Auto-generated method stub
}
@Override
public void closePopup() {
// TODO Auto-generated method stub
}
@Override
public void sendAnalytics(String event, HashMap<String, String> params) {
// TODO Auto-generated method stub
}
@Override
public boolean isBookMode() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean hasCover() {
// TODO Auto-generated method stub
return false;
}
@java.lang.Override
public boolean isPopupEnabled() {
// TODO Auto-generated method stub
return false;
}
@java.lang.Override
public void setPopupEnabled(boolean enabled) {
// TODO Auto-generated method stub
}
@Override
public void switchToPage(int index) {
// TODO Auto-generated method stub
}
@Override
public void switchToPageById(String pageId) {
// TODO Auto-generated method stub
}
}
|
3e062e7cf9ad9c9d63d1330c24fc9cbe9e6f72f4
| 3,766 |
java
|
Java
|
app/src/main/java/com/example/sqlbrite/widgets/RoundImageView.java
|
ChaoqinLiu/SQLBrite
|
74495c7934b03397a46a2ce4cdbcde931ff91117
|
[
"Apache-2.0"
] | 1 |
2021-11-03T08:04:59.000Z
|
2021-11-03T08:04:59.000Z
|
app/src/main/java/com/example/sqlbrite/widgets/RoundImageView.java
|
ChaoqinLiu/ImageIdentification
|
74495c7934b03397a46a2ce4cdbcde931ff91117
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/sqlbrite/widgets/RoundImageView.java
|
ChaoqinLiu/ImageIdentification
|
74495c7934b03397a46a2ce4cdbcde931ff91117
|
[
"Apache-2.0"
] | null | null | null | 36.563107 | 130 | 0.675783 | 2,611 |
package com.example.sqlbrite.widgets;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.os.Build;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.View;
import com.example.sqlbrite.R;
public class RoundImageView extends AppCompatImageView {
private float width, height;
private int defaultRadius = 0;
private int radius;
private int leftTopRadius;
private int rightTopRadius;
private int rightBottomRadius;
private int leftBottomRadius;
public RoundImageView(Context context) {
this(context, null);
init(context, null);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init(context, attrs);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
if (Build.VERSION.SDK_INT < 18) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Custom_Round_Image_View);
radius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_radius, defaultRadius);
leftTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_top_radius, defaultRadius);
rightTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_top_radius, defaultRadius);
rightBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_bottom_radius, defaultRadius);
leftBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_bottom_radius, defaultRadius);
//如果四个角的值没有设置,那么就使用通用的radius的值。
if (defaultRadius == leftTopRadius) {
leftTopRadius = radius;
}
if (defaultRadius == rightTopRadius) {
rightTopRadius = radius;
}
if (defaultRadius == rightBottomRadius) {
rightBottomRadius = radius;
}
if (defaultRadius == leftBottomRadius) {
leftBottomRadius = radius;
}
array.recycle();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
}
@Override
protected void onDraw(Canvas canvas) {
//这里做下判断,只有图片的宽高大于设置的圆角距离的时候才进行裁剪
int maxLeft = Math.max(leftTopRadius, leftBottomRadius);
int maxRight = Math.max(rightTopRadius, rightBottomRadius);
int minWidth = maxLeft + maxRight;
int maxTop = Math.max(leftTopRadius, rightTopRadius);
int maxBottom = Math.max(leftBottomRadius, rightBottomRadius);
int minHeight = maxTop + maxBottom;
if (width >= minWidth && height > minHeight) {
Path path = new Path();
//四个角:右上,右下,左下,左上
path.moveTo(leftTopRadius, 0);
path.lineTo(width - rightTopRadius, 0);
path.quadTo(width, 0, width, rightTopRadius);
path.lineTo(width, height - rightBottomRadius);
path.quadTo(width, height, width - rightBottomRadius, height);
path.lineTo(leftBottomRadius, height);
path.quadTo(0, height, 0, height - leftBottomRadius);
path.lineTo(0, leftTopRadius);
path.quadTo(0, 0, leftTopRadius, 0);
canvas.clipPath(path);
}
super.onDraw(canvas);
}
}
|
3e062f1b75f5fe612c921eb8e29a68443cd23382
| 11,170 |
java
|
Java
|
platform/arcus-containers/platform-services/src/main/java/com/iris/platform/address/validation/smartystreets/HttpSmartyStreetsClient.java
|
eanderso/arcusplatform
|
a2293efa1cd8e884e6bedbe9c51bf29832ba8652
|
[
"Apache-2.0"
] | null | null | null |
platform/arcus-containers/platform-services/src/main/java/com/iris/platform/address/validation/smartystreets/HttpSmartyStreetsClient.java
|
eanderso/arcusplatform
|
a2293efa1cd8e884e6bedbe9c51bf29832ba8652
|
[
"Apache-2.0"
] | null | null | null |
platform/arcus-containers/platform-services/src/main/java/com/iris/platform/address/validation/smartystreets/HttpSmartyStreetsClient.java
|
eanderso/arcusplatform
|
a2293efa1cd8e884e6bedbe9c51bf29832ba8652
|
[
"Apache-2.0"
] | null | null | null | 36.986755 | 124 | 0.714772 | 2,612 |
/*
* Copyright 2019 Arcus 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.iris.platform.address.validation.smartystreets;
import static com.iris.messages.errors.Errors.genericError;
import static com.iris.util.GsonUtil.getMemberAsDouble;
import static com.iris.util.GsonUtil.getMemberAsString;
import static org.apache.http.HttpStatus.SC_OK;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Timer;
import com.codahale.metrics.Timer.Context;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.iris.messages.errors.ErrorEventException;
import com.iris.metrics.IrisMetricSet;
import com.iris.metrics.IrisMetrics;
import com.iris.metrics.tag.TaggingMetric;
import com.iris.platform.address.StreetAddress;
@Singleton
public class HttpSmartyStreetsClient implements SmartyStreetsClient
{
private static final Logger logger = getLogger(HttpSmartyStreetsClient.class);
private static final IrisMetricSet metrics = IrisMetrics.metrics("smartystreets");
@SuppressWarnings("serial")
private static final Type streetAddressesType = new TypeToken<List<StreetAddress>>(){}.getType();
@SuppressWarnings("serial")
private static final Type detailedStreetAddressesType = new TypeToken<List<DetailedStreetAddress>>(){}.getType();
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(StreetAddress.class, new StreetAddressDeserializer())
.registerTypeAdapter(DetailedStreetAddress.class, new DetailedStreetAddressDeserializer())
.create();
private final URI serviceBaseUri;
private final CloseableHttpClient httpClient;
private final TaggingMetric<Timer> requestTimerMetric;
private final TaggingMetric<Counter> failureCounterMetric;
@Inject
public HttpSmartyStreetsClient(SmartyStreetsClientConfig config, CloseableHttpClient httpClient)
throws URISyntaxException
{
serviceBaseUri = new URIBuilder(config.getServiceBaseUrl())
.addParameter("auth-id", config.getAuthId())
.addParameter("auth-token", config.getAuthToken())
.addParameter("candidates", Integer.toString(config.getCandidates()))
.build();
this.httpClient = httpClient;
requestTimerMetric = metrics.taggingTimer("request.time");
failureCounterMetric = metrics.taggingCounter("failure.count");
}
@Override
public List<StreetAddress> getSuggestions(StreetAddress address)
{
try (Context timerContext = requestTimerMetric.tag("op", "getSuggestions").time())
{
String jsonResponse = sendRequest(address);
return gson.fromJson(jsonResponse, streetAddressesType);
}
}
@Override
public List<DetailedStreetAddress> getDetailedSuggestions(StreetAddress address)
{
try (Context timerContext = requestTimerMetric.tag("op", "getDetailedSuggestions").time())
{
String jsonResponse = sendRequest(address);
return gson.fromJson(jsonResponse, detailedStreetAddressesType);
}
}
private String sendRequest(StreetAddress address)
{
URI serviceUri = buildServiceUri(address);
HttpGet httpGet = new HttpGet(serviceUri);
// These headers are mentioned as required by the SmartyStreets docs
httpGet.addHeader("Content-Type", APPLICATION_JSON.getMimeType());
httpGet.addHeader("Host", serviceUri.getHost());
return sendRequest(httpGet);
}
private URI buildServiceUri(StreetAddress address)
{
try
{
return new URIBuilder(serviceBaseUri)
.addParameter("street", address.getLine1())
.addParameter("street2", address.getLine2())
.addParameter("city", address.getCity())
.addParameter("state", address.getState())
.addParameter("zipcode", address.getZip())
.build();
}
catch (URISyntaxException e)
{
throw new ErrorEventException(genericError(), e);
}
}
/*
* NOTE: Although HttpClient is thread-safe, Apache docs "highly recommend" that each thread use a separate
* HttpContext:
*
* https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e405 ("2.4. Multithreaded request
* execution")
*
* For now we are keeping the HttpContext as a local, although it's possible it could be moved into a ThreadLocal for
* better memory efficiency. (The context might get into a weird state and requests which run on a
* certain thread might fail.)
*/
private String sendRequest(HttpUriRequest httpUriRequest)
{
HttpContext httpContext = HttpClientContext.create();
logger.trace("SmartyStreets API request = {}", httpUriRequest);
try (CloseableHttpResponse response = httpClient.execute(httpUriRequest, httpContext))
{
logger.trace("SmartyStreets API response = {}", response);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != SC_OK)
{
failureCounterMetric
.tag("httpResponse.statusCode", Integer.toString(statusCode))
.inc();
// No root cause to include here, but we have the status code included in the failure counter above
throw new ErrorEventException(genericError());
}
try (InputStream contentIn = response.getEntity().getContent())
{
String content = IOUtils.toString(contentIn);
logger.trace("SmartyStreets API response content = {}", content);
return content;
}
}
catch (IOException e)
{
throw new ErrorEventException(genericError(), e);
}
}
private static abstract class AbstractStreetAddressDeserializer<T extends StreetAddress> implements JsonDeserializer<T>
{
@Override
public T deserialize(JsonElement addressElement, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
JsonObject addressObject = addressElement.getAsJsonObject();
String line1 = getMemberAsString(addressObject, "delivery_line_1");
String line2 = getMemberAsString(addressObject, "delivery_line_2");
JsonObject componentsObject = addressObject.get("components").getAsJsonObject();
String city = getMemberAsString(componentsObject, "city_name");
String state = getMemberAsString(componentsObject, "state_abbreviation");
String zip5 = getMemberAsString(componentsObject, "zipcode");
String zipPlus4 = getMemberAsString(componentsObject, "plus4_code");
String zip = StreetAddress.zipBuilder()
.withZip(zip5)
.withZipPlus4(zipPlus4)
.build();
T streetAddress = newStreetAddress();
streetAddress.setLine1(line1);
streetAddress.setLine2(line2);
streetAddress.setCity(city);
streetAddress.setState(state);
streetAddress.setZip(zip);
return streetAddress;
}
protected abstract T newStreetAddress();
}
private static class StreetAddressDeserializer extends AbstractStreetAddressDeserializer<StreetAddress>
{
@Override
protected StreetAddress newStreetAddress()
{
return new StreetAddress();
}
}
private static class DetailedStreetAddressDeserializer extends AbstractStreetAddressDeserializer<DetailedStreetAddress>
{
@Override
public DetailedStreetAddress deserialize(JsonElement addressElement, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
DetailedStreetAddress detailedStreetAddress = super.deserialize(addressElement, typeOfT, context);
JsonObject addressObject = addressElement.getAsJsonObject();
JsonObject componentsObject = addressObject.get("components").getAsJsonObject();
String plus4Code = getMemberAsString(componentsObject, "plus4_code");
String country = "US";
JsonObject metadataObject = addressObject.get("metadata").getAsJsonObject();
String addrType = getMemberAsString(metadataObject, "record_type");
String addrZipType = getMemberAsString(metadataObject, "zip_type");
String addrRDI = getMemberAsString(metadataObject, "rdi");
String addrCountyFIPS = getMemberAsString(metadataObject, "county_fips");
Double addrLatitude = getMemberAsDouble(metadataObject, "latitude");
Double addrLongitude = getMemberAsDouble(metadataObject, "longitude");
String addrGeoPrecision = getMemberAsString(metadataObject, "precision");
String zip = StreetAddress.zipBuilder()
.withZip(detailedStreetAddress.getZip())
.withZipPlus4(plus4Code)
.build();
detailedStreetAddress.setZipPlus4(zip);
detailedStreetAddress.setCountry(country);
detailedStreetAddress.setAddrType(addrType);
detailedStreetAddress.setAddrZipType(addrZipType);
detailedStreetAddress.setAddrRDI(addrRDI);
detailedStreetAddress.setAddrCountyFIPS(addrCountyFIPS);
detailedStreetAddress.setAddrLatitude(addrLatitude);
detailedStreetAddress.setAddrLongitude(addrLongitude);
detailedStreetAddress.setAddrGeoPrecision(addrGeoPrecision.toUpperCase());
return detailedStreetAddress;
}
@Override
protected DetailedStreetAddress newStreetAddress()
{
return new DetailedStreetAddress();
}
}
}
|
3e062fba4a38f9ce9224d8eee6eb0e23db0f7823
| 4,162 |
java
|
Java
|
activemq-client/src/main/java/org/apache/activemq/transport/nio/NIOInputStream.java
|
sho25/activemq
|
d34b61b56206883e6570ae7207c3ddb074311adf
|
[
"Apache-2.0"
] | null | null | null |
activemq-client/src/main/java/org/apache/activemq/transport/nio/NIOInputStream.java
|
sho25/activemq
|
d34b61b56206883e6570ae7207c3ddb074311adf
|
[
"Apache-2.0"
] | 7 |
2020-06-18T17:27:51.000Z
|
2022-02-01T01:05:30.000Z
|
activemq-client/src/main/java/org/apache/activemq/transport/nio/NIOInputStream.java
|
sho25/activemq
|
d34b61b56206883e6570ae7207c3ddb074311adf
|
[
"Apache-2.0"
] | null | null | null | 14.811388 | 811 | 0.784238 | 2,613 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|transport
operator|.
name|nio
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|InputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|BufferUnderflowException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|ByteBuffer
import|;
end_import
begin_comment
comment|/** * An optimized buffered input stream for Tcp * * */
end_comment
begin_class
specifier|public
class|class
name|NIOInputStream
extends|extends
name|InputStream
block|{
specifier|protected
name|int
name|count
decl_stmt|;
specifier|protected
name|int
name|position
decl_stmt|;
specifier|private
specifier|final
name|ByteBuffer
name|in
decl_stmt|;
specifier|public
name|NIOInputStream
parameter_list|(
name|ByteBuffer
name|in
parameter_list|)
block|{
name|this
operator|.
name|in
operator|=
name|in
expr_stmt|;
block|}
specifier|public
name|int
name|read
parameter_list|()
throws|throws
name|IOException
block|{
try|try
block|{
name|int
name|rc
init|=
name|in
operator|.
name|get
argument_list|()
operator|&
literal|0xff
decl_stmt|;
return|return
name|rc
return|;
block|}
catch|catch
parameter_list|(
name|BufferUnderflowException
name|e
parameter_list|)
block|{
return|return
operator|-
literal|1
return|;
block|}
block|}
specifier|public
name|int
name|read
parameter_list|(
name|byte
name|b
index|[]
parameter_list|,
name|int
name|off
parameter_list|,
name|int
name|len
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
name|in
operator|.
name|hasRemaining
argument_list|()
condition|)
block|{
name|int
name|rc
init|=
name|Math
operator|.
name|min
argument_list|(
name|len
argument_list|,
name|in
operator|.
name|remaining
argument_list|()
argument_list|)
decl_stmt|;
name|in
operator|.
name|get
argument_list|(
name|b
argument_list|,
name|off
argument_list|,
name|rc
argument_list|)
expr_stmt|;
return|return
name|rc
return|;
block|}
else|else
block|{
return|return
name|len
operator|==
literal|0
condition|?
literal|0
else|:
operator|-
literal|1
return|;
block|}
block|}
specifier|public
name|long
name|skip
parameter_list|(
name|long
name|n
parameter_list|)
throws|throws
name|IOException
block|{
name|int
name|rc
init|=
name|Math
operator|.
name|min
argument_list|(
operator|(
name|int
operator|)
name|n
argument_list|,
name|in
operator|.
name|remaining
argument_list|()
argument_list|)
decl_stmt|;
name|in
operator|.
name|position
argument_list|(
name|in
operator|.
name|position
argument_list|()
operator|+
name|rc
argument_list|)
expr_stmt|;
return|return
name|rc
return|;
block|}
specifier|public
name|int
name|available
parameter_list|()
throws|throws
name|IOException
block|{
return|return
name|in
operator|.
name|remaining
argument_list|()
return|;
block|}
specifier|public
name|boolean
name|markSupported
parameter_list|()
block|{
return|return
literal|false
return|;
block|}
specifier|public
name|void
name|close
parameter_list|()
throws|throws
name|IOException
block|{ }
block|}
end_class
end_unit
|
3e0631e102b6918d4c6669abc04be316afd56fe0
| 1,750 |
java
|
Java
|
sdo/eclipselink.sdo.test/src/org/eclipse/persistence/testing/sdo/helper/copyhelper/SDOCopyHelperOriginalDeepCopyTestCases.java
|
marschall/eclipselink.runtime
|
3d59eaa9e420902d5347b9fb60fbe6c92310894b
|
[
"BSD-3-Clause"
] | null | null | null |
sdo/eclipselink.sdo.test/src/org/eclipse/persistence/testing/sdo/helper/copyhelper/SDOCopyHelperOriginalDeepCopyTestCases.java
|
marschall/eclipselink.runtime
|
3d59eaa9e420902d5347b9fb60fbe6c92310894b
|
[
"BSD-3-Clause"
] | 2 |
2021-03-24T17:58:46.000Z
|
2021-12-14T20:59:52.000Z
|
sdo/eclipselink.sdo.test/src/org/eclipse/persistence/testing/sdo/helper/copyhelper/SDOCopyHelperOriginalDeepCopyTestCases.java
|
marschall/eclipselink.runtime
|
3d59eaa9e420902d5347b9fb60fbe6c92310894b
|
[
"BSD-3-Clause"
] | null | null | null | 41.666667 | 87 | 0.662857 | 2,614 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.sdo.helper.copyhelper;
import commonj.sdo.DataObject;
import org.eclipse.persistence.sdo.SDOChangeSummary;
public class SDOCopyHelperOriginalDeepCopyTestCases extends SDOCopyHelperDeepCopyTest {
public SDOCopyHelperOriginalDeepCopyTestCases(String name) {
super(name);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(SDOCopyHelperOriginalDeepCopyTestCases.class);
}
public SDOChangeSummary getChangeSummary() {
return(SDOChangeSummary)containedDataObject.getChangeSummary();
}
public void assertEqualityHelperEqual(DataObject original, DataObject copy) {
if (original.getChangeSummary() != null) {
if (original.getChangeSummary().getChangedDataObjects().size() > 0) {
assertFalse(equalityHelper.equal(original, copy));
original.getChangeSummary().undoChanges();
}
}
assertTrue(equalityHelper.equal(original, copy));
}
}
|
3e0632b66ef8f8097e420c5c89920827c5abdaa4
| 40,301 |
java
|
Java
|
holyshield/2016/mobile_sound_meter/source_original/android/support/v4/widget/NestedScrollView.java
|
PurpEth/solved-hacking-problem
|
6f289d1647eb9c091caa580c7aae673e3ba02952
|
[
"Unlicense"
] | 1 |
2021-08-24T22:16:41.000Z
|
2021-08-24T22:16:41.000Z
|
holyshield/2016/mobile_sound_meter/source_refactored/android/support/v4/widget/NestedScrollView.java
|
PurpEth/solved-hacking-problem
|
6f289d1647eb9c091caa580c7aae673e3ba02952
|
[
"Unlicense"
] | null | null | null |
holyshield/2016/mobile_sound_meter/source_refactored/android/support/v4/widget/NestedScrollView.java
|
PurpEth/solved-hacking-problem
|
6f289d1647eb9c091caa580c7aae673e3ba02952
|
[
"Unlicense"
] | null | null | null | 35.664602 | 281 | 0.507456 | 2,615 |
package android.support.v4.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Parcelable;
import android.support.v4.p004h.az;
import android.support.v4.p004h.bi;
import android.support.v4.p004h.bj;
import android.support.v4.p004h.bk;
import android.support.v4.p004h.bl;
import android.support.v4.p004h.bn;
import android.support.v4.p004h.bp;
import android.support.v4.p004h.bu;
import android.support.v7.p015b.C0243l;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.FocusFinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewParent;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import java.util.List;
public class NestedScrollView extends FrameLayout implements bi, bk, bn {
private static final ad f481v;
private static final int[] f482w;
private ae f483A;
private long f484a;
private final Rect f485b;
private at f486c;
private C0192s f487d;
private C0192s f488e;
private int f489f;
private boolean f490g;
private boolean f491h;
private View f492i;
private boolean f493j;
private VelocityTracker f494k;
private boolean f495l;
private boolean f496m;
private int f497n;
private int f498o;
private int f499p;
private int f500q;
private final int[] f501r;
private final int[] f502s;
private int f503t;
private af f504u;
private final bl f505x;
private final bj f506y;
private float f507z;
static {
f481v = new ad();
f482w = new int[]{16843130};
}
public NestedScrollView(Context context) {
this(context, null);
}
public NestedScrollView(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public NestedScrollView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.f485b = new Rect();
this.f490g = true;
this.f491h = false;
this.f492i = null;
this.f493j = false;
this.f496m = true;
this.f500q = -1;
this.f501r = new int[2];
this.f502s = new int[2];
m1361a();
TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, f482w, i, 0);
setFillViewport(obtainStyledAttributes.getBoolean(0, false));
obtainStyledAttributes.recycle();
this.f505x = new bl(this);
this.f506y = new bj(this);
setNestedScrollingEnabled(true);
bu.m984a((View) this, f481v);
}
private View m1360a(boolean z, int i, int i2) {
List focusables = getFocusables(2);
View view = null;
Object obj = null;
int size = focusables.size();
int i3 = 0;
while (i3 < size) {
View view2;
Object obj2;
View view3 = (View) focusables.get(i3);
int top = view3.getTop();
int bottom = view3.getBottom();
if (i < bottom && top < i2) {
Object obj3 = (i >= top || bottom >= i2) ? null : 1;
if (view == null) {
Object obj4 = obj3;
view2 = view3;
obj2 = obj4;
} else {
Object obj5 = ((!z || top >= view.getTop()) && (z || bottom <= view.getBottom())) ? null : 1;
if (obj != null) {
if (!(obj3 == null || obj5 == null)) {
view2 = view3;
obj2 = obj;
}
} else if (obj3 != null) {
view2 = view3;
int i4 = 1;
} else if (obj5 != null) {
view2 = view3;
obj2 = obj;
}
}
i3++;
view = view2;
obj = obj2;
}
obj2 = obj;
view2 = view;
i3++;
view = view2;
obj = obj2;
}
return view;
}
private void m1361a() {
this.f486c = at.m1468a(getContext(), null);
setFocusable(true);
setDescendantFocusability(262144);
setWillNotDraw(false);
ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
this.f497n = viewConfiguration.getScaledTouchSlop();
this.f498o = viewConfiguration.getScaledMinimumFlingVelocity();
this.f499p = viewConfiguration.getScaledMaximumFlingVelocity();
}
private void m1362a(MotionEvent motionEvent) {
int action = (motionEvent.getAction() & 65280) >> 8;
if (az.m898b(motionEvent, action) == this.f500q) {
action = action == 0 ? 1 : 0;
this.f489f = (int) az.m901d(motionEvent, action);
this.f500q = az.m898b(motionEvent, action);
if (this.f494k != null) {
this.f494k.clear();
}
}
}
private boolean m1363a(int i, int i2, int i3) {
boolean z = false;
int height = getHeight();
int scrollY = getScrollY();
int i4 = scrollY + height;
boolean z2 = i == 33;
View a = m1360a(z2, i2, i3);
if (a == null) {
a = this;
}
if (i2 < scrollY || i3 > i4) {
m1375e(z2 ? i2 - scrollY : i3 - i4);
z = true;
}
if (a != findFocus()) {
a.requestFocus(i);
}
return z;
}
private boolean m1364a(Rect rect, boolean z) {
int a = m1379a(rect);
boolean z2 = a != 0;
if (z2) {
if (z) {
scrollBy(0, a);
} else {
m1380a(0, a);
}
}
return z2;
}
private boolean m1365a(View view) {
return !m1366a(view, 0, getHeight());
}
private boolean m1366a(View view, int i, int i2) {
view.getDrawingRect(this.f485b);
offsetDescendantRectToMyCoords(view, this.f485b);
return this.f485b.bottom + i >= getScrollY() && this.f485b.top - i <= getScrollY() + i2;
}
private static boolean m1367a(View view, View view2) {
if (view == view2) {
return true;
}
ViewParent parent = view.getParent();
boolean z = (parent instanceof ViewGroup) && m1367a((View) parent, view2);
return z;
}
private static int m1368b(int i, int i2, int i3) {
return (i2 >= i3 || i < 0) ? 0 : i2 + i > i3 ? i3 - i2 : i;
}
private void m1369b(View view) {
view.getDrawingRect(this.f485b);
offsetDescendantRectToMyCoords(view, this.f485b);
int a = m1379a(this.f485b);
if (a != 0) {
scrollBy(0, a);
}
}
private boolean m1370b() {
View childAt = getChildAt(0);
if (childAt == null) {
return false;
}
return getHeight() < (childAt.getHeight() + getPaddingTop()) + getPaddingBottom();
}
private void m1371c() {
if (this.f494k == null) {
this.f494k = VelocityTracker.obtain();
} else {
this.f494k.clear();
}
}
private boolean m1372c(int i, int i2) {
if (getChildCount() <= 0) {
return false;
}
int scrollY = getScrollY();
View childAt = getChildAt(0);
return i2 >= childAt.getTop() - scrollY && i2 < childAt.getBottom() - scrollY && i >= childAt.getLeft() && i < childAt.getRight();
}
private void m1373d() {
if (this.f494k == null) {
this.f494k = VelocityTracker.obtain();
}
}
private void m1374e() {
if (this.f494k != null) {
this.f494k.recycle();
this.f494k = null;
}
}
private void m1375e(int i) {
if (i == 0) {
return;
}
if (this.f496m) {
m1380a(0, i);
} else {
scrollBy(0, i);
}
}
private void m1376f() {
this.f493j = false;
m1374e();
stopNestedScroll();
if (this.f487d != null) {
this.f487d.m1565b();
this.f488e.m1565b();
}
}
private void m1377f(int i) {
int scrollY = getScrollY();
boolean z = (scrollY > 0 || i > 0) && (scrollY < getScrollRange() || i < 0);
if (!dispatchNestedPreFling(0.0f, (float) i)) {
dispatchNestedFling(0.0f, (float) i, z);
if (z) {
m1387d(i);
}
}
}
private void m1378g() {
if (bu.m977a(this) == 2) {
this.f487d = null;
this.f488e = null;
} else if (this.f487d == null) {
Context context = getContext();
this.f487d = new C0192s(context);
this.f488e = new C0192s(context);
}
}
private int getScrollRange() {
return getChildCount() > 0 ? Math.max(0, getChildAt(0).getHeight() - ((getHeight() - getPaddingBottom()) - getPaddingTop())) : 0;
}
private float getVerticalScrollFactorCompat() {
if (this.f507z == 0.0f) {
TypedValue typedValue = new TypedValue();
Context context = getContext();
if (context.getTheme().resolveAttribute(16842829, typedValue, true)) {
this.f507z = typedValue.getDimension(context.getResources().getDisplayMetrics());
} else {
throw new IllegalStateException("Expected theme to define listPreferredItemHeight.");
}
}
return this.f507z;
}
protected int m1379a(Rect rect) {
if (getChildCount() == 0) {
return 0;
}
int height = getHeight();
int scrollY = getScrollY();
int i = scrollY + height;
int verticalFadingEdgeLength = getVerticalFadingEdgeLength();
if (rect.top > 0) {
scrollY += verticalFadingEdgeLength;
}
if (rect.bottom < getChildAt(0).getHeight()) {
i -= verticalFadingEdgeLength;
}
if (rect.bottom > i && rect.top > scrollY) {
scrollY = Math.min(rect.height() > height ? (rect.top - scrollY) + 0 : (rect.bottom - i) + 0, getChildAt(0).getBottom() - i);
} else if (rect.top >= scrollY || rect.bottom >= i) {
scrollY = 0;
} else {
scrollY = Math.max(rect.height() > height ? 0 - (i - rect.bottom) : 0 - (scrollY - rect.top), -getScrollY());
}
return scrollY;
}
public final void m1380a(int i, int i2) {
if (getChildCount() != 0) {
if (AnimationUtils.currentAnimationTimeMillis() - this.f484a > 250) {
int max = Math.max(0, getChildAt(0).getHeight() - ((getHeight() - getPaddingBottom()) - getPaddingTop()));
int scrollY = getScrollY();
this.f486c.m1469a(getScrollX(), scrollY, 0, Math.max(0, Math.min(scrollY + i2, max)) - scrollY);
bu.m990b(this);
} else {
if (!this.f486c.m1472a()) {
this.f486c.m1479g();
}
scrollBy(i, i2);
}
this.f484a = AnimationUtils.currentAnimationTimeMillis();
}
}
public boolean m1381a(int i) {
int i2 = i == 130 ? 1 : 0;
int height = getHeight();
if (i2 != 0) {
this.f485b.top = getScrollY() + height;
i2 = getChildCount();
if (i2 > 0) {
View childAt = getChildAt(i2 - 1);
if (this.f485b.top + height > childAt.getBottom()) {
this.f485b.top = childAt.getBottom() - height;
}
}
} else {
this.f485b.top = getScrollY() - height;
if (this.f485b.top < 0) {
this.f485b.top = 0;
}
}
this.f485b.bottom = this.f485b.top + height;
return m1363a(i, this.f485b.top, this.f485b.bottom);
}
boolean m1382a(int i, int i2, int i3, int i4, int i5, int i6, int i7, int i8, boolean z) {
boolean z2;
boolean z3;
int a = bu.m977a(this);
Object obj = computeHorizontalScrollRange() > computeHorizontalScrollExtent() ? 1 : null;
Object obj2 = computeVerticalScrollRange() > computeVerticalScrollExtent() ? 1 : null;
Object obj3 = (a == 0 || (a == 1 && obj != null)) ? 1 : null;
obj = (a == 0 || (a == 1 && obj2 != null)) ? 1 : null;
int i9 = i3 + i;
if (obj3 == null) {
i7 = 0;
}
int i10 = i4 + i2;
if (obj == null) {
i8 = 0;
}
int i11 = -i7;
int i12 = i7 + i5;
a = -i8;
int i13 = i8 + i6;
if (i9 > i12) {
z2 = true;
} else if (i9 < i11) {
z2 = true;
i12 = i11;
} else {
z2 = false;
i12 = i9;
}
if (i10 > i13) {
z3 = true;
} else if (i10 < a) {
z3 = true;
i13 = a;
} else {
z3 = false;
i13 = i10;
}
if (z3) {
this.f486c.m1473a(i12, i13, 0, 0, 0, getScrollRange());
}
onOverScrolled(i12, i13, z2, z3);
return z2 || z3;
}
public boolean m1383a(KeyEvent keyEvent) {
int i = 33;
this.f485b.setEmpty();
if (m1370b()) {
if (keyEvent.getAction() != 0) {
return false;
}
switch (keyEvent.getKeyCode()) {
case C0243l.Toolbar_collapseContentDescription /*19*/:
return !keyEvent.isAltPressed() ? m1386c(33) : m1385b(33);
case C0243l.Toolbar_navigationIcon /*20*/:
return !keyEvent.isAltPressed() ? m1386c(130) : m1385b(130);
case C0243l.AppCompatTheme_editTextColor /*62*/:
if (!keyEvent.isShiftPressed()) {
i = 130;
}
m1381a(i);
return false;
default:
return false;
}
} else if (!isFocused() || keyEvent.getKeyCode() == 4) {
return false;
} else {
View findFocus = findFocus();
if (findFocus == this) {
findFocus = null;
}
findFocus = FocusFinder.getInstance().findNextFocus(this, findFocus, 130);
boolean z = (findFocus == null || findFocus == this || !findFocus.requestFocus(130)) ? false : true;
return z;
}
}
public void addView(View view) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(view);
}
public void addView(View view, int i) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(view, i);
}
public void addView(View view, int i, LayoutParams layoutParams) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(view, i, layoutParams);
}
public void addView(View view, LayoutParams layoutParams) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(view, layoutParams);
}
public final void m1384b(int i, int i2) {
m1380a(i - getScrollX(), i2 - getScrollY());
}
public boolean m1385b(int i) {
int i2 = i == 130 ? 1 : 0;
int height = getHeight();
this.f485b.top = 0;
this.f485b.bottom = height;
if (i2 != 0) {
i2 = getChildCount();
if (i2 > 0) {
this.f485b.bottom = getChildAt(i2 - 1).getBottom() + getPaddingBottom();
this.f485b.top = this.f485b.bottom - height;
}
}
return m1363a(i, this.f485b.top, this.f485b.bottom);
}
public boolean m1386c(int i) {
View findFocus = findFocus();
if (findFocus == this) {
findFocus = null;
}
View findNextFocus = FocusFinder.getInstance().findNextFocus(this, findFocus, i);
int maxScrollAmount = getMaxScrollAmount();
if (findNextFocus == null || !m1366a(findNextFocus, maxScrollAmount, getHeight())) {
if (i == 33 && getScrollY() < maxScrollAmount) {
maxScrollAmount = getScrollY();
} else if (i == 130 && getChildCount() > 0) {
int bottom = getChildAt(0).getBottom();
int scrollY = (getScrollY() + getHeight()) - getPaddingBottom();
if (bottom - scrollY < maxScrollAmount) {
maxScrollAmount = bottom - scrollY;
}
}
if (maxScrollAmount == 0) {
return false;
}
if (i != 130) {
maxScrollAmount = -maxScrollAmount;
}
m1375e(maxScrollAmount);
} else {
findNextFocus.getDrawingRect(this.f485b);
offsetDescendantRectToMyCoords(findNextFocus, this.f485b);
m1375e(m1379a(this.f485b));
findNextFocus.requestFocus(i);
}
if (findFocus != null && findFocus.isFocused() && m1365a(findFocus)) {
int descendantFocusability = getDescendantFocusability();
setDescendantFocusability(131072);
requestFocus();
setDescendantFocusability(descendantFocusability);
}
return true;
}
public int computeHorizontalScrollExtent() {
return super.computeHorizontalScrollExtent();
}
public int computeHorizontalScrollOffset() {
return super.computeHorizontalScrollOffset();
}
public int computeHorizontalScrollRange() {
return super.computeHorizontalScrollRange();
}
public void computeScroll() {
if (this.f486c.m1478f()) {
int scrollX = getScrollX();
int scrollY = getScrollY();
int b = this.f486c.m1474b();
int c = this.f486c.m1475c();
if (scrollX != b || scrollY != c) {
int scrollRange = getScrollRange();
int a = bu.m977a(this);
int i = (a == 0 || (a == 1 && scrollRange > 0)) ? 1 : 0;
m1382a(b - scrollX, c - scrollY, scrollX, scrollY, 0, scrollRange, 0, 0, false);
if (i != 0) {
m1378g();
if (c <= 0 && scrollY > 0) {
this.f487d.m1563a((int) this.f486c.m1477e());
} else if (c >= scrollRange && scrollY < scrollRange) {
this.f488e.m1563a((int) this.f486c.m1477e());
}
}
}
}
}
public int computeVerticalScrollExtent() {
return super.computeVerticalScrollExtent();
}
public int computeVerticalScrollOffset() {
return Math.max(0, super.computeVerticalScrollOffset());
}
public int computeVerticalScrollRange() {
int height = (getHeight() - getPaddingBottom()) - getPaddingTop();
if (getChildCount() == 0) {
return height;
}
int bottom = getChildAt(0).getBottom();
int scrollY = getScrollY();
height = Math.max(0, bottom - height);
return scrollY < 0 ? bottom - scrollY : scrollY > height ? bottom + (scrollY - height) : bottom;
}
public void m1387d(int i) {
if (getChildCount() > 0) {
int height = (getHeight() - getPaddingBottom()) - getPaddingTop();
int height2 = getChildAt(0).getHeight();
this.f486c.m1471a(getScrollX(), getScrollY(), 0, i, 0, 0, 0, Math.max(0, height2 - height), 0, height / 2);
bu.m990b(this);
}
}
public boolean dispatchKeyEvent(KeyEvent keyEvent) {
return super.dispatchKeyEvent(keyEvent) || m1383a(keyEvent);
}
public boolean dispatchNestedFling(float f, float f2, boolean z) {
return this.f506y.m961a(f, f2, z);
}
public boolean dispatchNestedPreFling(float f, float f2) {
return this.f506y.m960a(f, f2);
}
public boolean dispatchNestedPreScroll(int i, int i2, int[] iArr, int[] iArr2) {
return this.f506y.m964a(i, i2, iArr, iArr2);
}
public boolean dispatchNestedScroll(int i, int i2, int i3, int i4, int[] iArr) {
return this.f506y.m963a(i, i2, i3, i4, iArr);
}
public void draw(Canvas canvas) {
super.draw(canvas);
if (this.f487d != null) {
int save;
int width;
int scrollY = getScrollY();
if (!this.f487d.m1561a()) {
save = canvas.save();
width = (getWidth() - getPaddingLeft()) - getPaddingRight();
canvas.translate((float) getPaddingLeft(), (float) Math.min(0, scrollY));
this.f487d.m1560a(width, getHeight());
if (this.f487d.m1564a(canvas)) {
bu.m990b(this);
}
canvas.restoreToCount(save);
}
if (!this.f488e.m1561a()) {
save = canvas.save();
width = (getWidth() - getPaddingLeft()) - getPaddingRight();
int height = getHeight();
canvas.translate((float) ((-width) + getPaddingLeft()), (float) (Math.max(getScrollRange(), scrollY) + height));
canvas.rotate(180.0f, (float) width, 0.0f);
this.f488e.m1560a(width, height);
if (this.f488e.m1564a(canvas)) {
bu.m990b(this);
}
canvas.restoreToCount(save);
}
}
}
protected float getBottomFadingEdgeStrength() {
if (getChildCount() == 0) {
return 0.0f;
}
int verticalFadingEdgeLength = getVerticalFadingEdgeLength();
int bottom = (getChildAt(0).getBottom() - getScrollY()) - (getHeight() - getPaddingBottom());
return bottom < verticalFadingEdgeLength ? ((float) bottom) / ((float) verticalFadingEdgeLength) : 1.0f;
}
public int getMaxScrollAmount() {
return (int) (0.5f * ((float) getHeight()));
}
public int getNestedScrollAxes() {
return this.f505x.m967a();
}
protected float getTopFadingEdgeStrength() {
if (getChildCount() == 0) {
return 0.0f;
}
int verticalFadingEdgeLength = getVerticalFadingEdgeLength();
int scrollY = getScrollY();
return scrollY < verticalFadingEdgeLength ? ((float) scrollY) / ((float) verticalFadingEdgeLength) : 1.0f;
}
public boolean hasNestedScrollingParent() {
return this.f506y.m965b();
}
public boolean isNestedScrollingEnabled() {
return this.f506y.m959a();
}
protected void measureChild(View view, int i, int i2) {
view.measure(getChildMeasureSpec(i, getPaddingLeft() + getPaddingRight(), view.getLayoutParams().width), MeasureSpec.makeMeasureSpec(0, 0));
}
protected void measureChildWithMargins(View view, int i, int i2, int i3, int i4) {
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) view.getLayoutParams();
view.measure(getChildMeasureSpec(i, (((getPaddingLeft() + getPaddingRight()) + marginLayoutParams.leftMargin) + marginLayoutParams.rightMargin) + i2, marginLayoutParams.width), MeasureSpec.makeMeasureSpec(marginLayoutParams.bottomMargin + marginLayoutParams.topMargin, 0));
}
public void onAttachedToWindow() {
this.f491h = false;
}
public boolean onGenericMotionEvent(MotionEvent motionEvent) {
if ((az.m900c(motionEvent) & 2) == 0) {
return false;
}
switch (motionEvent.getAction()) {
case C0243l.Toolbar_contentInsetRight /*8*/:
if (this.f493j) {
return false;
}
float e = az.m902e(motionEvent, 9);
if (e == 0.0f) {
return false;
}
int verticalScrollFactorCompat = (int) (e * getVerticalScrollFactorCompat());
int scrollRange = getScrollRange();
int scrollY = getScrollY();
verticalScrollFactorCompat = scrollY - verticalScrollFactorCompat;
if (verticalScrollFactorCompat < 0) {
scrollRange = 0;
} else if (verticalScrollFactorCompat <= scrollRange) {
scrollRange = verticalScrollFactorCompat;
}
if (scrollRange == scrollY) {
return false;
}
super.scrollTo(getScrollX(), scrollRange);
return true;
default:
return false;
}
}
public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
boolean z = false;
int action = motionEvent.getAction();
if (action == 2 && this.f493j) {
return true;
}
switch (action & 255) {
case C0243l.View_android_theme /*0*/:
action = (int) motionEvent.getY();
if (!m1372c((int) motionEvent.getX(), action)) {
this.f493j = false;
m1374e();
break;
}
this.f489f = action;
this.f500q = az.m898b(motionEvent, 0);
m1371c();
this.f494k.addMovement(motionEvent);
this.f486c.m1478f();
if (!this.f486c.m1472a()) {
z = true;
}
this.f493j = z;
startNestedScroll(2);
break;
case C0243l.View_android_focusable /*1*/:
case C0243l.View_paddingEnd /*3*/:
this.f493j = false;
this.f500q = -1;
m1374e();
if (this.f486c.m1473a(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
bu.m990b(this);
}
stopNestedScroll();
break;
case C0243l.View_paddingStart /*2*/:
action = this.f500q;
if (action != -1) {
int a = az.m896a(motionEvent, action);
if (a != -1) {
action = (int) az.m901d(motionEvent, a);
if (Math.abs(action - this.f489f) > this.f497n && (getNestedScrollAxes() & 2) == 0) {
this.f493j = true;
this.f489f = action;
m1373d();
this.f494k.addMovement(motionEvent);
this.f503t = 0;
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
break;
}
}
}
Log.e("NestedScrollView", "Invalid pointerId=" + action + " in onInterceptTouchEvent");
break;
}
break;
case C0243l.Toolbar_contentInsetEnd /*6*/:
m1362a(motionEvent);
break;
}
return this.f493j;
}
protected void onLayout(boolean z, int i, int i2, int i3, int i4) {
super.onLayout(z, i, i2, i3, i4);
this.f490g = false;
if (this.f492i != null && m1367a(this.f492i, (View) this)) {
m1369b(this.f492i);
}
this.f492i = null;
if (!this.f491h) {
if (this.f504u != null) {
scrollTo(getScrollX(), this.f504u.f526a);
this.f504u = null;
}
int max = Math.max(0, (getChildCount() > 0 ? getChildAt(0).getMeasuredHeight() : 0) - (((i4 - i2) - getPaddingBottom()) - getPaddingTop()));
if (getScrollY() > max) {
scrollTo(getScrollX(), max);
} else if (getScrollY() < 0) {
scrollTo(getScrollX(), 0);
}
}
scrollTo(getScrollX(), getScrollY());
this.f491h = true;
}
protected void onMeasure(int i, int i2) {
super.onMeasure(i, i2);
if (this.f495l && MeasureSpec.getMode(i2) != 0 && getChildCount() > 0) {
View childAt = getChildAt(0);
int measuredHeight = getMeasuredHeight();
if (childAt.getMeasuredHeight() < measuredHeight) {
childAt.measure(getChildMeasureSpec(i, getPaddingLeft() + getPaddingRight(), ((FrameLayout.LayoutParams) childAt.getLayoutParams()).width), MeasureSpec.makeMeasureSpec((measuredHeight - getPaddingTop()) - getPaddingBottom(), 1073741824));
}
}
}
public boolean onNestedFling(View view, float f, float f2, boolean z) {
if (z) {
return false;
}
m1377f((int) f2);
return true;
}
public boolean onNestedPreFling(View view, float f, float f2) {
return dispatchNestedPreFling(f, f2);
}
public void onNestedPreScroll(View view, int i, int i2, int[] iArr) {
dispatchNestedPreScroll(i, i2, iArr, null);
}
public void onNestedScroll(View view, int i, int i2, int i3, int i4) {
int scrollY = getScrollY();
scrollBy(0, i4);
int scrollY2 = getScrollY() - scrollY;
dispatchNestedScroll(0, scrollY2, 0, i4 - scrollY2, null);
}
public void onNestedScrollAccepted(View view, View view2, int i) {
this.f505x.m969a(view, view2, i);
startNestedScroll(2);
}
protected void onOverScrolled(int i, int i2, boolean z, boolean z2) {
super.scrollTo(i, i2);
}
protected boolean onRequestFocusInDescendants(int i, Rect rect) {
if (i == 2) {
i = 130;
} else if (i == 1) {
i = 33;
}
View findNextFocus = rect == null ? FocusFinder.getInstance().findNextFocus(this, null, i) : FocusFinder.getInstance().findNextFocusFromRect(this, rect, i);
return (findNextFocus == null || m1365a(findNextFocus)) ? false : findNextFocus.requestFocus(i, rect);
}
protected void onRestoreInstanceState(Parcelable parcelable) {
if (parcelable instanceof af) {
af afVar = (af) parcelable;
super.onRestoreInstanceState(afVar.getSuperState());
this.f504u = afVar;
requestLayout();
return;
}
super.onRestoreInstanceState(parcelable);
}
protected Parcelable onSaveInstanceState() {
Parcelable afVar = new af(super.onSaveInstanceState());
afVar.f526a = getScrollY();
return afVar;
}
protected void onScrollChanged(int i, int i2, int i3, int i4) {
super.onScrollChanged(i, i2, i3, i4);
if (this.f483A != null) {
this.f483A.m1429a(this, i, i2, i3, i4);
}
}
protected void onSizeChanged(int i, int i2, int i3, int i4) {
super.onSizeChanged(i, i2, i3, i4);
View findFocus = findFocus();
if (findFocus != null && this != findFocus && m1366a(findFocus, 0, i4)) {
findFocus.getDrawingRect(this.f485b);
offsetDescendantRectToMyCoords(findFocus, this.f485b);
m1375e(m1379a(this.f485b));
}
}
public boolean onStartNestedScroll(View view, View view2, int i) {
return (i & 2) != 0;
}
public void onStopNestedScroll(View view) {
this.f505x.m968a(view);
stopNestedScroll();
}
public boolean onTouchEvent(MotionEvent motionEvent) {
m1373d();
MotionEvent obtain = MotionEvent.obtain(motionEvent);
int a = az.m895a(motionEvent);
if (a == 0) {
this.f503t = 0;
}
obtain.offsetLocation(0.0f, (float) this.f503t);
switch (a) {
case C0243l.View_android_theme /*0*/:
if (getChildCount() != 0) {
boolean z = !this.f486c.m1472a();
this.f493j = z;
if (z) {
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
if (!this.f486c.m1472a()) {
this.f486c.m1479g();
}
this.f489f = (int) motionEvent.getY();
this.f500q = az.m898b(motionEvent, 0);
startNestedScroll(2);
break;
}
return false;
case C0243l.View_android_focusable /*1*/:
if (this.f493j) {
VelocityTracker velocityTracker = this.f494k;
velocityTracker.computeCurrentVelocity(1000, (float) this.f499p);
a = (int) bp.m971a(velocityTracker, this.f500q);
if (Math.abs(a) > this.f498o) {
m1377f(-a);
} else if (this.f486c.m1473a(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
bu.m990b(this);
}
}
this.f500q = -1;
m1376f();
break;
case C0243l.View_paddingStart /*2*/:
int a2 = az.m896a(motionEvent, this.f500q);
if (a2 != -1) {
int i;
int d = (int) az.m901d(motionEvent, a2);
a = this.f489f - d;
if (dispatchNestedPreScroll(0, a, this.f502s, this.f501r)) {
a -= this.f502s[1];
obtain.offsetLocation(0.0f, (float) this.f501r[1]);
this.f503t += this.f501r[1];
}
if (this.f493j || Math.abs(a) <= this.f497n) {
i = a;
} else {
ViewParent parent2 = getParent();
if (parent2 != null) {
parent2.requestDisallowInterceptTouchEvent(true);
}
this.f493j = true;
i = a > 0 ? a - this.f497n : a + this.f497n;
}
if (this.f493j) {
this.f489f = d - this.f501r[1];
int scrollY = getScrollY();
int scrollRange = getScrollRange();
a = bu.m977a(this);
Object obj = (a == 0 || (a == 1 && scrollRange > 0)) ? 1 : null;
if (m1382a(0, i, 0, getScrollY(), 0, scrollRange, 0, 0, true) && !hasNestedScrollingParent()) {
this.f494k.clear();
}
int scrollY2 = getScrollY() - scrollY;
if (!dispatchNestedScroll(0, scrollY2, 0, i - scrollY2, this.f501r)) {
if (obj != null) {
m1378g();
a = scrollY + i;
if (a < 0) {
this.f487d.m1562a(((float) i) / ((float) getHeight()), az.m899c(motionEvent, a2) / ((float) getWidth()));
if (!this.f488e.m1561a()) {
this.f488e.m1565b();
}
} else if (a > scrollRange) {
this.f488e.m1562a(((float) i) / ((float) getHeight()), 1.0f - (az.m899c(motionEvent, a2) / ((float) getWidth())));
if (!this.f487d.m1561a()) {
this.f487d.m1565b();
}
}
if (!(this.f487d == null || (this.f487d.m1561a() && this.f488e.m1561a()))) {
bu.m990b(this);
break;
}
}
}
this.f489f -= this.f501r[1];
obtain.offsetLocation(0.0f, (float) this.f501r[1]);
this.f503t += this.f501r[1];
break;
}
}
Log.e("NestedScrollView", "Invalid pointerId=" + this.f500q + " in onTouchEvent");
break;
break;
case C0243l.View_paddingEnd /*3*/:
if (this.f493j && getChildCount() > 0 && this.f486c.m1473a(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
bu.m990b(this);
}
this.f500q = -1;
m1376f();
break;
case C0243l.Toolbar_contentInsetStart /*5*/:
a = az.m897b(motionEvent);
this.f489f = (int) az.m901d(motionEvent, a);
this.f500q = az.m898b(motionEvent, a);
break;
case C0243l.Toolbar_contentInsetEnd /*6*/:
m1362a(motionEvent);
this.f489f = (int) az.m901d(motionEvent, az.m896a(motionEvent, this.f500q));
break;
}
if (this.f494k != null) {
this.f494k.addMovement(obtain);
}
obtain.recycle();
return true;
}
public void requestChildFocus(View view, View view2) {
if (this.f490g) {
this.f492i = view2;
} else {
m1369b(view2);
}
super.requestChildFocus(view, view2);
}
public boolean requestChildRectangleOnScreen(View view, Rect rect, boolean z) {
rect.offset(view.getLeft() - view.getScrollX(), view.getTop() - view.getScrollY());
return m1364a(rect, z);
}
public void requestDisallowInterceptTouchEvent(boolean z) {
if (z) {
m1374e();
}
super.requestDisallowInterceptTouchEvent(z);
}
public void requestLayout() {
this.f490g = true;
super.requestLayout();
}
public void scrollTo(int i, int i2) {
if (getChildCount() > 0) {
View childAt = getChildAt(0);
int b = m1368b(i, (getWidth() - getPaddingRight()) - getPaddingLeft(), childAt.getWidth());
int b2 = m1368b(i2, (getHeight() - getPaddingBottom()) - getPaddingTop(), childAt.getHeight());
if (b != getScrollX() || b2 != getScrollY()) {
super.scrollTo(b, b2);
}
}
}
public void setFillViewport(boolean z) {
if (z != this.f495l) {
this.f495l = z;
requestLayout();
}
}
public void setNestedScrollingEnabled(boolean z) {
this.f506y.m958a(z);
}
public void setOnScrollChangeListener(ae aeVar) {
this.f483A = aeVar;
}
public void setSmoothScrollingEnabled(boolean z) {
this.f496m = z;
}
public boolean shouldDelayChildPressedState() {
return true;
}
public boolean startNestedScroll(int i) {
return this.f506y.m962a(i);
}
public void stopNestedScroll() {
this.f506y.m966c();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.