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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9230a4c5fae098bc3202f92f7b98a51f191e643f | 2,045 | java | Java | src/main/java/com/sparrow/ioc/EasyIoc.java | kentchenjh/sparrow | 263ec239d9d799ba61f330bae239d6a3b8480a14 | [
"MIT"
] | 1 | 2018-03-10T03:49:27.000Z | 2018-03-10T03:49:27.000Z | src/main/java/com/sparrow/ioc/EasyIoc.java | kentchenjh/sparrow | 263ec239d9d799ba61f330bae239d6a3b8480a14 | [
"MIT"
] | null | null | null | src/main/java/com/sparrow/ioc/EasyIoc.java | kentchenjh/sparrow | 263ec239d9d799ba61f330bae239d6a3b8480a14 | [
"MIT"
] | null | null | null | 22.472527 | 66 | 0.689976 | 995,550 | package com.sparrow.ioc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.sparrow.kit.CollectionKit;
import com.sparrow.kit.ReflectKit;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EasyIoc implements Ioc {
private final Map<String, ClassInfo> container = new HashMap<>();
@Override
public <T> T getBean(String name) {
ClassInfo clazz = container.get(name);
if(null == clazz) return null;
Object obj = clazz.getInstance();
if(null == obj) {
obj = ReflectKit.instance(clazz.getClazz());
if(null == obj) return null;
clazz.setInstance(obj);
}
return (T) obj;
}
@Override
public void addBean(String name, Object bean) {
ClassInfo clzInfo = new ClassInfo(bean);
addBean(name, clzInfo);
}
@Override
public void addBean(ClassInfo clazzInfo) {
addBean(clazzInfo.getClazz().getName(), clazzInfo);
}
private void initBean(ClassInfo clazzInfo) {
if(clazzInfo.getInstance() == null) {
Object instance = ReflectKit.instance(clazzInfo.getClazz());
clazzInfo.setInstance(instance);
}
}
@Override
public void addBean(String name, ClassInfo clazzInfo) {
initBean(clazzInfo);
if(null != container.put(name, clazzInfo)){
log.warn("duplicate bean: {}", clazzInfo.getClazz());
};
}
@Override
public List<ClassInfo> getClassInfos() {
return new ArrayList<>(container.values());
}
@Override
public List<Object> getBeans() {
return container.values().stream()
.map(ClassInfo::getInstance)
.collect(Collectors.toList());
}
/**
* get the bean which implements the
* specfic interface
* @param type
* @return the bean found first
*/
public <T> T getBeanByInterface(Class<?> type) {
@SuppressWarnings("unchecked")
T[] beans = (T[]) container.values().stream()
.filter(ci -> ReflectKit.hasInterface(ci.getClazz(), type))
.map(ci -> ci.getInstance())
.toArray();
return CollectionKit.isEmpty(beans) ? null : beans[0];
}
}
|
9230a4d5a6802805f122ee9ddecf8c14d5e3994a | 180 | java | Java | linkis-computation-governance/linkis-manager/linkis-manager-commons/linkis-manager-common/src/main/java/com/webank/wedatasphere/linkis/manager/common/protocol/node/StopNodeRequest.java | xiejiajun/Linkis | 446069f8e14e22a3b6756b0ddbf0601cc37be594 | [
"Apache-2.0"
] | 2 | 2021-07-05T07:43:51.000Z | 2021-07-05T07:43:53.000Z | linkis-computation-governance/linkis-manager/linkis-manager-commons/linkis-manager-common/src/main/java/com/webank/wedatasphere/linkis/manager/common/protocol/node/StopNodeRequest.java | xiejiajun/Linkis | 446069f8e14e22a3b6756b0ddbf0601cc37be594 | [
"Apache-2.0"
] | null | null | null | linkis-computation-governance/linkis-manager/linkis-manager-commons/linkis-manager-common/src/main/java/com/webank/wedatasphere/linkis/manager/common/protocol/node/StopNodeRequest.java | xiejiajun/Linkis | 446069f8e14e22a3b6756b0ddbf0601cc37be594 | [
"Apache-2.0"
] | null | null | null | 25.714286 | 68 | 0.811111 | 995,551 | package com.webank.wedatasphere.linkis.manager.common.protocol.node;
public class StopNodeRequest implements NodeRequestProtocol {
private String name = "StopNodeRequest";
}
|
9230a643f4c5c32fd2b02a83e106b9c5a22d45ee | 209 | java | Java | hidden-api-common-bridge/src/main/java/hidden/UserInfoCompat.java | wtf74520/suizuku | 45eaebcc81c9b12a67997a5a7a828171dc5c83f1 | [
"Apache-2.0"
] | 2 | 2021-08-13T01:08:06.000Z | 2022-01-14T01:26:34.000Z | hidden-api-common-bridge/src/main/java/hidden/UserInfoCompat.java | LSPosed/Shizuku | 917e2b6308cf2811db1e3ad592b0e3e22c5d8503 | [
"Apache-2.0"
] | null | null | null | hidden-api-common-bridge/src/main/java/hidden/UserInfoCompat.java | LSPosed/Shizuku | 917e2b6308cf2811db1e3ad592b0e3e22c5d8503 | [
"Apache-2.0"
] | null | null | null | 16.076923 | 48 | 0.62201 | 995,552 | package hidden;
public class UserInfoCompat {
public final int id;
public final String name;
public UserInfoCompat(int id, String name) {
this.id = id;
this.name = name;
}
}
|
9230a6a62956634247a6da14d502689fafdb2072 | 1,916 | java | Java | org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | 1 | 2022-02-24T01:32:41.000Z | 2022-02-24T01:32:41.000Z | org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | 30.412698 | 132 | 0.717119 | 995,553 | package org.apache.fop.render.afp.extensions;
import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.FONode;
import org.apache.fop.fo.PropertyList;
import org.apache.fop.fo.ValidationException;
import org.apache.fop.fo.extensions.ExtensionAttachment;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
public abstract class AbstractAFPExtensionObject extends FONode {
protected AFPExtensionAttachment extensionAttachment;
protected String name;
public AbstractAFPExtensionObject(FONode parent, String name) {
super(parent);
this.name = name;
}
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException {
if ("http://www.w3.org/1999/XSL/Format".equals(nsURI)) {
this.invalidChildError(loc, nsURI, localName);
}
}
public String getNamespaceURI() {
return "http://xmlgraphics.apache.org/fop/extensions/afp";
}
public String getNormalNamespacePrefix() {
return "afp";
}
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException {
this.getExtensionAttachment();
String attr = attlist.getValue("name");
if (attr != null && attr.length() > 0) {
this.extensionAttachment.setName(attr);
} else {
throw new FOPException(elementName + " must have a name attribute.");
}
}
protected void endOfNode() throws FOPException {
super.endOfNode();
}
protected abstract ExtensionAttachment instantiateExtensionAttachment();
public ExtensionAttachment getExtensionAttachment() {
if (this.extensionAttachment == null) {
this.extensionAttachment = (AFPExtensionAttachment)this.instantiateExtensionAttachment();
}
return this.extensionAttachment;
}
public String getLocalName() {
return this.name;
}
}
|
9230a6f88ddbb67e6cd24e237a3a07b66ff334c6 | 446 | java | Java | hurriyetopensourcesdk/src/main/java/tr/com/hurriyet/opensourcesdk/extraparams/selectparams/ArticleDetailSelectParams.java | hurriyet/hurriyet-public-api-android-sdk | 19519e35e2a4255958e53a43497a246359dd6f8a | [
"MIT"
] | 2 | 2016-12-23T16:17:32.000Z | 2017-10-31T15:40:31.000Z | hurriyetopensourcesdk/src/main/java/tr/com/hurriyet/opensourcesdk/extraparams/selectparams/ArticleDetailSelectParams.java | hurriyet/hurriyet-public-api-android-sdk | 19519e35e2a4255958e53a43497a246359dd6f8a | [
"MIT"
] | null | null | null | hurriyetopensourcesdk/src/main/java/tr/com/hurriyet/opensourcesdk/extraparams/selectparams/ArticleDetailSelectParams.java | hurriyet/hurriyet-public-api-android-sdk | 19519e35e2a4255958e53a43497a246359dd6f8a | [
"MIT"
] | null | null | null | 29.733333 | 84 | 0.802691 | 995,554 | package tr.com.hurriyet.opensourcesdk.extraparams.selectparams;
import tr.com.hurriyet.opensourcesdk.extraparams.SelectParamsBase;
import tr.com.hurriyet.opensourcesdk.extraparams.selectenum.ArticleDetailSelectEnum;
/**
* Created by KOZMOS on 12/22/2016.
*/
public class ArticleDetailSelectParams extends SelectParamsBase {
public ArticleDetailSelectParams(ArticleDetailSelectEnum... selectParams) {
super(selectParams);
}
}
|
9230a708f271ea235b4c6a125cd2e555b58f8dc6 | 3,123 | java | Java | doc/jitsi-bundles-dex/sources/org/jivesoftware/smackx/workgroup/ext/notes/ChatNotes.java | lhzheng880828/VOIPCall | a7ba25debd4bd2086bae2a48306d28c614ce0d4a | [
"Apache-2.0"
] | null | null | null | doc/jitsi-bundles-dex/sources/org/jivesoftware/smackx/workgroup/ext/notes/ChatNotes.java | lhzheng880828/VOIPCall | a7ba25debd4bd2086bae2a48306d28c614ce0d4a | [
"Apache-2.0"
] | null | null | null | doc/jitsi-bundles-dex/sources/org/jivesoftware/smackx/workgroup/ext/notes/ChatNotes.java | lhzheng880828/VOIPCall | a7ba25debd4bd2086bae2a48306d28c614ce0d4a | [
"Apache-2.0"
] | null | null | null | 34.7 | 149 | 0.563561 | 995,555 | package org.jivesoftware.smackx.workgroup.ext.notes;
import org.jitsi.gov.nist.core.Separators;
import org.jitsi.org.xmlpull.v1.XmlPullParser;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider;
public class ChatNotes extends IQ {
public static final String ELEMENT_NAME = "chat-notes";
public static final String NAMESPACE = "http://jivesoftware.com/protocol/workgroup";
private String notes;
private String sessionID;
public static class Provider implements IQProvider {
public IQ parseIQ(XmlPullParser parser) throws Exception {
ChatNotes chatNotes = new ChatNotes();
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == 2) {
if (parser.getName().equals("sessionID")) {
chatNotes.setSessionID(parser.nextText());
} else if (parser.getName().equals("text")) {
chatNotes.setNotes(parser.nextText().replaceAll("\\\\n", Separators.RETURN));
}
} else if (eventType == 3 && parser.getName().equals(ChatNotes.ELEMENT_NAME)) {
done = true;
}
}
return chatNotes;
}
}
public String getSessionID() {
return this.sessionID;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getChildElementXML() {
StringBuilder buf = new StringBuilder();
buf.append(Separators.LESS_THAN).append(ELEMENT_NAME).append(" xmlns=\"").append("http://jivesoftware.com/protocol/workgroup").append("\">");
buf.append("<sessionID>").append(getSessionID()).append("</sessionID>");
if (getNotes() != null) {
buf.append("<notes>").append(getNotes()).append("</notes>");
}
buf.append("</").append(ELEMENT_NAME).append("> ");
return buf.toString();
}
public static final String replace(String string, String oldString, String newString) {
if (string == null) {
return null;
}
if (newString == null) {
return string;
}
int i = string.indexOf(oldString, 0);
if (i < 0) {
return string;
}
char[] string2 = string.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuilder buf = new StringBuilder(string2.length);
buf.append(string2, 0, i).append(newString2);
while (true) {
i += oLength;
int j = i;
i = string.indexOf(oldString, i);
if (i > 0) {
buf.append(string2, j, i - j).append(newString2);
} else {
buf.append(string2, j, string2.length - j);
return buf.toString();
}
}
}
}
|
9230a726504c47d435e05d9547fd2744ad329775 | 2,806 | java | Java | unitils-test/src/test/java/org/unitils/dbunit/dataset/comparison/RowDifferenceIsBetterMatchTest.java | Silvermedia/unitils | ed11af302a968b7a9f5666911160139f8994c2d7 | [
"Apache-2.0"
] | null | null | null | unitils-test/src/test/java/org/unitils/dbunit/dataset/comparison/RowDifferenceIsBetterMatchTest.java | Silvermedia/unitils | ed11af302a968b7a9f5666911160139f8994c2d7 | [
"Apache-2.0"
] | null | null | null | unitils-test/src/test/java/org/unitils/dbunit/dataset/comparison/RowDifferenceIsBetterMatchTest.java | Silvermedia/unitils | ed11af302a968b7a9f5666911160139f8994c2d7 | [
"Apache-2.0"
] | null | null | null | 30.835165 | 71 | 0.699216 | 995,556 | package org.unitils.dbunit.dataset.comparison;
import org.junit.Before;
import org.junit.Test;
import org.unitils.dbunit.dataset.Column;
import static org.dbunit.dataset.datatype.DataType.VARCHAR;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Tim Ducheyne
*/
public class RowDifferenceIsBetterMatchTest {
/* Tested object */
private RowDifference rowDifference1;
private RowDifference rowDifference2;
private Column column;
private ColumnDifference columnDifference;
@Before
public void initialize() {
column = new Column("column", VARCHAR, "1");
columnDifference = new ColumnDifference(null, null);
rowDifference1 = new RowDifference(null, null);
rowDifference2 = new RowDifference(null, null);
}
@Test
public void trueWhenLessMissingColumns() {
rowDifference1.addMissingColumn(column);
rowDifference2.addMissingColumn(column);
rowDifference2.addMissingColumn(column);
boolean result = rowDifference1.isBetterMatch(rowDifference2);
assertTrue(result);
}
@Test
public void falseWhenMoreMissingColumns() {
rowDifference1.addMissingColumn(column);
rowDifference1.addMissingColumn(column);
rowDifference2.addMissingColumn(column);
boolean result = rowDifference1.isBetterMatch(rowDifference2);
assertFalse(result);
}
@Test
public void trueWhenLessColumnDifferences() {
rowDifference1.addColumnDifference(columnDifference);
rowDifference2.addColumnDifference(columnDifference);
rowDifference2.addColumnDifference(columnDifference);
boolean result = rowDifference1.isBetterMatch(rowDifference2);
assertTrue(result);
}
@Test
public void falseWhenMoreColumnDifferences() {
rowDifference1.addColumnDifference(columnDifference);
rowDifference1.addColumnDifference(columnDifference);
rowDifference2.addColumnDifference(columnDifference);
boolean result = rowDifference1.isBetterMatch(rowDifference2);
assertFalse(result);
}
@Test
public void falseWhenEqualDifferences() {
rowDifference1.addMissingColumn(column);
rowDifference1.addColumnDifference(columnDifference);
rowDifference2.addMissingColumn(column);
rowDifference2.addColumnDifference(columnDifference);
boolean result = rowDifference1.isBetterMatch(rowDifference2);
assertFalse(result);
}
@Test
public void falseWhenBothHaveNoDifferences() {
boolean result = rowDifference1.isBetterMatch(rowDifference2);
assertFalse(result);
}
}
|
9230a757db256c1e71db6f565b310f296851eab5 | 1,458 | java | Java | src/training/math/E119_Easy_PascalTriangleII.java | taowu750/LeetCodeJourney | ae4aba3fbf79cb462f9839a521c6930a8ef5542f | [
"MIT"
] | null | null | null | src/training/math/E119_Easy_PascalTriangleII.java | taowu750/LeetCodeJourney | ae4aba3fbf79cb462f9839a521c6930a8ef5542f | [
"MIT"
] | null | null | null | src/training/math/E119_Easy_PascalTriangleII.java | taowu750/LeetCodeJourney | ae4aba3fbf79cb462f9839a521c6930a8ef5542f | [
"MIT"
] | null | null | null | 21.441176 | 87 | 0.570645 | 995,557 | package training.math;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.function.IntFunction;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* 给定整数 rowIndex,返回帕斯卡三角形(杨辉三角)的第 rowIndex(以 0 开头)行。
* 你能找到仅使用 O(rowIndex) 额外空间的实现吗?
*
* 例 1:
* Input: rowIndex = 3
* Output: [1,3,3,1]
* Explanation:
* 1
* 1 1
* 1 2 1
* → 1 3 3 1
*
* 例 2:
* Input: rowIndex = 0
* Output: [1]
*
* 例 3:
* Input: rowIndex = 1
* Output: [1,1]
*
* 约束:
* - 0 <= rowIndex <= 33
*/
public class E119_Easy_PascalTriangleII {
static void test(IntFunction<List<Integer>> method) {
assertEquals(method.apply(3), asList(1, 3, 3, 1));
assertEquals(method.apply(0), singletonList(1));
assertEquals(method.apply(1), asList(1, 1));
assertEquals(method.apply(4), asList(1, 4, 6, 4, 1));
}
/**
* LeetCode 耗时:0ms - 100%
*/
public List<Integer> getRow(int rowIndex) {
Integer[] row = new Integer[rowIndex + 1];
row[0] = 1;
for (int i = 1; i <= rowIndex; i++) {
for (int j = i; j >= 0; j--)
row[j] = (row[j] != null ? row[j] : 0) + (j - 1 >= 0 ? row[j - 1] : 0);
}
return Arrays.asList(row);
}
@Test
public void testGetRow() {
test(this::getRow);
}
}
|
9230a79bdeb8d8470f52dc046aa1ce1f85a94b5a | 672 | java | Java | src/main/java/mu/semte/ch/lib/dto/Delta.java | lblod/mu-java | 42f9150f727a069820e71fabcea81fa91d474b71 | [
"MIT"
] | null | null | null | src/main/java/mu/semte/ch/lib/dto/Delta.java | lblod/mu-java | 42f9150f727a069820e71fabcea81fa91d474b71 | [
"MIT"
] | 6 | 2021-04-28T08:39:36.000Z | 2021-12-12T17:38:52.000Z | src/main/java/mu/semte/ch/lib/dto/Delta.java | lblod/mu-java | 42f9150f727a069820e71fabcea81fa91d474b71 | [
"MIT"
] | null | null | null | 24 | 114 | 0.702381 | 995,558 | package mu.semte.ch.lib.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.stream.Collectors;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Delta {
private List<Triple> inserts;
private List<Triple> deletes;
public List<String> getInsertsFor(String predicate, String object) {
return this.inserts
.stream()
.filter(t -> predicate.equals(t.getPredicate().getValue()) && object.equals(t.getObject().getValue()))
.map(t -> t.getSubject().getValue())
.collect(Collectors.toList());
}
}
|
9230a87ad63fd0461fe7e28faa18ff6238910b87 | 330 | java | Java | Denial_Apps/SpringTutorials/src/main/java/com/spring/tutorial/SpringTutorials/personAPI/database/PersonDatabase.java | Dalemu2/TeamUpleftedApps | b522844017fa03031b7e2f61a1973fa772a3a064 | [
"MIT"
] | null | null | null | Denial_Apps/SpringTutorials/src/main/java/com/spring/tutorial/SpringTutorials/personAPI/database/PersonDatabase.java | Dalemu2/TeamUpleftedApps | b522844017fa03031b7e2f61a1973fa772a3a064 | [
"MIT"
] | null | null | null | Denial_Apps/SpringTutorials/src/main/java/com/spring/tutorial/SpringTutorials/personAPI/database/PersonDatabase.java | Dalemu2/TeamUpleftedApps | b522844017fa03031b7e2f61a1973fa772a3a064 | [
"MIT"
] | null | null | null | 30 | 69 | 0.851515 | 995,559 | package com.spring.tutorial.SpringTutorials.personAPI.database;
import com.spring.tutorial.SpringTutorials.personAPI.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonDatabase extends JpaRepository<Person, Long> {
}
|
9230a893d8f99e975ec367f6f67670f752e28994 | 755 | java | Java | yoo-domain-master-1d29d9118d5aefde5f17648046c36cbb0cbb7d1b/domain-common/src/main/java/com/lanking/cloud/domain/common/baseData/ExaminationPointFrequency.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | 1 | 2019-01-20T06:19:53.000Z | 2019-01-20T06:19:53.000Z | yoo-domain-master-1d29d9118d5aefde5f17648046c36cbb0cbb7d1b/domain-common/src/main/java/com/lanking/cloud/domain/common/baseData/ExaminationPointFrequency.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | null | null | null | yoo-domain-master-1d29d9118d5aefde5f17648046c36cbb0cbb7d1b/domain-common/src/main/java/com/lanking/cloud/domain/common/baseData/ExaminationPointFrequency.java | wangsikai/learn | af85f7c7db5c38b5009ebdfb8c8985032eca565c | [
"Apache-2.0"
] | 2 | 2019-01-20T06:19:54.000Z | 2021-07-21T14:13:44.000Z | 15.530612 | 67 | 0.605782 | 995,560 | package com.lanking.cloud.domain.common.baseData;
import com.lanking.cloud.sdk.bean.Valueable;
/**
* 考点频率
*
* @since 3.9.3
* @author <a href="mailto:hzdkv@example.com">sikai.wang</a>
* @version 2017年3月20日
*/
public enum ExaminationPointFrequency implements Valueable {
/**
* 高频
*/
HIGH(0),
/**
* 一般(低频)
*/
LOW(1),
/**
* 核心
*/
CORE(2);
private final int value;
private ExaminationPointFrequency(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static ExaminationPointFrequency findByValue(int value) {
switch (value) {
case 0:
return HIGH;
case 1:
return LOW;
case 2:
return CORE;
default:
return null;
}
}
}
|
9230a8bd393b09496c8462c3a95920e5cdd9b293 | 1,490 | java | Java | jaggery/org.eclipse.php.core/src/org/eclipse/php/internal/core/codeassist/contexts/UseAliasContext.java | knadikari/developer-studio | ed8b9e397bcf79e538c0f63397b3a8d8d7827660 | [
"Apache-2.0"
] | null | null | null | jaggery/org.eclipse.php.core/src/org/eclipse/php/internal/core/codeassist/contexts/UseAliasContext.java | knadikari/developer-studio | ed8b9e397bcf79e538c0f63397b3a8d8d7827660 | [
"Apache-2.0"
] | null | null | null | jaggery/org.eclipse.php.core/src/org/eclipse/php/internal/core/codeassist/contexts/UseAliasContext.java | knadikari/developer-studio | ed8b9e397bcf79e538c0f63397b3a8d8d7827660 | [
"Apache-2.0"
] | 1 | 2018-10-26T12:52:03.000Z | 2018-10-26T12:52:03.000Z | 29.215686 | 81 | 0.641611 | 995,561 | /*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Zend Technologies
*******************************************************************************/
package org.eclipse.php.internal.core.codeassist.contexts;
import org.eclipse.dltk.core.CompletionRequestor;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.php.internal.core.PHPCorePlugin;
/**
* This context represents the state when staying in a use statement in a alias
* part. <br/>
* Examples:
*
* <pre>
* 1. use A as |
* 2. use A as B|
* etc...
* </pre>
*
* @author michael
*/
public class UseAliasContext extends UseStatementContext {
public boolean isValid(ISourceModule sourceModule, int offset,
CompletionRequestor requestor) {
if (!super.isValid(sourceModule, offset, requestor)) {
return false;
}
try {
String previousWord = getPreviousWord();
if ("as".equalsIgnoreCase(previousWord)) { //$NON-NLS-1$
return true;
}
} catch (BadLocationException e) {
PHPCorePlugin.log(e);
}
return false;
}
}
|
9230a9052be319d1833fc27a5d7c12b02179333a | 2,679 | java | Java | src/main/java/servlets/ProductServlet.java | demetkochan/Java-Hibernate-MySql-Application---Depo-Project | d9c6d8ed87736358fac7c9bb0b76722160255a0b | [
"MIT"
] | 1 | 2021-10-07T13:12:05.000Z | 2021-10-07T13:12:05.000Z | src/main/java/servlets/ProductServlet.java | demetkochan/Java-Hibernate-MySql-Application---Depo-Project | d9c6d8ed87736358fac7c9bb0b76722160255a0b | [
"MIT"
] | null | null | null | src/main/java/servlets/ProductServlet.java | demetkochan/Java-Hibernate-MySql-Application---Depo-Project | d9c6d8ed87736358fac7c9bb0b76722160255a0b | [
"MIT"
] | null | null | null | 29.766667 | 116 | 0.639044 | 995,562 | package servlets;
import com.google.gson.Gson;
import entities.Customer;
import entities.Product;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet(name = "productServlet", value = { "/product-post", "/product-delete", "/product-get" })
public class ProductServlet extends HttpServlet {
SessionFactory sf = HibernateUtil.getSessionFactory();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int pid = 0;
Session sesi = sf.openSession();
Transaction tr = sesi.beginTransaction();
try{
String obj = req.getParameter("obj");
Gson gson = new Gson();
Product product = gson.fromJson(obj, Product.class);
sesi.saveOrUpdate(product);
tr.commit();
sesi.close();
pid = 1;
}catch (Exception ex){
System.err.println("Save OR Update Error : " + ex);
}finally {
sesi.close();
}
resp.setContentType("application/json");
resp.getWriter().write( "" +pid );
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Gson gson = new Gson();
Session sesi = sf.openSession();
List<Product> ls = sesi.createQuery("from Product ").getResultList();
sesi.close();
String stJson = gson.toJson(ls);
resp.setContentType("application/json");
resp.getWriter().write( stJson );
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int return_id = 0;
Session sesi = sf.openSession();
Transaction tr = sesi.beginTransaction();
try {
int pro_id = Integer.parseInt( req.getParameter("pro_id") );
Product product = sesi.load(Product.class, pro_id);
sesi.delete(product);
tr.commit();
return_id = product.getPro_id();
}catch (Exception ex) {
System.err.println("Delete Error : " + ex);
}finally {
sesi.close();
}
resp.setContentType("application/json");
resp.getWriter().write( ""+return_id );
}
}
|
9230a9aa4eb180266a4a277aab3a4cad307f46d8 | 8,062 | java | Java | test/src/main/java/org/apache/accumulo/test/functional/BalanceInPresenceOfOfflineTableIT.java | reggert/accumulo | 6766d925ef258af88fc17cae07cbef6ce4dbec26 | [
"Apache-2.0"
] | 2 | 2021-06-02T14:31:16.000Z | 2021-07-23T12:54:41.000Z | test/src/main/java/org/apache/accumulo/test/functional/BalanceInPresenceOfOfflineTableIT.java | reggert/accumulo | 6766d925ef258af88fc17cae07cbef6ce4dbec26 | [
"Apache-2.0"
] | 1 | 2022-01-13T15:20:39.000Z | 2022-01-13T15:20:39.000Z | test/src/main/java/org/apache/accumulo/test/functional/BalanceInPresenceOfOfflineTableIT.java | reggert/accumulo | 6766d925ef258af88fc17cae07cbef6ce4dbec26 | [
"Apache-2.0"
] | 1 | 2021-06-14T14:49:08.000Z | 2021-06-14T14:49:08.000Z | 38.390476 | 100 | 0.719052 | 995,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.accumulo.test.functional;
import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.clientImpl.Credentials;
import org.apache.accumulo.core.clientImpl.MasterClient;
import org.apache.accumulo.core.clientImpl.thrift.ThriftNotActiveServiceException;
import org.apache.accumulo.core.clientImpl.thrift.ThriftSecurityException;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.master.thrift.MasterClientService;
import org.apache.accumulo.core.master.thrift.MasterMonitorInfo;
import org.apache.accumulo.core.master.thrift.TableInfo;
import org.apache.accumulo.core.trace.TraceUtil;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.accumulo.miniclusterImpl.MiniAccumuloConfigImpl;
import org.apache.accumulo.test.TestIngest;
import org.apache.accumulo.test.VerifyIngest;
import org.apache.accumulo.test.VerifyIngest.VerifyParams;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.thrift.TException;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Start a new table, create many splits, and offline before they can rebalance. Then try to have a
* different table balance
*/
public class BalanceInPresenceOfOfflineTableIT extends AccumuloClusterHarness {
private static Logger log = LoggerFactory.getLogger(BalanceInPresenceOfOfflineTableIT.class);
@Override
public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
Map<String,String> siteConfig = cfg.getSiteConfig();
siteConfig.put(Property.TSERV_MAXMEM.getKey(), "10K");
siteConfig.put(Property.TSERV_MAJC_DELAY.getKey(), "0");
cfg.setSiteConfig(siteConfig);
// ensure we have two tservers
if (cfg.getNumTservers() < 2) {
cfg.setNumTservers(2);
}
}
@Override
protected int defaultTimeoutSeconds() {
return 10 * 60;
}
private static final int NUM_SPLITS = 200;
private String UNUSED_TABLE, TEST_TABLE;
private AccumuloClient accumuloClient;
@Before
public void setupTables() throws AccumuloException, AccumuloSecurityException,
TableExistsException, TableNotFoundException {
accumuloClient = Accumulo.newClient().from(getClientProps()).build();
// Need at least two tservers
Assume.assumeTrue("Not enough tservers to run test",
accumuloClient.instanceOperations().getTabletServers().size() >= 2);
// set up splits
final SortedSet<Text> splits = new TreeSet<>();
for (int i = 0; i < NUM_SPLITS; i++) {
splits.add(new Text(String.format("%08x", i * 1000)));
}
String[] names = getUniqueNames(2);
UNUSED_TABLE = names[0];
TEST_TABLE = names[1];
// load into a table we won't use
accumuloClient.tableOperations().create(UNUSED_TABLE);
accumuloClient.tableOperations().addSplits(UNUSED_TABLE, splits);
// mark the table offline before it can rebalance.
accumuloClient.tableOperations().offline(UNUSED_TABLE);
// actual test table
accumuloClient.tableOperations().create(TEST_TABLE);
accumuloClient.tableOperations().setProperty(TEST_TABLE,
Property.TABLE_SPLIT_THRESHOLD.getKey(), "10K");
}
@After
public void closeClient() {
accumuloClient.close();
}
@Test
public void test() throws Exception {
log.info("Test that balancing is not stopped by an offline table with outstanding migrations.");
log.debug("starting test ingestion");
VerifyParams params = new VerifyParams(getClientProps(), TEST_TABLE, 200_000);
TestIngest.ingest(accumuloClient, params);
accumuloClient.tableOperations().flush(TEST_TABLE, null, null, true);
VerifyIngest.verifyIngest(accumuloClient, params);
log.debug("waiting for balancing, up to ~5 minutes to allow for migration cleanup.");
final long startTime = System.currentTimeMillis();
long currentWait = 10 * 1000;
boolean balancingWorked = false;
Credentials creds = new Credentials(getAdminPrincipal(), getAdminToken());
while (!balancingWorked && (System.currentTimeMillis() - startTime) < ((5 * 60 + 15) * 1000)) {
Thread.sleep(currentWait);
currentWait *= 2;
log.debug("fetch the list of tablets assigned to each tserver.");
MasterClientService.Iface client = null;
MasterMonitorInfo stats;
while (true) {
try {
client = MasterClient.getConnectionWithRetry((ClientContext) accumuloClient);
stats = client.getMasterStats(TraceUtil.traceInfo(),
creds.toThrift(accumuloClient.instanceOperations().getInstanceID()));
break;
} catch (ThriftSecurityException exception) {
throw new AccumuloSecurityException(exception);
} catch (ThriftNotActiveServiceException e) {
// Let it loop, fetching a new location
log.debug("Contacted a Master which is no longer active, retrying");
sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
} catch (TException exception) {
throw new AccumuloException(exception);
} finally {
if (client != null) {
MasterClient.close(client);
}
}
}
if (stats.getTServerInfoSize() < 2) {
log.debug("we need >= 2 servers. sleeping for {}ms", currentWait);
continue;
}
if (stats.getUnassignedTablets() != 0) {
log.debug("We shouldn't have unassigned tablets. sleeping for {}ms", currentWait);
continue;
}
long[] tabletsPerServer = new long[stats.getTServerInfoSize()];
Arrays.fill(tabletsPerServer, 0L);
for (int i = 0; i < stats.getTServerInfoSize(); i++) {
for (Map.Entry<String,TableInfo> entry : stats.getTServerInfo().get(i).getTableMap()
.entrySet()) {
tabletsPerServer[i] += entry.getValue().getTablets();
}
}
if (tabletsPerServer[0] <= 10) {
log.debug("We should have > 10 tablets. sleeping for {}ms", currentWait);
continue;
}
long min = NumberUtils.min(tabletsPerServer), max = NumberUtils.max(tabletsPerServer);
log.debug("Min={}, Max={}", min, max);
if ((min / ((double) max)) < 0.5) {
log.debug(
"ratio of min to max tablets per server should be roughly even. sleeping for {}ms",
currentWait);
continue;
}
balancingWorked = true;
}
assertTrue("did not properly balance", balancingWorked);
}
}
|
9230aca3b9c9796b94aef3ecbcb17432aa0437a3 | 3,940 | java | Java | app/src/main/java/com/time/cat/ui/modules/editor/fragment/EditorFragment.java | triline3/timecat | fdb54695c417366ca2c5e0978bae4ef856f74b74 | [
"Apache-2.0"
] | 71 | 2018-04-07T07:11:10.000Z | 2022-03-06T07:15:40.000Z | app/src/main/java/com/time/cat/ui/modules/editor/fragment/EditorFragment.java | 809593092/timecat | fdb54695c417366ca2c5e0978bae4ef856f74b74 | [
"Apache-2.0"
] | 4 | 2018-04-02T17:36:40.000Z | 2020-01-05T11:00:56.000Z | app/src/main/java/com/time/cat/ui/modules/editor/fragment/EditorFragment.java | 809593092/timecat | fdb54695c417366ca2c5e0978bae4ef856f74b74 | [
"Apache-2.0"
] | 25 | 2018-07-11T02:48:06.000Z | 2022-01-17T09:52:34.000Z | 32.03252 | 104 | 0.592893 | 995,564 | package com.time.cat.ui.modules.editor.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.time.cat.R;
import com.time.cat.data.Constants;
import com.time.cat.ui.modules.editor.EditorAction;
import com.time.cat.util.FileUtils;
import com.timecat.commonjar.contentProvider.SPHelper;
import org.greenrobot.eventbus.EventBus;
import butterknife.BindView;
public class EditorFragment extends BaseEditorFragment {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.editor_viewpager)
ViewPager editorViewPager;
@Override
public int getLayoutId() {
return R.layout.fragment_editor;
}
@Override
public void initView() {
getArgs();
super.initView();
toolbar.setTitle("");
context.setSupportActionBar(toolbar);
context.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setHasOptionsMenu(true);
setViewPager();
setViewPagerListener();
}
public void getArgs() {
Bundle args = getArguments();
if (args != null) {
fromFile = args.getBoolean(Constants.BUNDLE_KEY_FROM_FILE);
if (fromFile) {
saved = args.getBoolean(Constants.BUNDLE_KEY_SAVED);
fileName = args.getString(Constants.BUNDLE_KEY_FILE_NAME);
filePath = args.getString(Constants.BUNDLE_KEY_FILE_PATH);
if (filePath != null) {
fileContent = FileUtils.readContentFromPath(filePath, true);
}
} else {
fileContent = SPHelper.getString(Constants.UNIVERSAL_SAVE_COTENT, "");
}
}
}
public void setViewPager() {
final ScreenSlidePagerAdapter adapter = new ScreenSlidePagerAdapter(
getChildFragmentManager());
editorViewPager.setAdapter(adapter);
}
public void setViewPagerListener() {
editorViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
if (position == 1) {
EventBus.getDefault().post(true);
}
}
@Override
public void onPageScrollStateChanged(int state) {}
});
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 0) {
fragment = new EditFragment();
} else {
fragment = new PreviewFragment();
}
return fragment;
}
@Override
public int getCount() {
return 2;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
EditorAction editorAction = new EditorAction(context);
switch (item.getItemId()) {
case R.id.preview:
// switch to preview page
editorAction.toggleKeyboard(0);
editorViewPager.setCurrentItem(1, true);
break;
case R.id.edit:
// switch to edit page
editorViewPager.setCurrentItem(0, true);
break;
}
return super.onOptionsItemSelected(item);
}
}
|
9230acbbce0a083b0f88d7c8bae335948c965c8d | 1,250 | java | Java | ide/lexer/src/org/netbeans/api/lexer/TokenHierarchyListener.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | ide/lexer/src/org/netbeans/api/lexer/TokenHierarchyListener.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | ide/lexer/src/org/netbeans/api/lexer/TokenHierarchyListener.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 32.051282 | 73 | 0.7352 | 995,565 | /*
* 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.netbeans.api.lexer;
/**
* Listener for chagnes in the token hierarchy.
*
* @author Miloslav Metelka
* @version 1.00
*/
public interface TokenHierarchyListener extends java.util.EventListener {
/**
* Token hierarchy has changed in a way described by the event.
*
* @param evt event describing the change in the token hierarchy.
*/
public void tokenHierarchyChanged(TokenHierarchyEvent evt);
}
|
9230ad62b8f42eef8d50f6bacb7ae14bb244ade8 | 1,842 | java | Java | src/main/java/br/com/zup/eduardoribeiro/mercadolivre/treinomercadolivre/produto/opiniao/Opiniao.java | eduardorcury/orange-talents-03-template-ecommerce | b6893a76473c73ca0c1df8d1861df37f590262e5 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zup/eduardoribeiro/mercadolivre/treinomercadolivre/produto/opiniao/Opiniao.java | eduardorcury/orange-talents-03-template-ecommerce | b6893a76473c73ca0c1df8d1861df37f590262e5 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zup/eduardoribeiro/mercadolivre/treinomercadolivre/produto/opiniao/Opiniao.java | eduardorcury/orange-talents-03-template-ecommerce | b6893a76473c73ca0c1df8d1861df37f590262e5 | [
"Apache-2.0"
] | null | null | null | 24.236842 | 82 | 0.666124 | 995,566 | package br.com.zup.eduardoribeiro.mercadolivre.treinomercadolivre.produto.opiniao;
import br.com.zup.eduardoribeiro.mercadolivre.treinomercadolivre.produto.Produto;
import br.com.zup.eduardoribeiro.mercadolivre.treinomercadolivre.usuario.Usuario;
import org.hibernate.validator.constraints.Length;
import org.springframework.util.Assert;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "opinioes")
public class Opiniao {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Min(1)
@Max(5)
@Column(nullable = false)
private Integer nota;
@NotBlank
@Column(nullable = false)
private String titulo;
@NotBlank
@Length(max = 500)
@Column(nullable = false, length = 500)
private String descricao;
@NotNull
@ManyToOne(optional = false)
@Valid
private Produto produto;
@NotNull
@Valid
@ManyToOne(optional = false)
private Usuario usuario;
@Deprecated
public Opiniao() {
}
public Opiniao(@NotNull @Min(1) @Max(5) Integer nota,
@NotBlank String titulo,
@NotBlank @Length(max = 500) String descricao,
@NotNull @Valid Produto produto,
@NotNull @Valid Usuario usuario) {
this.nota = nota;
this.titulo = titulo;
this.descricao = descricao;
this.produto = produto;
this.usuario = usuario;
}
public Integer getNota() {
return nota;
}
public String getTitulo() {
return titulo;
}
public String getDescricao() {
return descricao;
}
}
|
9230ad9f22425b874acd2b7c2f2c92fcee6e11e8 | 1,151 | java | Java | src/main/java/downfall/relics/ShatteredFragment.java | tldyl/EvilWithin | 2a713787ccd7e1228d59f0946db76a689bda6b89 | [
"MIT"
] | 12 | 2020-08-27T16:35:17.000Z | 2022-03-26T17:57:00.000Z | src/main/java/downfall/relics/ShatteredFragment.java | tldyl/EvilWithin | 2a713787ccd7e1228d59f0946db76a689bda6b89 | [
"MIT"
] | 1 | 2021-04-02T21:05:12.000Z | 2021-04-02T21:05:12.000Z | src/main/java/downfall/relics/ShatteredFragment.java | tldyl/EvilWithin | 2a713787ccd7e1228d59f0946db76a689bda6b89 | [
"MIT"
] | 23 | 2020-06-28T19:57:13.000Z | 2022-03-27T08:07:50.000Z | 34.878788 | 116 | 0.765421 | 995,567 | package downfall.relics;
import basemod.abstracts.CustomRelic;
import com.badlogic.gdx.graphics.Texture;
import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction;
import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import downfall.downfallMod;
import guardian.cards.CrystalShiv;
public class ShatteredFragment extends CustomRelic {
public static final String ID = downfallMod.makeID("ShatteredFragment");
private static final Texture IMG = new Texture(downfallMod.assetPath("images/relics/WingShiv.png"));
private static final Texture OUTLINE = new Texture(downfallMod.assetPath("images/relics/Outline/WingShiv.png"));
public ShatteredFragment() {
super(ID, IMG, OUTLINE, RelicTier.SPECIAL, LandingSound.FLAT);
}
@Override
public String getUpdatedDescription() {
return DESCRIPTIONS[0];
}
@Override
public void atTurnStart() {
this.addToBot(new RelicAboveCreatureAction(AbstractDungeon.player, this));
this.addToBot(new MakeTempCardInHandAction(new CrystalShiv(), 1, false));
}
}
|
9230ada9f9f29ae7c22d3938b5ec633fd7e86ef0 | 460 | java | Java | app/src/main/java/com/mayhsupaing/news/delegates/NewsActionDelegate.java | mayhsupaing/PADC-3-F-MHP-MM-News | d5e2003d54f4ba93102fb2eab3aa4110ee4ae73e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/mayhsupaing/news/delegates/NewsActionDelegate.java | mayhsupaing/PADC-3-F-MHP-MM-News | d5e2003d54f4ba93102fb2eab3aa4110ee4ae73e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/mayhsupaing/news/delegates/NewsActionDelegate.java | mayhsupaing/PADC-3-F-MHP-MM-News | d5e2003d54f4ba93102fb2eab3aa4110ee4ae73e | [
"Apache-2.0"
] | null | null | null | 24.210526 | 46 | 0.756522 | 995,568 | package com.mayhsupaing.news.delegates;
import com.mayhsupaing.news.data.vo.NewsVO;
/**
* Created by Lenovo on 12/17/2017.
*/
public interface NewsActionDelegate {
void onTapNewsItem(NewsVO tappedNews);
void onTapCommentButton();
void onTapSendToButton(NewsVO tappedNews);
void onTapFavouriteButton();
void onTapLikeUser(NewsVO tappedNews);
void onTapCommentUser(NewsVO tappedNews);
void onTapSendToUser(NewsVO tappedNews);
}
|
9230afa677a308ef7e463251491f66ed7b6b908a | 2,511 | java | Java | app/src/main/java/com/discover/step/helper/BitmapHelper.java | stepapp/step-android-service | 1ca971e5da9490aeb259510d53014dbf400d9496 | [
"CC0-1.0"
] | null | null | null | app/src/main/java/com/discover/step/helper/BitmapHelper.java | stepapp/step-android-service | 1ca971e5da9490aeb259510d53014dbf400d9496 | [
"CC0-1.0"
] | null | null | null | app/src/main/java/com/discover/step/helper/BitmapHelper.java | stepapp/step-android-service | 1ca971e5da9490aeb259510d53014dbf400d9496 | [
"CC0-1.0"
] | null | null | null | 33.932432 | 99 | 0.708084 | 995,569 | package com.discover.step.helper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import com.discover.step.util.DpConverterUtil;
public class BitmapHelper {
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = bitmap.getWidth();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
//paint.setMaskFilter(new BlurMaskFilter(15, Blur.INNER));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static Bitmap getCenterChorpedRoundedBitmap(Bitmap bitmap, int size) {
int sourceWidth = bitmap.getWidth();
int sourceHeight = bitmap.getHeight();
int newWidth = (int) DpConverterUtil.convertDpToPixel(size);
int newHeight = (int) DpConverterUtil.convertDpToPixel(size);
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
Bitmap output = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, newWidth, newHeight);
final RectF rectBaseF = new RectF(rect);
final RectF rectModifiedBmpF = new RectF(left, top,left + scaledWidth, top + scaledHeight);
final float roundPx = newWidth;
paint.setAntiAlias(true);
canvas.drawRoundRect(rectBaseF,roundPx,roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, null, rectModifiedBmpF, paint);
return output;
}
}
|
9230b0dbb5f7c4d4f6ccbe1bc4d4f4a4e3e738de | 1,215 | java | Java | management-model/src/main/java/com/abeldevelop/architecture/service/management/model/ServiceEntity.java | abeldevelop/management-service | 1e77cbf880c9f0157d4c9fc1a8f244be7d271487 | [
"Apache-2.0"
] | null | null | null | management-model/src/main/java/com/abeldevelop/architecture/service/management/model/ServiceEntity.java | abeldevelop/management-service | 1e77cbf880c9f0157d4c9fc1a8f244be7d271487 | [
"Apache-2.0"
] | null | null | null | management-model/src/main/java/com/abeldevelop/architecture/service/management/model/ServiceEntity.java | abeldevelop/management-service | 1e77cbf880c9f0157d4c9fc1a8f244be7d271487 | [
"Apache-2.0"
] | null | null | null | 25.3125 | 68 | 0.784362 | 995,570 | package com.abeldevelop.architecture.service.management.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
@ToString
@Table(name = "services", schema = "management_db")
@Entity
public class ServiceEntity {
@Id
@Column(name = "name", nullable = false, unique = true)
private String name;
@Column(name = "description", nullable = false, unique = true)
private String description;
@Column(name = "port", nullable = false, unique = true)
private Integer port;
@Column(name = "git_url", nullable = false)
private String gitUrl;
@Column(name = "documentation_url", nullable = false)
private String documentationUrl;
@ManyToOne(fetch = FetchType.LAZY)
private ApplicationEntity application;
} |
9230b28383857b45cfb228d9f72356d3e5f0280a | 2,801 | java | Java | app/src/main/java/fr/lab/bbox/bboxapirunner/BboxFragment.java | BboxLab/bboxapi-client-android | 81b1d16247161b3fe081e635169c0b8d231467ed | [
"MIT"
] | null | null | null | app/src/main/java/fr/lab/bbox/bboxapirunner/BboxFragment.java | BboxLab/bboxapi-client-android | 81b1d16247161b3fe081e635169c0b8d231467ed | [
"MIT"
] | null | null | null | app/src/main/java/fr/lab/bbox/bboxapirunner/BboxFragment.java | BboxLab/bboxapi-client-android | 81b1d16247161b3fe081e635169c0b8d231467ed | [
"MIT"
] | 1 | 2021-06-11T18:35:43.000Z | 2021-06-11T18:35:43.000Z | 32.952941 | 138 | 0.638343 | 995,571 | package fr.lab.bbox.bboxapirunner;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import fr.bouyguestelecom.tv.bboxapi.Bbox;
/**
* Created by dinh on 01/07/16.
*/
public class BboxFragment extends Fragment implements View.OnClickListener {
private static final String TAG = BboxFragment.class.getSimpleName();
private Button mSearchBtn;
private Button mSaveBtn;
private EditText mBboxIp;
private TextView mCurrentIp;
private SharedPreferences mSharedPreferences;
private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_bbox, container, false);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mCurrentIp = (TextView) view.findViewById(R.id.currentip);
mSearchBtn = view.findViewById(R.id.searchBtn);
mSaveBtn = view.findViewById(R.id.saveBtn);
mBboxIp = view.findViewById(R.id.bboxip);
mCurrentIp.setText(mSharedPreferences.getString("bboxip", ""));
mSearchBtn.setOnClickListener(this);
mSaveBtn.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
if (v == mSearchBtn) {
Bbox.discoverBboxApi(getActivity(), getString(R.string.APP_ID), getString(R.string.APP_SECRET), new Bbox.DiscoveryListener() {
@Override
public void bboxFound(final Bbox bbox) {
mHandler.post(new Runnable() {
@Override
public void run() {
mCurrentIp.setText(bbox.getIp());
}
});
}
});
} else if (v == mSaveBtn) {
final String bboxip = mBboxIp.getText().toString();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("bboxip", bboxip);
editor.apply();
mHandler.post(new Runnable() {
@Override
public void run() {
mCurrentIp.setText(bboxip);
Toast.makeText(getActivity(), "Bbox IP address saved", Toast.LENGTH_LONG).show();
}
});
}
}
} |
9230b2f0b119026a755287725ba8b9676bfc0a8a | 7,079 | java | Java | src/main/java/com/revature/servlet/UserServlet.java | tmd1990us/troy_davis_p1 | d12787bfb8fe096591e522b71a9505643f505cb0 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/revature/servlet/UserServlet.java | tmd1990us/troy_davis_p1 | d12787bfb8fe096591e522b71a9505643f505cb0 | [
"Apache-2.0"
] | 1 | 2020-09-03T21:24:19.000Z | 2020-09-03T21:24:19.000Z | src/main/java/com/revature/servlet/UserServlet.java | tmd1990us/troy_davis_p1 | d12787bfb8fe096591e522b71a9505643f505cb0 | [
"Apache-2.0"
] | null | null | null | 41.641176 | 116 | 0.62085 | 995,572 | package com.revature.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.revature.dtos.ErrorResponse;
import com.revature.exceptions.InvalidRequestException;
import com.revature.exceptions.ResourceNotFoundException;
import com.revature.models.Role;
import com.revature.models.User;
import com.revature.services.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
@WebServlet("/users/*")
public class UserServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ObjectMapper mapper = new ObjectMapper();
PrintWriter writer = resp.getWriter();
resp.setContentType("application/json");
System.out.println(req.getRequestURI());
System.out.println(req.getParameter("id"));
try {
// String idParam = req.getParameter("id");
// String emailParam = req.getParameter("email");
// String roleParam = req.getParameter("role");
// if (idParam != null){
// //Get the user by id if present
// int id = Integer.parseInt(idParam);
// User user = userService.getUserById(id);
// String userJSON = mapper.writeValueAsString(user);
// writer.write(userJSON);
// resp.setStatus(200);
// }
// if (emailParam != null){
// //Get the user by id if present
// User user = userService.getUserByEmail(emailParam);
// String userJSON = mapper.writeValueAsString(user);
// writer.write(userJSON);
// resp.setStatus(200);
// }
// if (roleParam != null){
// //Get all users by role if present
// List<User> users = userService.getUsersByRole(roleParam);
// String userJSON = mapper.writeValueAsString(users);
// writer.write(userJSON);
// resp.setStatus(200);
// }
Integer loggedInRole = (Integer) req.getSession().getAttribute("loggedinrole");
//check to see if Admin role before sending all users
if (loggedInRole == 1){
List<User> users = userService.getAllUsers();
String usersJSON = mapper.writeValueAsString(users);
writer.write(usersJSON);
resp.setStatus(200); //not required will be 200 by default
}
} catch (ResourceNotFoundException rnfe){
resp.setStatus(404);
ErrorResponse err = new ErrorResponse(404,rnfe.getMessage());
writer.write(mapper.writeValueAsString(err));
} catch (NumberFormatException | InvalidRequestException nfe){
resp.setStatus(400);
ErrorResponse err = new ErrorResponse(404, "Malformed user id");
writer.write(mapper.writeValueAsString(err));
} catch (Exception e){
e.printStackTrace();
resp.setStatus(500); //500 = internal server error
ErrorResponse err = new ErrorResponse(500,"server: my bad.");
writer.write(mapper.writeValueAsString(err));
}
}
/**
* getting the do post method
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
ObjectMapper mapper = new ObjectMapper();
PrintWriter respWriter = resp.getWriter();
try {
//read BODY OF REQUEST
//create new appuser from the json request
User newUser = mapper.readValue(req.getInputStream(),User.class);
userService.register(newUser);
System.out.println(newUser);
String newUserJSON = mapper.writeValueAsString(newUser);
respWriter.write(newUserJSON);
resp.setStatus(201); // 201 = created
}catch (MismatchedInputException upe) {
upe.printStackTrace();
resp.setStatus(400);
ErrorResponse err = new ErrorResponse(400,"Bad Request: malformed user object found in request body");
respWriter.write(mapper.writeValueAsString(err));
}catch (Exception e){
e.printStackTrace();
resp.setStatus(500); //500 = internal server error
ErrorResponse err = new ErrorResponse(500,"server: my bad.");
respWriter.write(mapper.writeValueAsString(err));
}
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
ObjectMapper mapper = new ObjectMapper();
PrintWriter respWriter = resp.getWriter();
try {
Integer loggedInRole = (Integer) req.getSession().getAttribute("loggedinrole");
if (loggedInRole == 1){
User updatedUser = mapper.readValue(req.getInputStream(),User.class);
System.out.println(updatedUser.toString());
userService.update(updatedUser);
resp.setStatus(201); // 201 = created
}
} catch (Exception e){
e.printStackTrace();
resp.setStatus(500); //500 = internal server error
ErrorResponse err = new ErrorResponse(500,"server: my bad.");
respWriter.write(mapper.writeValueAsString(err));
}
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json");
ObjectMapper mapper = new ObjectMapper();
PrintWriter respWriter = resp.getWriter();
try {
Integer loggedInRole = (Integer) req.getSession().getAttribute("loggedinrole");
if (loggedInRole == 1){
int idParam = Integer.parseInt(req.getParameter("id"));
System.out.println("id to delete: " + idParam);
if (userService.deleteUserById(idParam)) {
resp.setStatus(201); // 201 = created
}
}
} catch (Exception e){
e.printStackTrace();
resp.setStatus(500); //500 = internal server error
ErrorResponse err = new ErrorResponse(500,"server: my bad.");
respWriter.write(mapper.writeValueAsString(err));
}
}
}
|
9230b339adb0d3a8be08bbdb7c15cd54b9d18b64 | 633 | java | Java | androlog-it/gen/de/akquinet/gomobile/androlog/test/R.java | JLLeitschuh/androlog | 82fa81354c01c9b1d1928062b634ba21f14be560 | [
"Apache-2.0"
] | 8 | 2015-02-11T13:41:27.000Z | 2019-05-24T12:20:23.000Z | androlog-it/gen/de/akquinet/gomobile/androlog/test/R.java | JLLeitschuh/androlog | 82fa81354c01c9b1d1928062b634ba21f14be560 | [
"Apache-2.0"
] | null | null | null | androlog-it/gen/de/akquinet/gomobile/androlog/test/R.java | JLLeitschuh/androlog | 82fa81354c01c9b1d1928062b634ba21f14be560 | [
"Apache-2.0"
] | 6 | 2016-04-24T10:05:16.000Z | 2020-02-11T03:29:46.000Z | 26.375 | 52 | 0.687204 | 995,573 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package de.akquinet.gomobile.androlog.test;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}
|
9230b3907e999e030f5c21a866917b07272dfa60 | 396 | java | Java | src/main/java/com/example/demo/service/MemoService.java | blteam220/demo-security-spring2-master | eb50c537b29630fd9a9eff3f523765c57dec8762 | [
"MIT"
] | 25 | 2018-05-08T13:58:17.000Z | 2022-02-26T10:06:34.000Z | src/main/java/com/example/demo/service/MemoService.java | blteam220/demo-security-spring2-master | eb50c537b29630fd9a9eff3f523765c57dec8762 | [
"MIT"
] | 1 | 2019-11-19T15:41:09.000Z | 2019-11-19T16:04:39.000Z | src/main/java/com/example/demo/service/MemoService.java | blteam220/demo-security-spring2-master | eb50c537b29630fd9a9eff3f523765c57dec8762 | [
"MIT"
] | 9 | 2018-06-06T07:12:28.000Z | 2021-10-03T01:39:34.000Z | 20.842105 | 48 | 0.767677 | 995,574 | package com.example.demo.service;
import com.example.demo.entity.Memo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
public interface MemoService {
Optional<Memo> findById(Long id);
Page<Memo> findAll(Pageable page);
void store(Memo memo);
void updateById(Long id, Memo memo);
void removeById(Long id);
} |
9230b3ba01dbdcc87d60519112ac553425d03f76 | 18,473 | java | Java | wct-core/src/main/java/org/webcurator/ui/util/TabbedController.java | jmvezic/webcurator | 74f1be1ad1e7c528e1b55f3e7f93911b23844d49 | [
"Apache-2.0"
] | 29 | 2015-11-09T10:59:40.000Z | 2020-02-17T09:32:50.000Z | wct-core/src/main/java/org/webcurator/ui/util/TabbedController.java | jmvezic/webcurator | 74f1be1ad1e7c528e1b55f3e7f93911b23844d49 | [
"Apache-2.0"
] | 106 | 2015-11-17T02:12:04.000Z | 2020-11-22T20:52:49.000Z | wct-core/src/main/java/org/webcurator/ui/util/TabbedController.java | jmvezic/webcurator | 74f1be1ad1e7c528e1b55f3e7f93911b23844d49 | [
"Apache-2.0"
] | 18 | 2015-11-09T10:59:43.000Z | 2020-11-10T13:20:25.000Z | 36.435897 | 168 | 0.70779 | 995,575 | /*
* Copyright 2006 The National Library of New Zealand
*
* 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.webcurator.ui.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.BaseCommandController;
import org.springframework.web.util.WebUtils;
import org.webcurator.ui.common.Constants;
import org.webcurator.ui.target.command.TargetDefaultCommand;
import org.webcurator.ui.target.command.TargetGeneralCommand;
import org.webcurator.ui.target.command.TargetInstanceCommand;
/**
* The <code>TabbedController</code> extends Spring's BaseCommandController to
* create a controller that helps with tabbed interfaces. The TabbedController
* itself is the main manager for a set of tabs. It is responsible for
* controlling entry into the tabs, exit from the set of tabs, and determining
* which tab should be displayed.
*
* The TabConfig class manages the set of tabs in a given tab set.
*
* The TabHandler is responsible for processing the entry or submission of any
* given tab.
*
* This controller relies on the presence of parameters in the request to
* identify what type of action should be performed. The parameter do not need a
* specific value - their presence is all that is required. The list of
* parameters that control the action are as follows:
*
* <ul>
* <li><code>_tab_current_page</code> - identifies the current page.</li>
* <li><code>_tab_change</code> - indicates that we are changing to a
* different tab.</li>
* <li><code>_tab_save</code> - indicates we are saving the tabset.</li>
* <li><code>_tab_cancel</code> - indicates we are cancelling any changes we
* have made in this tabset.</li>
* </ul>
*
* If _tab_change is specified, this controller uses the value of the
* <code>tabChangedTo</code> parameter to identify the title of the next tab
* to be displayed.
*
* If none of these actions are selected, the TabbedController invokes the
* processOther method of the current tab's handler and lets it decide what to
* do. This is useful for supporting "sub-actions" within a tab.
*
* The TabbedController only defines handlers for POST requests. For GET
* requests the request is delegated through to the showForm method on the
* subclass. This method is not exactly the same as the standard Spring showForm
* method as it may have a Command object associated with it. If you wish to
* bookmark an tabset, it is critical the the showForm method is overriden as it
* is the only method that responds to a GET request.
*
* @author bbeaumont
*/
public abstract class TabbedController extends BaseCommandController {
/** The default command class for the entry into this tabbed controller */
private Class defaultCommandClass = null;
/** The default validator for entry into this tabbed controller */
private Validator defaultValidator = null;
/** The tab configuration - set of tabs in the tabset */
private TabConfig tabConfig;
/**
* Get the tab configuration.
*
* @return The tab configuration.
*/
public TabConfig getTabConfig() {
return tabConfig;
}
/**
* Set the tab configuration.
*
* @param tabConfig
* the tab configuration.
*/
public void setTabConfig(TabConfig tabConfig) {
this.tabConfig = tabConfig;
}
/**
* Get the ID of the next tab to be displayed. This looks for a hidden
* fields named "_TAB"
*
* @param req
* The HttpServletRequest.
* @return The ID of the next tab to be displayed.
*/
public String getNextTab(HttpServletRequest req) {
String code = req.getParameter("_TAB");
return code;
}
/**
* Initialise the binders for this request. This method checks to see if
* there is a current page enabled. If there is, this calls the binder
* method of the tab handler for that tab.
*/
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
String currentPage = request.getParameter("_tab_current_page");
if (currentPage != null && !currentPage.trim().equals("")) {
Tab currentTab = tabConfig.getTabByID(currentPage);
currentTab.getTabHandler().initBinder(request, binder);
}
}
/**
* An inner class for a Tabbed ModelAndView. This limits the amount of setup
* required to ensure that tabs are correctly set up.
*
* @author bbeaumont
*
*/
public class TabbedModelAndView extends ModelAndView {
/** The tab status */
private TabStatus tabStatus = new TabStatus();
/**
* Construct and new Model and View.
*/
public TabbedModelAndView() {
super();
this.setViewName(getTabConfig().getViewName());
this.addObject("tabs", tabConfig);
this.addObject("tabStatus", tabStatus);
}
/**
* Construct a new model and view.
*
* @param modelName
* The name of the model object to add.
* @param modelObj
* The model object to set.
*/
public TabbedModelAndView(String modelName, Object modelObj) {
super(getTabConfig().getViewName(), modelName, modelObj);
this.addObject("tabs", tabConfig);
this.addObject("tabStatus", tabStatus);
}
/**
* Get the tab status object for the view.
*
* @return The tab status object for this view.
*/
public TabStatus getTabStatus() {
return tabStatus;
}
}
/**
* Process the save instruction for this set of tabs. This is invoked when
* the user saves a tabset. This action is identified by the presence of the
* _tab_save parameter in the request.
*
* The implementation of this method should save the tabset to the database
* and then return a ModelAndView of a logical "next" page. The
* TabbedController will perform validation of the current tab, but if there
* is any validation required across tabs, it may need to be done in this
* method.
*
* @param currentTab
* The current tab being posted.
* @param req
* The HttpServletRequest.
* @param res
* The HttpServletResponse.
* @param comm
* The Spring command object.
* @param errors
* The Spring errors object.
* @return The ModelAndView object to display.
*/
protected abstract ModelAndView processSave(Tab currentTab,
HttpServletRequest req, HttpServletResponse res, Object comm,
BindException errors);
/**
* Process the cancel instruction for this set of tabs. This is invoked when
* the user cancels a tabset. This action is identified by the presence of
* the _tab_cancel parameter in the request.
*
* In general this method will abort any changes made in the tabset and
* return the user to a logical point in the application.
*
* @param currentTab
* The current tab being posted.
* @param req
* The HttpServletRequest.
* @param res
* The HttpServletResponse.
* @param comm
* The Spring command object.
* @param errors
* The Spring errors object.
* @return The ModelAndView object to display.
*/
protected abstract ModelAndView processCancel(Tab currentTab,
HttpServletRequest req, HttpServletResponse res, Object comm,
BindException errors);
protected abstract void switchToEditMode(HttpServletRequest req);
/**
* Process the entry into the tabset.
*
* In general this method will load an object into the tabset.
*
* @param req
* The HttpServletRequest.
* @param res
* The HttpServletResponse.
* @param comm
* The Spring command object.
* @param errors
* The Spring errors object.
* @return The ModelAndView object to display.
*/
protected abstract ModelAndView processInitial(HttpServletRequest req,
HttpServletResponse res, Object comm, BindException errors);
/**
* This is the main method of the TabbedController. It identifies which
* command has been entered and how the command must be processed. See the
* class description for the controller parameters.
*
* @param req
* The HttpServletRequest.
* @param res
* The HttpServletResponse.
* @param comm
* The Spring command object.
* @param errors
* The Spring errors object.
* @return The next ModelAndView object to be displayed.
* @throws Exception
* Any exception raised by the handlers.
*/
protected ModelAndView processFormSubmission(HttpServletRequest req, HttpServletResponse res, Object comm, BindException errors) throws Exception {
String currentPage = req.getParameter("_tab_current_page");
Tab currentTab = tabConfig.getTabByID(currentPage);
//log.info("processFormSubmission");
//log.info("Current Tab: " + currentTab);
// Tab Change Handler
if( WebUtils.hasSubmitParameter(req, "_tab_change") ) {
Tab nextTab = null;
// If there are errors, do not allow the tab to be changed. Simply
// add the command and errors to the model and return the user to
// the same tab.
if(errors.hasErrors()) {
TabbedModelAndView tmav = currentTab.getTabHandler().preProcessNextTab(this, currentTab, req, res, comm, errors);
tmav.getTabStatus().setCurrentTab(currentTab);
tmav.addObject(Constants.GBL_CMD_DATA, errors.getTarget());
tmav.addObject(Constants.GBL_ERRORS, errors);
return tmav;
}
// There are no errors, so process the tab (saving the information
// to the business objects) and return the view for the next tab,
// as identified by the "tabChangedTo" parameter.
else {
currentTab.getTabHandler().processTab(this, currentTab, req, res, comm, errors);
nextTab = tabConfig.getTabByTitle(req.getParameter("tabChangedTo"));
// ensure that the target instance oid is set (enables us to directly refer the user to a specific tab)
if (comm instanceof TargetInstanceCommand && ((TargetInstanceCommand)comm).getTargetInstanceId() == null && WebUtils.hasSubmitParameter(req, "targetInstanceOid")) {
String targetInstanceOid = req.getParameter("targetInstanceOid");
Long targetInstanceId = Long.parseLong(targetInstanceOid);
((TargetInstanceCommand)comm).setTargetInstanceId(targetInstanceId);
}
TabbedModelAndView tmav = nextTab.getTabHandler().preProcessNextTab(this, nextTab, req, res, comm, errors);
tmav.getTabStatus().setCurrentTab(nextTab);
return tmav;
}
} else if (WebUtils.hasSubmitParameter(req, "_tab_edit"))
{
switchToEditMode(req);
TabbedModelAndView tmav = currentTab.getTabHandler().preProcessNextTab(this, currentTab, req, res, comm, errors);
tmav.getTabStatus().setCurrentTab(currentTab);
return tmav;
}
// Save Handler
else if( WebUtils.hasSubmitParameter(req, "_tab_save")) {
// Process the tab.
currentTab.getTabHandler().processTab(this, currentTab, req, res, comm, errors);
// If there are any errors, do not invoke the save controller, but
// simply return the current tab with the command and errors objects
// populated.
if(errors.hasErrors()) {
TabbedModelAndView tmav = currentTab.getTabHandler().preProcessNextTab(this, currentTab, req, res, comm ,errors);
tmav.getTabStatus().setCurrentTab(currentTab);
tmav.addObject(Constants.GBL_CMD_DATA, comm);
tmav.addObject(Constants.GBL_ERRORS, errors);
return tmav;
}
else {
// There were no errors, so invoke the save method on the
// subclass.
return processSave(currentTab, req, res, comm, errors);
}
}
// Cancel Handler
else if( WebUtils.hasSubmitParameter(req, "_tab_cancel")) {
return processCancel(currentTab, req, res, comm, errors);
}
// No standard action has been provided that the TabbedController
// can handle. In this case, call the processOther method on the
// handler of the current tab and let the tab decide what to do.
else {
//log.debug(currentTab.getTabHandler().getClass().toString());
ModelAndView mav = currentTab.getTabHandler().processOther(this, currentTab, req, res, comm, errors);
//if(mav instanceof TabbedModelAndView) {
// log.debug("Moving to: " + ((TabbedModelAndView)mav).getTabStatus().getCurrentTab().toString());
//}
if(errors.hasErrors()) {
mav.addObject(Constants.GBL_ERRORS, errors);
}
return mav;
// return processOther(currentTab, req, res, comm, errors);
}
}
/**
* Get the Spring command for this request. This method overrides the Spring
* configuration to get the appropriate command class for the currently
* selected tab.
*
* @param req
* The HttpServletRequest.
* @return An unpopulated command class.
*/
@Override
protected Object getCommand(HttpServletRequest req) throws Exception {
String currentPage = req.getParameter("_tab_current_page");
Tab currentTab = tabConfig.getTabByID(currentPage);
Class clazz = currentTab.getCommandClass();
return BeanUtils.instantiateClass(clazz);
}
/**
* General point of access to the controller.
*
* @param request
* The HttpServletRequest object.
* @param response
* The HttpServletResponse object.
* @return The ModelAndView to display.
* @throws Exception
* if anything fails.
*/
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// If the submission method is a POST.
if ("POST".equals(request.getMethod())) {
// Is there a tab currently selected? If there is, then get the
// command object for that tab, populate and validate the command,
// and call the processFormSubmission method to work out what
// to do next.
if (WebUtils.hasSubmitParameter(request, "_tab_current_page")) {
Object command = getCommand(request);
ServletRequestDataBinder binder = bindAndValidate(request,
command);
// create a TargetDefaultCommand and bind the editor context if we need to go directly to a tab
if (WebUtils.hasSubmitParameter(request, "tabForceChangeTo") && request.getParameter("tabForceChangeTo").equals("true")) {
Object newCommand = BeanUtils.instantiateClass(defaultCommandClass);
if (newCommand instanceof TargetDefaultCommand && request.getParameter("targetOid") != null) {
Long targetOid = Long.parseLong(request.getParameter("targetOid"));
((TargetDefaultCommand)newCommand).setTargetOid(targetOid);
showForm(request, response, newCommand, binder.getErrors());
}
}
return processFormSubmission(request, response, command, binder
.getErrors());
}
// No tab is currently selected, so we need to instantated, bind,
// and validate the default command. In general this will load
// an object from the database into the tabset.
else {
Object command = BeanUtils
.instantiateClass(defaultCommandClass);
ServletRequestDataBinder binder = bindAndValidate(request,
command);
return processInitial(request, response, command, binder
.getErrors());
}
} else {
// Even for a form, we may need a command object.
if (defaultCommandClass != null) {
Object command = BeanUtils
.instantiateClass(defaultCommandClass);
ServletRequestDataBinder binder = bindAndValidate(request,
command);
return showForm(request, response, command, binder.getErrors());
} else {
return showForm(request, response, null, null);
}
}
}
/**
* Override the bind and validate method to use the validate and command
* objects defined by the tab, instead of those defined for the controller.
* This allows us to have different command and validator classes per
* handler.
*
* @param req
* The HttpServletRequest object.
* @param command
* The Spring command object.
* @param errors
* The Spring errors object.
* @throws Exception
* on failure.
*/
@Override
protected void onBindAndValidate(HttpServletRequest req, Object command,
BindException errors) throws Exception {
if (WebUtils.hasSubmitParameter(req, "_tab_current_page")) {
String currentPage = req.getParameter("_tab_current_page");
Tab currentTab = tabConfig.getTabByID(currentPage);
if (currentTab.getValidator() != null && !WebUtils.hasSubmitParameter(req, "_tab_cancel")) {
currentTab.getValidator().validate(command, errors);
}
} else {
if (defaultValidator != null && !WebUtils.hasSubmitParameter(req, "_tab_cancel")) {
defaultValidator.validate(command, errors);
}
}
}
/**
* Show the form in response to a GET request. In general this may delegate
* the call and do the same as processInitial. This can be important if you
* wish to be able to bookmark an entry point into the tab (since bookmarks
* must be GET requests).
*
* @param req
* The HttpServletRequest object.
* @param res
* The HttpSerlvetResponse object.
* @param command
* The Spring command object.
* @param bex
* The Spring errors object.
* @return The model and view to display.
* @throws Exception
* if any errors are raised.
*/
protected abstract ModelAndView showForm(HttpServletRequest req,
HttpServletResponse res, Object command, BindException bex)
throws Exception;
/**
* Set the Spring command class to use if we have no current tab. e.g. The
* first entry into the TabbedController.
*
* @param defaultCommand
* The defaultCommandClass to set.
*/
public void setDefaultCommandClass(Class defaultCommand) {
this.defaultCommandClass = defaultCommand;
}
}
|
9230b3bb28af7089d5a12ef244396b3c94486029 | 649 | java | Java | swift-jdbc-parser/src/test/java/com/fr/swift/cloud/jdbc/antlr4/Antlr4CodeGen.java | fanruan/swift-jdbc | 0effc209b35374ea1e33d6fda0399585f19779b7 | [
"Apache-2.0"
] | 7 | 2019-02-14T08:29:18.000Z | 2021-11-18T07:45:30.000Z | swift-jdbc-parser/src/test/java/com/fr/swift/cloud/jdbc/antlr4/Antlr4CodeGen.java | fanruan/swift-jdbc | 0effc209b35374ea1e33d6fda0399585f19779b7 | [
"Apache-2.0"
] | 1 | 2021-03-17T01:11:15.000Z | 2021-03-17T01:11:15.000Z | swift-jdbc-parser/src/test/java/com/fr/swift/cloud/jdbc/antlr4/Antlr4CodeGen.java | fanruan/swift-jdbc | 0effc209b35374ea1e33d6fda0399585f19779b7 | [
"Apache-2.0"
] | 5 | 2019-02-20T07:22:34.000Z | 2019-07-08T01:03:32.000Z | 32.45 | 145 | 0.633282 | 995,576 | package com.fr.swift.cloud.jdbc.antlr4;
import org.antlr.v4.Tool;
/**
* @author anchore
* @date 2019/7/17
* <p>
* 生成parser的工具
*/
public class Antlr4CodeGen {
public static void main(String[] args) {
String classesDir = System.getProperty("user.dir") + "/target/classes/";
String outputDir = System.getProperty("user.dir") + "/intelli-swift-jdbc/swift-jdbc-parser/src/main/java/com/fr/swift/cloud/jdbc/antlr4";
Tool.main(new String[]{
"-package", "com.fr.swift.cloud.jdbc.antlr4",
"-o", outputDir, classesDir + "SwiftSqlLexer.g4", classesDir + "SwiftSqlParser.g4"
});
}
} |
9230b46a199ef273b5e602a3461e75ad45989708 | 1,396 | java | Java | src/command/CriarSugestao.java | thiagocarpes/Sistema-Sugestoes-Web | 32101631a63859891ae149fe7d949f5c97d96e34 | [
"Apache-2.0"
] | null | null | null | src/command/CriarSugestao.java | thiagocarpes/Sistema-Sugestoes-Web | 32101631a63859891ae149fe7d949f5c97d96e34 | [
"Apache-2.0"
] | null | null | null | src/command/CriarSugestao.java | thiagocarpes/Sistema-Sugestoes-Web | 32101631a63859891ae149fe7d949f5c97d96e34 | [
"Apache-2.0"
] | null | null | null | 26.339623 | 71 | 0.769341 | 995,577 | package command;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Sugestao;
import service.SugestaoService;
public class CriarSugestao implements Command {
@Override
public void executar(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String pId = request.getParameter("id");
int pIdUsuario = Integer.parseInt(request.getParameter("idUsuario"));
int pCategoria = Integer.parseInt(request.getParameter("categoria"));
String pTitulo = request.getParameter("titulo");
String pSugestao = request.getParameter("sugestao");
int id = -1;
try {
id = Integer.parseInt(pId);
} catch (NumberFormatException e) {
}
Sugestao sugestao = new Sugestao();
sugestao.setIdSugestao(id);
sugestao.setColaborador(pIdUsuario);
sugestao.setEspecialidade(pCategoria);
sugestao.setTitulo(pTitulo);
sugestao.setSugestao(pSugestao);
SugestaoService ss = new SugestaoService();
ss.novaSugestao(sugestao);
RequestDispatcher view = null;
HttpSession session = request.getSession();
view = request.getRequestDispatcher("sugestoes.jsp");
view.forward(request, response);
}
}
|
9230b672bea27d049ddee9ae47fe2dcd0a3ed115 | 6,743 | java | Java | src/main/java/com/github/netty/protocol/NRpcProtocol.java | tuohai666/spring-boot-protocol | c05693fe4ba31e4cca39e0372d4373962fd5e1e4 | [
"Apache-2.0"
] | 2 | 2021-02-18T02:16:34.000Z | 2021-08-03T08:22:39.000Z | src/main/java/com/github/netty/protocol/NRpcProtocol.java | liuharper/spring-boot-protocol | e762183ac5c3c3f918c825dddd1648759202387b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/netty/protocol/NRpcProtocol.java | liuharper/spring-boot-protocol | e762183ac5c3c3f918c825dddd1648759202387b | [
"Apache-2.0"
] | 1 | 2021-07-13T01:59:31.000Z | 2021-07-13T01:59:31.000Z | 41.623457 | 169 | 0.582975 | 995,578 | package com.github.netty.protocol;
import com.github.netty.annotation.Protocol;
import com.github.netty.core.AbstractProtocol;
import com.github.netty.core.util.ApplicationX;
import com.github.netty.core.util.ClassFileMethodToParameterNamesFunction;
import com.github.netty.core.util.LoggerFactoryX;
import com.github.netty.core.util.LoggerX;
import com.github.netty.protocol.nrpc.*;
import com.github.netty.protocol.nrpc.service.RpcCommandServiceImpl;
import com.github.netty.protocol.nrpc.service.RpcDBServiceImpl;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import static com.github.netty.protocol.nrpc.RpcServerChannelHandler.getRequestMappingName;
/**
* Internal RPC protocol registry
*
* ACK flag : (0=Don't need, 1=Need)
* Request Packet (note: 1 = request type)
*-+------8B--------+--1B--+--1B--+------4B------+-----4B-----+------1B--------+-----length-----+------1B-------+---length----+-----4B------+-------length-------------+
* | header/version | type | ACK | total length | Request ID | service length | service name | method length | method name | data length | data |
* | NRPC/010 | 1 | 1 | 55 | 1 | 8 | "/sys/user" | 7 | getUser | 24 | {"age":10,"name":"wang"} |
*-+----------------+------+------+--------------+------------+----------------+----------------+---------------+-------------+-------------+--------------------------+
*
*
* Response Packet (note: 2 = response type)
*-+------8B--------+--1B--+--1B--+------4B------+-----4B-----+---2B---+--------1B------+--length--+---1B---+-----4B------+----------length----------+
* | header/version | type | ACK | total length | Request ID | status | message length | message | encode | data length | data |
* | NRPC/010 | 2 | 0 | 35 | 1 | 200 | 2 | ok | 1 | 24 | {"age":10,"name":"wang"} |
*-+----------------+------+------+--------------+------------+--------+----------------+----------+--------+-------------+--------------------------+
*
*
*-+------2B-------+--1B--+----1B----+-----8B-----+------1B-----+----------------dynamic---------------------+-------dynamic------------+
* | packet length | type | ACK flag | version | Fields size | Fields | Body |
* | 76 | 1 | 1 | NRPC/201 | 2 | 11requestMappingName6/hello10methodName8sayHello | {"age":10,"name":"wang"} |
*-+---------------+------+----------+------------+-------------+--------------------------------------------+--------------------------+
*
* @author wangzihao
* 2018/11/25/025
*/
public class NRpcProtocol extends AbstractProtocol {
private LoggerX logger = LoggerFactoryX.getLogger(getClass());
private ApplicationX application;
/**
* Maximum message length per pass
*/
private int messageMaxLength = 10 * 1024 * 1024;
private Map<Object,Instance> instanceMap = new HashMap<>();
public NRpcProtocol(ApplicationX application) {
this.application = application;
}
public void addInstance(Object instance){
addInstance(instance,getRequestMappingName(instance.getClass()),new ClassFileMethodToParameterNamesFunction());
}
public void addInstance(Object instance,String requestMappingName,Function<Method,String[]> methodToParameterNamesFunction){
instanceMap.put(instance,new Instance(instance,requestMappingName,methodToParameterNamesFunction));
logger.info("addInstance({}, {}, {})",
requestMappingName,
instance.getClass().getSimpleName(),
methodToParameterNamesFunction.getClass().getSimpleName());
}
public boolean existInstance(Object instance){
return instanceMap.containsKey(instance);
}
@Override
public String getProtocolName() {
return RpcVersion.CURRENT_VERSION.getText();
}
@Override
public boolean canSupport(ByteBuf msg) {
return RpcVersion.CURRENT_VERSION.isSupport(msg);
}
@Override
public void addPipeline(Channel channel) throws Exception {
RpcServerChannelHandler rpcServerHandler = new RpcServerChannelHandler();
rpcServerHandler.getAopList().addAll(application.getBeanForType(RpcServerAop.class));
for (Instance instance : instanceMap.values()) {
rpcServerHandler.addInstance(instance.instance,instance.requestMappingName,instance.methodToParameterNamesFunction);
}
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new RpcDecoder(messageMaxLength));
pipeline.addLast(new RpcEncoder());
pipeline.addLast(rpcServerHandler);
}
@Override
public int getOrder() {
return 200;
}
@Override
public void onServerStart() throws Exception {
Collection list = application.getBeanForAnnotation(Protocol.RpcService.class);
for(Object serviceImpl : list){
if(existInstance(serviceImpl)){
continue;
}
addInstance(serviceImpl);
}
addInstancePlugins();
for (RpcServerAop rpcServerAop : application.getBeanForType(RpcServerAop.class)) {
rpcServerAop.onInitAfter(this);
}
}
@Override
public void onServerStop() throws Exception {
}
/**
* Add an instance of the extension
*/
protected void addInstancePlugins(){
//The RPC basic command service is enabled by default
addInstance(new RpcCommandServiceImpl());
//Open DB service by default
addInstance(new RpcDBServiceImpl());
}
protected ApplicationX getApplication() {
return application;
}
public int getMessageMaxLength() {
return messageMaxLength;
}
public void setMessageMaxLength(int messageMaxLength) {
this.messageMaxLength = messageMaxLength;
}
static class Instance{
Object instance;
String requestMappingName;
Function<Method,String[]> methodToParameterNamesFunction;
Instance(Object instance, String requestMappingName, Function<Method, String[]> methodToParameterNamesFunction) {
this.instance = instance;
this.requestMappingName = requestMappingName;
this.methodToParameterNamesFunction = methodToParameterNamesFunction;
}
}
}
|
9230b765a3fe7d17440750268c99e52ba00c5672 | 347 | java | Java | sourceTest/src/main/java/com/source/learn/springApplication_xmldependencyInjetion/BClassService.java | zhaojiaying/learn_springFramework | 7c47dd001537e19ca76eb41ae19dd6de266900b2 | [
"Apache-2.0"
] | null | null | null | sourceTest/src/main/java/com/source/learn/springApplication_xmldependencyInjetion/BClassService.java | zhaojiaying/learn_springFramework | 7c47dd001537e19ca76eb41ae19dd6de266900b2 | [
"Apache-2.0"
] | null | null | null | sourceTest/src/main/java/com/source/learn/springApplication_xmldependencyInjetion/BClassService.java | zhaojiaying/learn_springFramework | 7c47dd001537e19ca76eb41ae19dd6de266900b2 | [
"Apache-2.0"
] | null | null | null | 14.458333 | 65 | 0.694524 | 995,579 | package com.source.learn.springApplication_xmldependencyInjetion;
/**
* 测试 set方法 注入
* @author: jiayingzhao
* @Date: 2019.11.23
*/
public class BClassService {
ClassDao dao;
public void service(){
dao.service();
}
/**
* 在xml中配置此依赖的时候,通过set方法注入IOC容器,xml中使用property来注入
*/
public void setDao(ClassDao dao) {
this.dao = dao;
}
}
|
9230b876472b52f9ea7055d93e3193361b611726 | 1,431 | java | Java | app/src/main/java/com/journal/salimfgaier/journalalc/Database/LocalDB.java | salimsuke/ALC_Journal_App | 4bcb3af4c1afa1997fe11520332ca35035ecc00e | [
"MIT"
] | null | null | null | app/src/main/java/com/journal/salimfgaier/journalalc/Database/LocalDB.java | salimsuke/ALC_Journal_App | 4bcb3af4c1afa1997fe11520332ca35035ecc00e | [
"MIT"
] | null | null | null | app/src/main/java/com/journal/salimfgaier/journalalc/Database/LocalDB.java | salimsuke/ALC_Journal_App | 4bcb3af4c1afa1997fe11520332ca35035ecc00e | [
"MIT"
] | null | null | null | 38.675676 | 95 | 0.734451 | 995,580 | package com.journal.salimfgaier.journalalc.Database;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverters;
import android.content.Context;
import android.util.Log;
import com.journal.salimfgaier.journalalc.DataAccessLayer.JournalDAO;
import com.journal.salimfgaier.journalalc.Database.Models.Journal;
import com.journal.salimfgaier.journalalc.Utility.DateConverter;
@Database(entities = {Journal.class}, version = 1, exportSchema = false)
@TypeConverters(DateConverter.class)
public abstract class LocalDB extends RoomDatabase {
private static final String LOG_TAG = LocalDB.class.getSimpleName();
private static final String DATABASE_NAME = "local-journal-db";
private static final Object LOCK = new Object();
private static LocalDB sInstance;
public static LocalDB getInstance(Context context) {
synchronized (LOCK) {
if (sInstance == null) {
Log.d(LOG_TAG, "new database instance creating");
sInstance = Room.databaseBuilder(context.getApplicationContext(),
LocalDB.class, DATABASE_NAME).fallbackToDestructiveMigration().build();
}
}
Log.d(LOG_TAG, "Getting database instance");
return sInstance;
}
public abstract JournalDAO journalDao();
}
|
9230b88e2e71c73d59cbb45818aa456a8343ba09 | 3,188 | java | Java | scrimage-filters/src/main/java/thirdparty/jhlabs/image/SwimFilter.java | gipeshka/scrimage | de467304de8c9ac7b1b790c3e05a2b40f2227837 | [
"Apache-2.0"
] | 772 | 2015-01-02T14:28:59.000Z | 2022-03-29T05:33:06.000Z | scrimage-filters/src/main/java/thirdparty/jhlabs/image/SwimFilter.java | gipeshka/scrimage | de467304de8c9ac7b1b790c3e05a2b40f2227837 | [
"Apache-2.0"
] | 189 | 2015-01-02T16:41:27.000Z | 2022-03-29T02:14:43.000Z | scrimage-filters/src/main/java/thirdparty/jhlabs/image/SwimFilter.java | gipeshka/scrimage | de467304de8c9ac7b1b790c3e05a2b40f2227837 | [
"Apache-2.0"
] | 130 | 2015-01-23T21:21:56.000Z | 2022-01-13T22:00:57.000Z | 26.131148 | 85 | 0.603827 | 995,581 | /*
Copyright 2006 Jerry Huxtable
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 thirdparty.jhlabs.image;
import thirdparty.jhlabs.math.*;
import java.util.Random;
/**
* A filter which distorts an image as if it were underwater.
*/
public class SwimFilter extends TransformFilter {
private final NoiseInstance noise;
private float scale = 32;
private float stretch = 1.0f;
private float angle = 0.0f;
private float amount = 1.0f;
private float turbulence = 1.0f;
private float time = 0.0f;
private float m00 = 1.0f;
private float m01 = 0.0f;
private float m10 = 0.0f;
private float m11 = 1.0f;
public SwimFilter(Random random) {
this.noise = new NoiseInstance(random);
}
public void setAmount(float amount) {
this.amount = amount;
}
/**
* Specifies the scale of the distortion.
*
* @param scale the scale of the distortion.
* min-value 1
* max-value 300+
*/
public void setScale(float scale) {
this.scale = scale;
}
/**
* Specifies the stretch factor of the distortion.
*
* @param stretch the stretch factor of the distortion.
* min-value 1
* max-value 50+
*/
public void setStretch(float stretch) {
this.stretch = stretch;
}
/**
* Specifies the angle of the effect.
*/
public void setAngle(float angle) {
this.angle = angle;
float cos = (float) Math.cos(angle);
float sin = (float) Math.sin(angle);
m00 = cos;
m01 = sin;
m10 = -sin;
m11 = cos;
}
/**
* Specifies the turbulence of the texture.
*
* @param turbulence the turbulence of the texture.
* min-value 0
* max-value 1
*/
public void setTurbulence(float turbulence) {
this.turbulence = turbulence;
}
/**
* Specifies the time. Use this to animate the effect.
*
* @param time the time.
*/
public void setTime(float time) {
this.time = time;
}
protected void transformInverse(int x, int y, float[] out) {
float nx = m00 * x + m01 * y;
float ny = m10 * x + m11 * y;
nx /= scale;
ny /= scale * stretch;
if (turbulence == 1.0f) {
out[0] = x + amount * noise.noise3(nx + 0.5f, ny, time);
out[1] = y + amount * noise.noise3(nx, ny + 0.5f, time);
} else {
out[0] = x + amount * noise.turbulence3(nx + 0.5f, ny, turbulence, time);
out[1] = y + amount * noise.turbulence3(nx, ny + 0.5f, turbulence, time);
}
}
public String toString() {
return "Distort/Swim...";
}
}
|
9230b8c06900357a5b54f21e99c2c3dc3295a9df | 175 | java | Java | src/main/java/edu/purdue/jpgsql/type/package-info.java | Lorentz83/jpgsql | 4727d3b879cab96e7c910c1b77ca1fe9a5e95021 | [
"MIT"
] | null | null | null | src/main/java/edu/purdue/jpgsql/type/package-info.java | Lorentz83/jpgsql | 4727d3b879cab96e7c910c1b77ca1fe9a5e95021 | [
"MIT"
] | null | null | null | src/main/java/edu/purdue/jpgsql/type/package-info.java | Lorentz83/jpgsql | 4727d3b879cab96e7c910c1b77ca1fe9a5e95021 | [
"MIT"
] | null | null | null | 29.166667 | 75 | 0.765714 | 995,582 | /**
* Contains Postgres data types. The Postgres protocol defines some complex
* types. This package contains classes to represent them.
*/
package edu.purdue.jpgsql.type;
|
9230b94eb198e5c8902a7ea16eb6c2b316d49ac3 | 552 | java | Java | lemenintl/src/main/java/com/tom/lemenintl/entity/TransOverseaConsultItem.java | liri19921121/empire | b8e099509acd13147677edbb76e9732204ec0619 | [
"MIT"
] | null | null | null | lemenintl/src/main/java/com/tom/lemenintl/entity/TransOverseaConsultItem.java | liri19921121/empire | b8e099509acd13147677edbb76e9732204ec0619 | [
"MIT"
] | null | null | null | lemenintl/src/main/java/com/tom/lemenintl/entity/TransOverseaConsultItem.java | liri19921121/empire | b8e099509acd13147677edbb76e9732204ec0619 | [
"MIT"
] | null | null | null | 17.806452 | 52 | 0.773551 | 995,583 | package com.tom.lemenintl.entity;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@Data
public class TransOverseaConsultItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
Long overseaConsultId;// 父id
Long userId;// 用户id
@Transient
String userName;
Long replierAccountId;// 回复人员id
@Transient
String replierAccountName;
String content;// 内容
String updator;
LocalDateTime updateTime = LocalDateTime.now();
String creator;
LocalDateTime createTime = LocalDateTime.now();
}
|
9230bb0415508ca49e25f4c72f7fa4d093086e0b | 1,675 | java | Java | ClassificationTraining/SpringSprint/ShipWithinDays.java | Kevin-SJW/Enterprise-programming-exercises | 7b64e7c7c0d4b5bb4624b7ce3f5875485ab2d614 | [
"MIT"
] | 1 | 2019-05-12T11:17:57.000Z | 2019-05-12T11:17:57.000Z | ClassificationTraining/SpringSprint/ShipWithinDays.java | Kevin-SJW/Enterprise-programming-exercises | 7b64e7c7c0d4b5bb4624b7ce3f5875485ab2d614 | [
"MIT"
] | null | null | null | ClassificationTraining/SpringSprint/ShipWithinDays.java | Kevin-SJW/Enterprise-programming-exercises | 7b64e7c7c0d4b5bb4624b7ce3f5875485ab2d614 | [
"MIT"
] | null | null | null | 24.632353 | 61 | 0.486567 | 995,584 | package ClassificationTraining.SpringSprint;
/**
* @Classname ShipWithinDays
* @Description TODO
* @Date 2021/2/11 16:33
* @Created by Administrator
* 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。传送带上的第 i 个包裹的重量为 weights[i]。
* 每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
* 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
* 示例 1:
* <p>
* 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
* 输出:15
*/
public class ShipWithinDays {
public static void main(String[] args) {
int[] weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int d = 5;
System.out.println(shipWithinDays(weights, d));
}
public static int shipWithinDays(int[] weights, int d) {
int left = getMax(weights);
int right = getSum(weights) + 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (canFinsh(weights, d, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
public static boolean canFinsh(int[] w, int D, int cap) {
int i = 0;
for (int day = 0; day < D; day++) {
int maxCap = cap;
while ((maxCap -= w[i]) >= 0) {
i++;
if(i==w.length){
return true;
}
}
}
return false;
}
public static int getSum(int[] weights) {
int sum = 0;
for (int n : weights) {
sum += n;
}
return sum;
}
public static int getMax(int[] weights) {
int max = 0;
for (int n : weights) {
max = Math.max(n, max);
}
return max;
}
}
|
9230bb9242e6d2404dae80141c3308f7a9332215 | 42,396 | java | Java | juneau-utest/src/test/java/org/apache/juneau/xml/BasicXmlTest.java | garydgregory/juneau | d3cb07c42e71507cab3d303cca340f4706d9e3c0 | [
"Apache-2.0"
] | 65 | 2017-11-01T00:59:36.000Z | 2021-11-06T22:04:06.000Z | juneau-utest/src/test/java/org/apache/juneau/xml/BasicXmlTest.java | garydgregory/juneau | d3cb07c42e71507cab3d303cca340f4706d9e3c0 | [
"Apache-2.0"
] | 43 | 2018-01-11T23:36:18.000Z | 2021-03-06T15:00:05.000Z | juneau-utest/src/test/java/org/apache/juneau/xml/BasicXmlTest.java | garydgregory/juneau | d3cb07c42e71507cab3d303cca340f4706d9e3c0 | [
"Apache-2.0"
] | 34 | 2017-11-01T00:59:38.000Z | 2021-11-06T22:03:57.000Z | 24.865689 | 331 | 0.505024 | 995,585 | // ***************************************************************************************************************************
// * 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.juneau.xml;
import static org.junit.Assert.*;
import static org.junit.runners.MethodSorters.*;
import java.util.*;
import org.apache.juneau.annotation.*;
import org.apache.juneau.collections.*;
import org.apache.juneau.xml.annotation.*;
import org.junit.*;
import org.junit.runner.*;
import org.junit.runners.*;
@RunWith(Parameterized.class)
@SuppressWarnings({"serial"})
@FixMethodOrder(NAME_ASCENDING)
public class BasicXmlTest {
private static final XmlSerializer
s1 = XmlSerializer.DEFAULT_SQ,
s2 = XmlSerializer.DEFAULT_SQ_READABLE,
s3 = XmlSerializer.DEFAULT_NS_SQ;
private static final XmlParser parser = XmlParser.DEFAULT;
@Parameterized.Parameters
public static Collection<Object[]> getParameters() {
return Arrays.asList(new Object[][] {
{ /* 0 */
"SimpleTypes-1",
"foo",
"<string>foo</string>",
"<string>foo</string>\n",
"<string>foo</string>",
},
{ /* 1 */
"SimpleTypes-2",
true,
"<boolean>true</boolean>",
"<boolean>true</boolean>\n",
"<boolean>true</boolean>",
},
{ /* 2 */
"SimpleTypes-3",
123,
"<number>123</number>",
"<number>123</number>\n",
"<number>123</number>",
},
{ /* 3 */
"SimpleTypes-4",
1.23f,
"<number>1.23</number>",
"<number>1.23</number>\n",
"<number>1.23</number>",
},
{ /* 4 */
"SimpleTypes-5",
null,
"<null/>",
"<null/>\n",
"<null/>",
},
{ /* 5 */
"Arrays-1",
new String[]{"foo"},
"<array><string>foo</string></array>",
"<array>\n\t<string>foo</string>\n</array>\n",
"<array><string>foo</string></array>",
},
{ /* 6 */
"Arrays-2",
new String[]{null},
"<array><null/></array>",
"<array>\n\t<null/>\n</array>\n",
"<array><null/></array>",
},
{ /* 7 */
"Arrays-3",
new Object[]{"foo"},
"<array><string>foo</string></array>",
"<array>\n\t<string>foo</string>\n</array>\n",
"<array><string>foo</string></array>",
},
{ /* 8 */
"Arrays-4",
new int[]{123},
"<array><number>123</number></array>",
"<array>\n\t<number>123</number>\n</array>\n",
"<array><number>123</number></array>",
},
{ /* 9 */
"Arrays-5",
new boolean[]{true},
"<array><boolean>true</boolean></array>",
"<array>\n\t<boolean>true</boolean>\n</array>\n",
"<array><boolean>true</boolean></array>",
},
{ /* 10 */
"Arrays-6",
new String[][]{{"foo"}},
"<array><array><string>foo</string></array></array>",
"<array>\n\t<array>\n\t\t<string>foo</string>\n\t</array>\n</array>\n",
"<array><array><string>foo</string></array></array>",
},
{ /* 11 */
"MapWithStrings",
new MapWithStrings().append("k1", "v1").append("k2", null),
"<object><k1>v1</k1><k2 _type='null'/></object>",
"<object>\n\t<k1>v1</k1>\n\t<k2 _type='null'/>\n</object>\n",
"<object><k1>v1</k1><k2 _type='null'/></object>",
},
{ /* 12 */
"MapsWithNumbers",
new MapWithNumbers().append("k1", 123).append("k2", 1.23).append("k3", null),
"<object><k1>123</k1><k2>1.23</k2><k3 _type='null'/></object>",
"<object>\n\t<k1>123</k1>\n\t<k2>1.23</k2>\n\t<k3 _type='null'/>\n</object>\n",
"<object><k1>123</k1><k2>1.23</k2><k3 _type='null'/></object>",
},
{ /* 13 */
"MapWithObjects",
new MapWithObjects().append("k1", "v1").append("k2", 123).append("k3", 1.23).append("k4", true).append("k5", null),
"<object><k1>v1</k1><k2 _type='number'>123</k2><k3 _type='number'>1.23</k3><k4 _type='boolean'>true</k4><k5 _type='null'/></object>",
"<object>\n\t<k1>v1</k1>\n\t<k2 _type='number'>123</k2>\n\t<k3 _type='number'>1.23</k3>\n\t<k4 _type='boolean'>true</k4>\n\t<k5 _type='null'/>\n</object>\n",
"<object><k1>v1</k1><k2 _type='number'>123</k2><k3 _type='number'>1.23</k3><k4 _type='boolean'>true</k4><k5 _type='null'/></object>",
},
{ /* 14 */
"ListWithStrings",
new ListWithStrings().append("foo").append(null),
"<array><string>foo</string><null/></array>",
"<array>\n\t<string>foo</string>\n\t<null/>\n</array>\n",
"<array><string>foo</string><null/></array>",
},
{ /* 15 */
"ListWithNumbers",
new ListWithNumbers().append(123).append(1.23).append(null),
"<array><number>123</number><number>1.23</number><null/></array>",
"<array>\n\t<number>123</number>\n\t<number>1.23</number>\n\t<null/>\n</array>\n",
"<array><number>123</number><number>1.23</number><null/></array>",
},
{ /* 16 */
"ListWithObjects",
new ListWithObjects().append("foo").append(123).append(1.23).append(true).append(null),
"<array><string>foo</string><number>123</number><number>1.23</number><boolean>true</boolean><null/></array>",
"<array>\n\t<string>foo</string>\n\t<number>123</number>\n\t<number>1.23</number>\n\t<boolean>true</boolean>\n\t<null/>\n</array>\n",
"<array><string>foo</string><number>123</number><number>1.23</number><boolean>true</boolean><null/></array>",
},
{ /* 17 */
"BeanWithNormalProperties",
new BeanWithNormalProperties().init(),
"<object>"
+"<a>foo</a>"
+"<b>123</b>"
+"<c>bar</c>"
+"<d _type='number'>456</d>"
+"<e>"
+"<h>qux</h>"
+"</e>"
+"<f>"
+"<string>baz</string>"
+"</f>"
+"<g>"
+"<number>789</number>"
+"</g>"
+"</object>",
"<object>"
+"\n\t<a>foo</a>"
+"\n\t<b>123</b>"
+"\n\t<c>bar</c>"
+"\n\t<d _type='number'>456</d>"
+"\n\t<e>"
+"\n\t\t<h>qux</h>"
+"\n\t</e>"
+"\n\t<f>"
+"\n\t\t<string>baz</string>"
+"\n\t</f>"
+"\n\t<g>"
+"\n\t\t<number>789</number>"
+"\n\t</g>"
+"\n</object>\n",
"<object>"
+"<a>foo</a>"
+"<b>123</b>"
+"<c>bar</c>"
+"<d _type='number'>456</d>"
+"<e>"
+"<h>qux</h>"
+"</e>"
+"<f>"
+"<string>baz</string>"
+"</f>"
+"<g>"
+"<number>789</number>"
+"</g>"
+"</object>",
},
{ /* 18 */
"BeanWithMapProperties",
new BeanWithMapProperties().init(),
"<object>"
+"<a>"
+"<k1>foo</k1>"
+"</a>"
+"<b>"
+"<k2>123</k2>"
+"</b>"
+"<c>"
+"<k3>bar</k3>"
+"<k4 _type='number'>456</k4>"
+"<k5 _type='boolean'>true</k5>"
+"<k6 _type='null'/>"
+"</c>"
+"</object>",
"<object>"
+"\n\t<a>"
+"\n\t\t<k1>foo</k1>"
+"\n\t</a>"
+"\n\t<b>"
+"\n\t\t<k2>123</k2>"
+"\n\t</b>"
+"\n\t<c>"
+"\n\t\t<k3>bar</k3>"
+"\n\t\t<k4 _type='number'>456</k4>"
+"\n\t\t<k5 _type='boolean'>true</k5>"
+"\n\t\t<k6 _type='null'/>"
+"\n\t</c>"
+"\n</object>\n",
"<object>"
+"<a>"
+"<k1>foo</k1>"
+"</a>"
+"<b>"
+"<k2>123</k2>"
+"</b>"
+"<c>"
+"<k3>bar</k3>"
+"<k4 _type='number'>456</k4>"
+"<k5 _type='boolean'>true</k5>"
+"<k6 _type='null'/>"
+"</c>"
+"</object>",
},
{ /* 19 */
"BeanWithTypeName",
new BeanWithTypeName().init(),
"<X><a>123</a><b>foo</b></X>",
"<X>\n\t<a>123</a>\n\t<b>foo</b>\n</X>\n",
"<X><a>123</a><b>foo</b></X>",
},
{ /* 20 */
"BeanWithPropertiesWithTypeNames",
new BeanWithPropertiesWithTypeNames().init(),
"<object><B _name='b1'><b>foo</b></B><B _name='b2'><b>foo</b></B></object>",
"<object>\n <B _name='b1'>\n <b>foo</b>\n </B>\n <B _name='b2'>\n <b>foo</b>\n </B>\n</object>\n",
"<object><B _name='b1'><b>foo</b></B><B _name='b2'><b>foo</b></B></object>"
},
{ /* 21 */
"BeanWithPropertiesWithArrayTypeNames",
new BeanWithPropertiesWithArrayTypeNames().init(),
"<object>"
+"<b1>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</b1>"
+"<b2>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</b2>"
+"<b3>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</b3>"
+"</object>",
"<object>\n"
+"\t<b1>\n"
+"\t\t<B>\n"
+"\t\t\t<b>foo</b>\n"
+"\t\t</B>\n"
+"\t</b1>\n"
+"\t<b2>\n"
+"\t\t<B>\n"
+"\t\t\t<b>foo</b>\n"
+"\t\t</B>\n"
+"\t</b2>\n"
+"\t<b3>\n"
+"\t\t<B>\n"
+"\t\t\t<b>foo</b>\n"
+"\t\t</B>\n"
+"\t</b3>\n"
+"</object>\n",
"<object>"
+"<b1>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</b1>"
+"<b2>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</b2>"
+"<b3>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</b3>"
+"</object>",
},
{ /* 22 */
"BeanWithPropertiesWithArray2dTypeNames",
new BeanWithPropertiesWith2dArrayTypeNames().init(),
"<object>"
+"<b1>"
+"<array>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</array>"
+"</b1>"
+"<b2>"
+"<array>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</array>"
+"</b2>"
+"<b3>"
+"<array>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</array>"
+"</b3>"
+"</object>",
"<object>\n"
+"\t<b1>\n"
+"\t\t<array>\n"
+"\t\t\t<B>\n"
+"\t\t\t\t<b>foo</b>\n"
+"\t\t\t</B>\n"
+"\t\t</array>\n"
+"\t</b1>\n"
+"\t<b2>\n"
+"\t\t<array>\n"
+"\t\t\t<B>\n"
+"\t\t\t\t<b>foo</b>\n"
+"\t\t\t</B>\n"
+"\t\t</array>\n"
+"\t</b2>\n"
+"\t<b3>\n"
+"\t\t<array>\n"
+"\t\t\t<B>\n"
+"\t\t\t\t<b>foo</b>\n"
+"\t\t\t</B>\n"
+"\t\t</array>\n"
+"\t</b3>\n"
+"</object>\n",
"<object>"
+"<b1>"
+"<array>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</array>"
+"</b1>"
+"<b2>"
+"<array>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</array>"
+"</b2>"
+"<b3>"
+"<array>"
+"<B>"
+"<b>foo</b>"
+"</B>"
+"</array>"
+"</b3>"
+"</object>",
},
{ /* 23 */
"BeanWithPropertiesWithMapTypeNames",
new BeanWithPropertiesWithMapTypeNames().init(),
"<object>"
+"<b1>"
+"<B _name='k1'>"
+"<b>foo</b>"
+"</B>"
+"</b1>"
+"<b2>"
+"<B _name='k2'>"
+"<b>foo</b>"
+"</B>"
+"</b2>"
+"</object>",
"<object>\n"
+"\t<b1>\n"
+"\t\t<B _name='k1'>\n"
+"\t\t\t<b>foo</b>\n"
+"\t\t</B>\n"
+"\t</b1>\n"
+"\t<b2>\n"
+"\t\t<B _name='k2'>\n"
+"\t\t\t<b>foo</b>\n"
+"\t\t</B>\n"
+"\t</b2>\n"
+"</object>\n",
"<object>"
+"<b1>"
+"<B _name='k1'>"
+"<b>foo</b>"
+"</B>"
+"</b1>"
+"<b2>"
+"<B _name='k2'>"
+"<b>foo</b>"
+"</B>"
+"</b2>"
+"</object>",
},
{ /* 24 */
"BeanWithChildTypeNames",
new BeanWithChildTypeNames().init(),
"<object>"
+"<X _name='a'>"
+"<fx>fx1</fx>"
+"</X>"
+"<X _name='b'>"
+"<fx>fx1</fx>"
+"</X>"
+"<c>"
+"<X>"
+"<fx>fx1</fx>"
+"</X>"
+"</c>"
+"<d>"
+"<X>"
+"<fx>fx1</fx>"
+"</X>"
+"</d>"
+"</object>",
"<object>"
+"\n\t<X _name='a'>"
+"\n\t\t<fx>fx1</fx>"
+"\n\t</X>"
+"\n\t<X _name='b'>"
+"\n\t\t<fx>fx1</fx>"
+"\n\t</X>"
+"\n\t<c>"
+"\n\t\t<X>"
+"\n\t\t\t<fx>fx1</fx>"
+"\n\t\t</X>"
+"\n\t</c>"
+"\n\t<d>"
+"\n\t\t<X>"
+"\n\t\t\t<fx>fx1</fx>"
+"\n\t\t</X>"
+"\n\t</d>"
+"\n</object>\n",
"<object>"
+"<X _name='a'>"
+"<fx>fx1</fx>"
+"</X>"
+"<X _name='b'>"
+"<fx>fx1</fx>"
+"</X>"
+"<c>"
+"<X>"
+"<fx>fx1</fx>"
+"</X>"
+"</c>"
+"<d>"
+"<X>"
+"<fx>fx1</fx>"
+"</X>"
+"</d>"
+"</object>",
},
{ /* 25 */
"BeanWithChildName",
new BeanWithChildName().init(),
"<object><a><X>foo</X><X>bar</X></a><b><Y>123</Y><Y>456</Y></b></object>",
"<object>\n\t<a>\n\t\t<X>foo</X>\n\t\t<X>bar</X>\n\t</a>\n\t<b>\n\t\t<Y>123</Y>\n\t\t<Y>456</Y>\n\t</b>\n</object>\n",
"<object><a><X>foo</X><X>bar</X></a><b><Y>123</Y><Y>456</Y></b></object>",
},
{ /* 26 */
"BeanWithXmlFormatAttrProperty",
new BeanWithXmlFormatAttrProperty().init(),
"<object a='foo' b='123'/>",
"<object a='foo' b='123'/>\n",
"<object a='foo' b='123'/>",
},
{ /* 27 */
"BeanWithXmlFormatAttrs",
new BeanWithXmlFormatAttrs().init(),
"<object a='foo' b='123'/>",
"<object a='foo' b='123'/>\n",
"<object a='foo' b='123'/>",
},
{ /* 28 */
"BeanWithXmlFormatElementProperty",
new BeanWithXmlFormatElementProperty().init(),
"<object a='foo'><b>123</b></object>",
"<object a='foo'>\n\t<b>123</b>\n</object>\n",
"<object a='foo'><b>123</b></object>",
},
{ /* 29 */
"BeanWithXmlFormatAttrsProperty",
new BeanWithXmlFormatAttrsProperty().init(),
"<object k1='foo' k2='123' b='456'/>",
"<object k1='foo' k2='123' b='456'/>\n",
"<object k1='foo' k2='123' b='456'/>",
},
{ /* 30 */
"BeanWithXmlFormatCollapsedProperty",
new BeanWithXmlFormatCollapsedProperty().init(),
"<object><A>foo</A><A>bar</A><B>123</B><B>456</B></object>",
"<object>\n\t<A>foo</A>\n\t<A>bar</A>\n\t<B>123</B>\n\t<B>456</B>\n</object>\n",
"<object><A>foo</A><A>bar</A><B>123</B><B>456</B></object>",
},
{ /* 31 */
"BeanWithXmlFormatTextProperty",
new BeanWithXmlFormatTextProperty().init(),
"<object a='foo'>bar</object>",
"<object a='foo'>bar</object>\n",
"<object a='foo'>bar</object>",
},
{ /* 32 */
"BeanWithXmlFormatXmlTextProperty",
new BeanWithXmlFormatXmlTextProperty().init(),
"<object a='foo'>bar<b>baz</b>qux</object>",
"<object a='foo'>bar<b>baz</b>qux</object>\n",
"<object a='foo'>bar<b>baz</b>qux</object>",
},
{ /* 33 */
"BeanWithXmlFormatElementsPropertyCollection",
new BeanWithXmlFormatElementsPropertyCollection().init(),
"<object a='foo'><string>bar</string><string>baz</string><number>123</number><boolean>true</boolean><null/></object>",
"<object a='foo'>\n\t<string>bar</string>\n\t<string>baz</string>\n\t<number>123</number>\n\t<boolean>true</boolean>\n\t<null/>\n</object>\n",
"<object a='foo'><string>bar</string><string>baz</string><number>123</number><boolean>true</boolean><null/></object>",
},
{ /* 34 */
"BeanWithMixedContent",
new BeanWithMixedContent().init(),
"<object>foo<X fx='fx1'/>bar<Y fy='fy1'/>baz</object>",
"<object>foo<X fx='fx1'/>bar<Y fy='fy1'/>baz</object>\n", // Mixed content doesn't use whitespace!
"<object>foo<X fx='fx1'/>bar<Y fy='fy1'/>baz</object>",
},
{ /* 35 */
"BeanWithSpecialCharacters",
new BeanWithSpecialCharacters().init(),
"<object><a>_x0020_ _x0008__x000C_
	
 _x0020_</a></object>",
"<object>\n\t<a>_x0020_ _x0008__x000C_
	
 _x0020_</a>\n</object>\n",
"<object><a>_x0020_ _x0008__x000C_
	
 _x0020_</a></object>"
},
{ /* 36 */
"BeanWithSpecialCharacters2",
new BeanWithSpecialCharacters2().init(),
"<_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_><_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>_x0020_ _x0008__x000C_
	
 _x0020_</_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_></_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>",
"<_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>\n\t<_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>_x0020_ _x0008__x000C_
	
 _x0020_</_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>\n</_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>\n",
"<_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_><_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>_x0020_ _x0008__x000C_
	
 _x0020_</_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_></_x0020__x0020__x0008__x000C__x000A__x0009__x000D__x0020__x0020_>"
},
{ /* 37 */
"BeanWithNullProperties",
new BeanWithNullProperties(),
"<object/>",
"<object/>\n",
"<object/>"
},
{ /* 38 */
"BeanWithAbstractFields",
new BeanWithAbstractFields().init(),
"<object>"
+"<A _name='a'>"
+"<a>foo</a>"
+"</A>"
+"<A _name='ia'>"
+"<a>foo</a>"
+"</A>"
+"<A _name='aa'>"
+"<a>foo</a>"
+"</A>"
+"<A _name='o'>"
+"<a>foo</a>"
+"</A>"
+"</object>",
"<object>\n"
+"\t<A _name='a'>\n"
+"\t\t<a>foo</a>\n"
+"\t</A>\n"
+"\t<A _name='ia'>\n"
+"\t\t<a>foo</a>\n"
+"\t</A>\n"
+"\t<A _name='aa'>\n"
+"\t\t<a>foo</a>\n"
+"\t</A>\n"
+"\t<A _name='o'>\n"
+"\t\t<a>foo</a>\n"
+"\t</A>\n"
+"</object>\n",
"<object>"
+"<A _name='a'>"
+"<a>foo</a>"
+"</A>"
+"<A _name='ia'>"
+"<a>foo</a>"
+"</A>"
+"<A _name='aa'>"
+"<a>foo</a>"
+"</A>"
+"<A _name='o'>"
+"<a>foo</a>"
+"</A>"
+"</object>",
},
{ /* 39 */
"BeanWithAbstractArrayFields",
new BeanWithAbstractArrayFields().init(),
"<object>"
+"<a>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</a>"
+"<ia1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia1>"
+"<ia2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia2>"
+"<aa1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa1>"
+"<aa2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa2>"
+"<o1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o1>"
+"<o2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o2>"
+"</object>",
"<object>\n"
+"\t<a>\n"
+"\t\t<A>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</a>\n"
+"\t<ia1>\n"
+"\t\t<A>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</ia1>\n"
+"\t<ia2>\n"
+"\t\t<A>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</ia2>\n"
+"\t<aa1>\n"
+"\t\t<A>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</aa1>\n"
+"\t<aa2>\n"
+"\t\t<A>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</aa2>\n"
+"\t<o1>\n"
+"\t\t<A>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</o1>\n"
+"\t<o2>\n"
+"\t\t<A>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</o2>\n"
+"</object>\n",
"<object>"
+"<a>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</a>"
+"<ia1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia1>"
+"<ia2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia2>"
+"<aa1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa1>"
+"<aa2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa2>"
+"<o1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o1>"
+"<o2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o2>"
+"</object>",
},
{ /* 40 */
"BeanWithAbstractMapFields",
new BeanWithAbstractMapFields().init(),
"<object>"
+"<a>"
+"<A _name='k1'>"
+"<a>foo</a>"
+"</A>"
+"</a>"
+"<b>"
+"<A _name='k2'>"
+"<a>foo</a>"
+"</A>"
+"</b>"
+"<c>"
+"<A _name='k3'>"
+"<a>foo</a>"
+"</A>"
+"</c>"
+"</object>",
"<object>\n"
+"\t<a>\n"
+"\t\t<A _name='k1'>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</a>\n"
+"\t<b>\n"
+"\t\t<A _name='k2'>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</b>\n"
+"\t<c>\n"
+"\t\t<A _name='k3'>\n"
+"\t\t\t<a>foo</a>\n"
+"\t\t</A>\n"
+"\t</c>\n"
+"</object>\n",
"<object>"
+"<a>"
+"<A _name='k1'>"
+"<a>foo</a>"
+"</A>"
+"</a>"
+"<b>"
+"<A _name='k2'>"
+"<a>foo</a>"
+"</A>"
+"</b>"
+"<c>"
+"<A _name='k3'>"
+"<a>foo</a>"
+"</A>"
+"</c>"
+"</object>",
},
{ /* 41 */
"BeanWithAbstractMapArrayFields",
new BeanWithAbstractMapArrayFields().init(),
"<object>"
+"<a>"
+"<a1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</a1>"
+"</a>"
+"<ia>"
+"<ia1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia1>"
+"<ia2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia2>"
+"</ia>"
+"<aa>"
+"<aa1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa1>"
+"<aa2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa2>"
+"</aa>"
+"<o>"
+"<o1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o1>"
+"<o2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o2>"
+"</o>"
+"</object>",
"<object>\n"
+"\t<a>\n"
+"\t\t<a1>\n"
+"\t\t\t<A>\n"
+"\t\t\t\t<a>foo</a>\n"
+"\t\t\t</A>\n"
+"\t\t</a1>\n"
+"\t</a>\n"
+"\t<ia>\n"
+"\t\t<ia1>\n"
+"\t\t\t<A>\n"
+"\t\t\t\t<a>foo</a>\n"
+"\t\t\t</A>\n"
+"\t\t</ia1>\n"
+"\t\t<ia2>\n"
+"\t\t\t<A>\n"
+"\t\t\t\t<a>foo</a>\n"
+"\t\t\t</A>\n"
+"\t\t</ia2>\n"
+"\t</ia>\n"
+"\t<aa>\n"
+"\t\t<aa1>\n"
+"\t\t\t<A>\n"
+"\t\t\t\t<a>foo</a>\n"
+"\t\t\t</A>\n"
+"\t\t</aa1>\n"
+"\t\t<aa2>\n"
+"\t\t\t<A>\n"
+"\t\t\t\t<a>foo</a>\n"
+"\t\t\t</A>\n"
+"\t\t</aa2>\n"
+"\t</aa>\n"
+"\t<o>\n"
+"\t\t<o1>\n"
+"\t\t\t<A>\n"
+"\t\t\t\t<a>foo</a>\n"
+"\t\t\t</A>\n"
+"\t\t</o1>\n"
+"\t\t<o2>\n"
+"\t\t\t<A>\n"
+"\t\t\t\t<a>foo</a>\n"
+"\t\t\t</A>\n"
+"\t\t</o2>\n"
+"\t</o>\n"
+"</object>\n",
"<object>"
+"<a>"
+"<a1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</a1>"
+"</a>"
+"<ia>"
+"<ia1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia1>"
+"<ia2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</ia2>"
+"</ia>"
+"<aa>"
+"<aa1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa1>"
+"<aa2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</aa2>"
+"</aa>"
+"<o>"
+"<o1>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o1>"
+"<o2>"
+"<A>"
+"<a>foo</a>"
+"</A>"
+"</o2>"
+"</o>"
+"</object>",
},
{ /* 42 */
"BeanWithWhitespaceTextFields-1",
new BeanWithWhitespaceTextFields().init(null),
"<object nil='true'></object>",
"<object nil='true'>\n</object>\n",
"<object nil='true'></object>",
},
{ /* 43 */
"BeanWithWhitespaceTextFields-2",
new BeanWithWhitespaceTextFields().init(""),
"<object>_xE000_</object>",
"<object>_xE000_</object>\n",
"<object>_xE000_</object>",
},
{ /* 44 */
"BeanWithWhitespaceTextFields-3",
new BeanWithWhitespaceTextFields().init(" "),
"<object>_x0020_</object>",
"<object>_x0020_</object>\n",
"<object>_x0020_</object>",
},
{ /* 45 */
"BeanWithWhitespaceTextFields-4",
new BeanWithWhitespaceTextFields().init(" "),
"<object>_x0020__x0020_</object>",
"<object>_x0020__x0020_</object>\n",
"<object>_x0020__x0020_</object>",
},
{ /* 46 */
"BeanWithWhitespaceTextFields-5",
new BeanWithWhitespaceTextFields().init(" foo\n\tbar "),
"<object>_x0020_foo
	bar_x0020_</object>",
"<object>_x0020_foo
	bar_x0020_</object>\n",
"<object>_x0020_foo
	bar_x0020_</object>",
},
{ /* 47 */
"BeanWithWhitespaceTextPwsFields-1",
new BeanWithWhitespaceTextPwsFields().init(null),
"<object nil='true'></object>",
"<object nil='true'>\n</object>\n",
"<object nil='true'></object>",
},
{ /* 48 */
"BeanWithWhitespaceTextPwsFields-2",
new BeanWithWhitespaceTextPwsFields().init(""),
"<object>_xE000_</object>",
"<object>_xE000_</object>\n",
"<object>_xE000_</object>",
},
{ /* 49 */
"BeanWithWhitespaceTextPwsFields-3",
new BeanWithWhitespaceTextPwsFields().init(" "),
"<object> </object>",
"<object> </object>\n",
"<object> </object>",
},
{ /* 50 */
"BeanWithWhitespaceTextPwsFields-4",
new BeanWithWhitespaceTextPwsFields().init(" "),
"<object> </object>",
"<object> </object>\n",
"<object> </object>",
},
{ /* 51 */
"BeanWithWhitespaceTextPwsFields-5",
new BeanWithWhitespaceTextPwsFields().init(" foobar "),
"<object> foobar </object>",
"<object> foobar </object>\n",
"<object> foobar </object>",
},
{ /* 52 */
"BeanWithWhitespaceMixedFields-1",
new BeanWithWhitespaceMixedFields().init(null),
"<object nil='true'></object>",
"<object nil='true'>\n</object>\n",
"<object nil='true'></object>",
},
{ /* 53 */
"BeanWithWhitespaceMixedFields-2",
new BeanWithWhitespaceMixedFields().init(new String[0]),
"<object></object>",
"<object></object>\n",
"<object></object>",
},
{ /* 54 */
"BeanWithWhitespaceMixedFields-3",
new BeanWithWhitespaceMixedFields().init(new String[]{""}),
"<object>_xE000_</object>",
"<object>_xE000_</object>\n",
"<object>_xE000_</object>",
},
{ /* 55 */
"BeanWithWhitespaceMixedFields-4",
new BeanWithWhitespaceMixedFields().init(new String[]{" "}),
"<object>_x0020_</object>",
"<object>_x0020_</object>\n",
"<object>_x0020_</object>",
},
{ /* 56 */
"BeanWithWhitespaceMixedFields-5",
new BeanWithWhitespaceMixedFields().init(new String[]{" "}),
"<object>_x0020__x0020_</object>",
"<object>_x0020__x0020_</object>\n",
"<object>_x0020__x0020_</object>",
},
{ /* 57 */
"BeanWithWhitespaceMixedFields-6",
new BeanWithWhitespaceMixedFields().init(new String[]{" foobar "}),
"<object>_x0020_ foobar _x0020_</object>",
"<object>_x0020_ foobar _x0020_</object>\n",
"<object>_x0020_ foobar _x0020_</object>",
},
{ /* 58 */
"BeanWithWhitespaceMixedPwsFields-1",
new BeanWithWhitespaceMixedPwsFields().init(null),
"<object nil='true'></object>",
"<object nil='true'>\n</object>\n",
"<object nil='true'></object>",
},
{ /* 59 */
"BeanWithWhitespaceMixedPwsFields-2",
new BeanWithWhitespaceMixedPwsFields().init(new String[0]),
"<object></object>",
"<object></object>\n",
"<object></object>",
},
{ /* 60 */
"BeanWithWhitespaceMixedPwsFields-3",
new BeanWithWhitespaceMixedPwsFields().init(new String[]{""}),
"<object>_xE000_</object>",
"<object>_xE000_</object>\n",
"<object>_xE000_</object>",
},
{ /* 61 */
"BeanWithWhitespaceMixedPwsFields-4",
new BeanWithWhitespaceMixedPwsFields().init(new String[]{" "}),
"<object> </object>",
"<object> </object>\n",
"<object> </object>",
},
{ /* 62 */
"BeanWithWhitespaceMixedPwsFields-5",
new BeanWithWhitespaceMixedPwsFields().init(new String[]{" "}),
"<object> </object>",
"<object> </object>\n",
"<object> </object>",
},
{ /* 63 */
"BeanWithWhitespaceMixedPwsFields-6",
new BeanWithWhitespaceMixedPwsFields().init(new String[]{" foobar "}),
"<object> foobar </object>",
"<object> foobar </object>\n",
"<object> foobar </object>",
},
});
}
private String label, e1, e2, e3;
private Object in;
public BasicXmlTest(String label, Object in, String e1, String e2, String e3) throws Exception {
this.label = label;
this.in = in;
this.e1 = e1;
this.e2 = e2;
this.e3 = e3;
}
@Test
public void serializeNormal() {
try {
String r = s1.serialize(in);
assertEquals(label + " serialize-normal failed", e1, r);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(label + " test failed", e);
}
}
@Test
public void parseNormal() {
try {
String r = s1.serialize(in);
Class<?> c = in == null ? Object.class : in.getClass();
Object o = parser.parse(r, c);
r = s1.serialize(o);
assertEquals(label + " parse-normal failed", e1, r);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(label + " test failed", e);
}
}
@Test
public void serializeReadable() {
try {
String r = s2.serialize(in);
assertEquals(label + " serialize-readable failed", e2, r);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(label + " test failed", e);
}
}
@Test
public void parseReadable() {
try {
String r = s2.serialize(in);
Class<?> c = in == null ? Object.class : in.getClass();
Object o = parser.parse(r, c);
r = s2.serialize(o);
assertEquals(label + " parse-readable failed", e2, r);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(label + " test failed", e);
}
}
@Test
public void serializeNsEnabled() {
try {
String r = s3.serialize(in);
assertEquals(label + " serialize-ns-enabled failed", e3, r);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(label + " test failed", e);
}
}
@Test
public void parseNsEnabled() {
try {
String r = s3.serialize(in);
Class<?> c = in == null ? Object.class : in.getClass();
Object o = parser.parse(r, c);
r = s3.serialize(o);
assertEquals(label + " parse-ns-enabled failed", e3, r);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(label + " test failed", e);
}
}
//-----------------------------------------------------------------------------------------------------------------
// Test beans
//-----------------------------------------------------------------------------------------------------------------
public static class MapWithStrings extends LinkedHashMap<String,String> {
public MapWithStrings append(String key, String value) {
put(key, value);
return this;
}
}
public static class MapWithNumbers extends LinkedHashMap<String,Number> {
public MapWithNumbers append(String key, Number value) {
put(key, value);
return this;
}
}
public static class MapWithObjects extends LinkedHashMap<String,Object> {
public MapWithObjects append(String key, Object value) {
put(key, value);
return this;
}
}
public static class ListWithStrings extends ArrayList<String> {
public ListWithStrings append(String value) {
this.add(value);
return this;
}
}
public static class ListWithNumbers extends ArrayList<Number> {
public ListWithNumbers append(Number value) {
this.add(value);
return this;
}
}
public static class ListWithObjects extends ArrayList<Object> {
public ListWithObjects append(Object value) {
this.add(value);
return this;
}
}
public static class BeanWithNormalProperties {
public String a;
public int b;
public Object c;
public Object d;
public Bean1a e;
public String[] f;
public int[] g;
BeanWithNormalProperties init() {
a = "foo";
b = 123;
c = "bar";
d = 456;
e = new Bean1a().init();
f = new String[]{ "baz" };
g = new int[]{ 789 };
return this;
}
}
public static class Bean1a {
public String h;
Bean1a init() {
h = "qux";
return this;
}
}
public static class BeanWithMapProperties {
@Beanp(type=MapWithStrings.class)
public Map<String,String> a;
@Beanp(type=MapWithNumbers.class)
public Map<String,Number> b;
@Beanp(type=MapWithObjects.class)
public Map<String,Object> c;
BeanWithMapProperties init() {
a = new MapWithStrings().append("k1","foo");
b = new MapWithNumbers().append("k2",123);
c = new MapWithObjects().append("k3","bar").append("k4",456).append("k5",true).append("k6",null);
return this;
}
}
@Bean(typeName="X")
public static class BeanWithTypeName {
public int a;
public String b;
BeanWithTypeName init() {
a = 123;
b = "foo";
return this;
}
}
@Bean(dictionary={B.class})
public static class BeanWithPropertiesWithTypeNames {
public B b1;
public Object b2;
BeanWithPropertiesWithTypeNames init() {
b1 = new B().init();
b2 = new B().init();
return this;
}
}
@Bean(dictionary={B.class})
public static class BeanWithPropertiesWithArrayTypeNames {
public B[] b1;
public Object[] b2;
public Object[] b3;
BeanWithPropertiesWithArrayTypeNames init() {
b1 = new B[]{new B().init()};
b2 = new B[]{new B().init()};
b3 = new Object[]{new B().init()};
return this;
}
}
@Bean(dictionary={B.class})
public static class BeanWithPropertiesWith2dArrayTypeNames {
public B[][] b1;
public Object[][] b2;
public Object[][] b3;
BeanWithPropertiesWith2dArrayTypeNames init() {
b1 = new B[][]{{new B().init()}};
b2 = new B[][]{{new B().init()}};
b3 = new Object[][]{{new B().init()}};
return this;
}
}
@Bean(dictionary={B.class})
public static class BeanWithPropertiesWithMapTypeNames {
public Map<String,B> b1;
public Map<String,Object> b2;
BeanWithPropertiesWithMapTypeNames init() {
b1 = new HashMap<>();
b1.put("k1", new B().init());
b2 = new HashMap<>();
b2.put("k2", new B().init());
return this;
}
}
@Bean(typeName="B")
public static class B {
public String b;
B init() {
b = "foo";
return this;
}
}
public static class BeanWithChildTypeNames {
public BeanX a;
@Beanp(dictionary=BeanX.class)
public Object b;
public BeanX[] c;
@Beanp(dictionary=BeanX.class)
public Object[] d;
BeanWithChildTypeNames init() {
a = new BeanX().init();
b = new BeanX().init();
c = new BeanX[]{new BeanX().init()};
d = new Object[]{new BeanX().init()};
return this;
}
}
public static class BeanWithChildName {
@Xml(childName = "X")
public String[] a;
@Xml(childName = "Y")
public int[] b;
BeanWithChildName init() {
a = new String[] { "foo", "bar" };
b = new int[] { 123, 456 };
return this;
}
}
public static class BeanWithXmlFormatAttrProperty {
@Xml(format=XmlFormat.ATTR)
public String a;
@Xml(format=XmlFormat.ATTR)
public int b;
BeanWithXmlFormatAttrProperty init() {
a = "foo";
b = 123;
return this;
}
}
@Xml(format=XmlFormat.ATTRS)
public static class BeanWithXmlFormatAttrs {
public String a;
public int b;
BeanWithXmlFormatAttrs init() {
a = "foo";
b = 123;
return this;
}
}
@Xml(format=XmlFormat.ATTRS)
public static class BeanWithXmlFormatElementProperty {
public String a;
@Xml(format=XmlFormat.ELEMENT)
public int b;
BeanWithXmlFormatElementProperty init() {
a = "foo";
b = 123;
return this;
}
}
public static class BeanWithXmlFormatAttrsProperty {
@Xml(format=XmlFormat.ATTRS)
public Map<String,Object> a;
@Xml(format=XmlFormat.ATTR)
public int b;
BeanWithXmlFormatAttrsProperty init() {
a = OMap.of("k1", "foo", "k2", 123);
b = 456;
return this;
}
}
public static class BeanWithXmlFormatCollapsedProperty {
@Xml(childName="A",format=XmlFormat.COLLAPSED)
public String[] a;
@Xml(childName="B",format=XmlFormat.COLLAPSED)
public int[] b;
BeanWithXmlFormatCollapsedProperty init() {
a = new String[]{"foo","bar"};
b = new int[]{123,456};
return this;
}
}
public static class BeanWithXmlFormatTextProperty {
@Xml(format=XmlFormat.ATTR)
public String a;
@Xml(format=XmlFormat.TEXT)
public String b;
BeanWithXmlFormatTextProperty init() {
a = "foo";
b = "bar";
return this;
}
}
public static class BeanWithXmlFormatXmlTextProperty {
@Xml(format=XmlFormat.ATTR)
public String a;
@Xml(format=XmlFormat.XMLTEXT)
public String b;
BeanWithXmlFormatXmlTextProperty init() {
a = "foo";
b = "bar<b>baz</b>qux";
return this;
}
}
public static class BeanWithXmlFormatElementsPropertyCollection {
@Xml(format=XmlFormat.ATTR)
public String a;
@Xml(format=XmlFormat.ELEMENTS)
public Object[] b;
BeanWithXmlFormatElementsPropertyCollection init() {
a = "foo";
b = new Object[]{"bar","baz",123,true,null};
return this;
}
}
public static class BeanWithMixedContent {
@Xml(format=XmlFormat.MIXED)
@Beanp(dictionary={BeanXSimple.class, BeanYSimple.class})
public Object[] a;
BeanWithMixedContent init() {
a = new Object[]{
"foo",
new BeanXSimple().init(),
"bar",
new BeanYSimple().init(),
"baz"
};
return this;
}
}
@Bean(typeName="X")
public static class BeanX {
public String fx;
BeanX init() {
fx = "fx1";
return this;
}
}
@Bean(typeName="X")
public static class BeanXSimple {
@Xml(format=XmlFormat.ATTR)
public String fx;
BeanXSimple init() {
fx = "fx1";
return this;
}
}
@Bean(typeName="Y")
public static class BeanY {
public String fy;
BeanY init() {
fy = "fy1";
return this;
}
}
@Bean(typeName="Y")
public static class BeanYSimple {
@Xml(format=XmlFormat.ATTR)
public String fy;
BeanYSimple init() {
fy = "fy1";
return this;
}
}
public static class BeanWithSpecialCharacters {
public String a;
BeanWithSpecialCharacters init() {
a = " \b\f\n\t\r ";
return this;
}
}
@Bean(typeName=" \b\f\n\t\r ")
public static class BeanWithSpecialCharacters2 {
@Beanp(name=" \b\f\n\t\r ")
public String a;
BeanWithSpecialCharacters2 init() {
a = " \b\f\n\t\r ";
return this;
}
}
public static class BeanWithNullProperties {
public String a;
public String[] b;
}
@Bean(dictionary={A.class},p="a,ia,aa,o")
public static class BeanWithAbstractFields {
public A a;
public IA ia;
public AA aa;
public Object o;
BeanWithAbstractFields init() {
ia = new A().init();
aa = new A().init();
a = new A().init();
o = new A().init();
return this;
}
}
@Bean(dictionary={A.class},p="a,ia1,ia2,aa1,aa2,o1,o2")
public static class BeanWithAbstractArrayFields {
public A[] a;
public IA[] ia1, ia2;
public AA[] aa1, aa2;
public Object[] o1, o2;
BeanWithAbstractArrayFields init() {
a = new A[]{new A().init()};
ia1 = new A[]{new A().init()};
aa1 = new A[]{new A().init()};
o1 = new A[]{new A().init()};
ia2 = new IA[]{new A().init()};
aa2 = new AA[]{new A().init()};
o2 = new Object[]{new A().init()};
return this;
}
}
@Bean(dictionary={A.class})
public static class BeanWithAbstractMapFields {
public Map<String,A> a;
public Map<String,AA> b;
public Map<String,Object> c;
BeanWithAbstractMapFields init() {
a = new HashMap<>();
b = new HashMap<>();
c = new HashMap<>();
a.put("k1", new A().init());
b.put("k2", new A().init());
c.put("k3", new A().init());
return this;
}
}
@Bean(dictionary={A.class},p="a,ia,aa,o")
public static class BeanWithAbstractMapArrayFields {
public Map<String,A[]> a;
public Map<String,IA[]> ia;
public Map<String,AA[]> aa;
public Map<String,Object[]> o;
BeanWithAbstractMapArrayFields init() {
a = new LinkedHashMap<>();
ia = new LinkedHashMap<>();
aa = new LinkedHashMap<>();
o = new LinkedHashMap<>();
a.put("a1", new A[]{new A().init()});
ia.put("ia1", new A[]{new A().init()});
ia.put("ia2", new IA[]{new A().init()});
aa.put("aa1", new A[]{new A().init()});
aa.put("aa2", new AA[]{new A().init()});
o.put("o1", new A[]{new A().init()});
o.put("o2", new Object[]{new A().init()});
return this;
}
}
public static interface IA {
public String getA();
public void setA(String a);
}
public static abstract class AA implements IA {}
@Bean(typeName="A")
public static class A extends AA {
private String a;
@Override
public String getA() {
return a;
}
@Override
public void setA(String a) {
this.a = a;
}
A init() {
this.a = "foo";
return this;
}
}
public static class BeanWithWhitespaceTextFields {
@Xml(format=XmlFormat.TEXT)
public String a;
public BeanWithWhitespaceTextFields init(String s) {
a = s;
return this;
}
}
public static class BeanWithWhitespaceTextPwsFields {
@Xml(format=XmlFormat.TEXT_PWS)
public String a;
public BeanWithWhitespaceTextPwsFields init(String s) {
a = s;
return this;
}
}
public static class BeanWithWhitespaceMixedFields {
@Xml(format=XmlFormat.MIXED)
public String[] a;
public BeanWithWhitespaceMixedFields init(String[] s) {
a = s;
return this;
}
}
public static class BeanWithWhitespaceMixedPwsFields {
@Xml(format=XmlFormat.MIXED_PWS)
public String[] a;
public BeanWithWhitespaceMixedPwsFields init(String[] s) {
a = s;
return this;
}
}
}
|
9230bba60c740089c5bacb64273c5e08267ad1d6 | 40,206 | java | Java | experiments/subjects/math_46/symexe/src/test/org/apache/commons/math/linear/RealVector.java | yannicnoller/hydiff | 4df7df1d2f00bf28d6fb2e2ed7a14103084c39f3 | [
"MIT"
] | 19 | 2020-05-24T11:55:24.000Z | 2022-03-29T08:16:36.000Z | experiments/subjects/math_46/symexe/src/test/org/apache/commons/math/linear/RealVector.java | newthis/hydiff | dd4fe909fb733fdea9f60ce3729a215322c4371a | [
"MIT"
] | 1 | 2022-01-03T11:48:08.000Z | 2022-01-04T01:07:39.000Z | experiments/subjects/math_46/symexe/src/test/org/apache/commons/math/linear/RealVector.java | newthis/hydiff | dd4fe909fb733fdea9f60ce3729a215322c4371a | [
"MIT"
] | 4 | 2020-05-24T11:55:26.000Z | 2021-03-24T02:20:08.000Z | 31.708202 | 92 | 0.548873 | 995,586 | /*
* 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 test.org.apache.commons.math.linear;
import java.util.Iterator;
import java.util.NoSuchElementException;
import test.org.apache.commons.math.analysis.FunctionUtils;
import test.org.apache.commons.math.analysis.UnivariateRealFunction;
import test.org.apache.commons.math.analysis.function.Add;
import test.org.apache.commons.math.analysis.function.Divide;
import test.org.apache.commons.math.analysis.function.Multiply;
import test.org.apache.commons.math.exception.DimensionMismatchException;
import test.org.apache.commons.math.exception.MathArithmeticException;
import test.org.apache.commons.math.exception.MathUnsupportedOperationException;
import test.org.apache.commons.math.exception.OutOfRangeException;
import test.org.apache.commons.math.exception.util.LocalizedFormats;
import test.org.apache.commons.math.util.FastMath;
/**
* Class defining a real-valued vector with basic algebraic operations.
* <p>
* vector element indexing is 0-based -- e.g., {@code getEntry(0)}
* returns the first element of the vector.
* </p>
* <p>
* The {@code code map} and {@code mapToSelf} methods operate
* on vectors element-wise, i.e. they perform the same operation (adding a scalar,
* applying a function ...) on each element in turn. The {@code map}
* versions create a new vector to hold the result and do not change the instance.
* The {@code mapToSelf} version uses the instance itself to store the
* results, so the instance is changed by this method. In all cases, the result
* vector is returned by the methods, allowing the <i>fluent API</i>
* style, like this:
* </p>
* <pre>
* RealVector result = v.mapAddToSelf(3.4).mapToSelf(new Tan()).mapToSelf(new Power(2.3));
* </pre>
*
* @version $Id$
* @since 2.1
*/
public abstract class RealVector {
/**
* Returns the size of the vector.
*
* @return the size of this vector.
*/
public abstract int getDimension();
/**
* Return the entry at the specified index.
*
* @param index Index location of entry to be fetched.
* @return the vector entry at {@code index}.
* @throws test.org.apache.commons.math.exception.OutOfRangeException
* if the index is not valid.
* @see #setEntry(int, double)
*/
public abstract double getEntry(int index);
/**
* Set a single element.
*
* @param index element index.
* @param value new value for the element.
* @throws test.org.apache.commons.math.exception.OutOfRangeException
* if the index is not valid.
* @see #getEntry(int)
*/
public abstract void setEntry(int index, double value);
/**
* Construct a new vector by appending a vector to this vector.
*
* @param v vector to append to this one.
* @return a new vector.
*/
public abstract RealVector append(RealVector v);
/**
* Construct a new vector by appending a double to this vector.
*
* @param d double to append.
* @return a new vector.
*/
public abstract RealVector append(double d);
/**
* Get a subvector from consecutive elements.
*
* @param index index of first element.
* @param n number of elements to be retrieved.
* @return a vector containing n elements.
* @throws test.org.apache.commons.math.exception.OutOfRangeException
* if the index is not valid.
*/
public abstract RealVector getSubVector(int index, int n);
/**
* Set a sequence of consecutive elements.
*
* @param index index of first element to be set.
* @param v vector containing the values to set.
* @throws test.org.apache.commons.math.exception.OutOfRangeException
* if the index is not valid.
*/
public abstract void setSubVector(int index, RealVector v);
/**
* Check whether any coordinate of this vector is {@code NaN}.
*
* @return {@code true} if any coordinate of this vector is {@code NaN},
* {@code false} otherwise.
*/
public abstract boolean isNaN();
/**
* Check whether any coordinate of this vector is infinite and none are {@code NaN}.
*
* @return {@code true} if any coordinate of this vector is infinite and
* none are {@code NaN}, {@code false} otherwise.
*/
public abstract boolean isInfinite();
/**
* Check if instance and specified vectors have the same dimension.
*
* @param v Vector to compare instance with.
* @throws DimensionMismatchException if the vectors do not
* have the same dimension.
*/
protected void checkVectorDimensions(RealVector v) {
checkVectorDimensions(v.getDimension());
}
/**
* Check if instance dimension is equal to some expected value.
*
* @param n Expected dimension.
* @throws DimensionMismatchException if the dimension is
* inconsistent with the vector size.
*/
protected void checkVectorDimensions(int n) {
int d = getDimension();
if (d != n) {
throw new DimensionMismatchException(d, n);
}
}
/**
* Check if an index is valid.
*
* @param index Index to check.
* @exception OutOfRangeException if {@code index} is not valid.
*/
protected void checkIndex(final int index) {
if (index < 0 ||
index >= getDimension()) {
throw new OutOfRangeException(LocalizedFormats.INDEX,
index, 0, getDimension() - 1);
}
}
/**
* Compute the sum of this vector and {@code v}.
* Returns a new vector. Does not change instance data.
*
* @param v Vector to be added.
* @return {@code this} + {@code v}.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
*/
public RealVector add(RealVector v) {
RealVector result = v.copy();
Iterator<Entry> it = sparseIterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
final int index = e.getIndex();
result.setEntry(index, e.getValue() + result.getEntry(index));
}
return result;
}
/**
* Subtract {@code v} from this vector.
* Returns a new vector. Does not change instance data.
*
* @param v Vector to be subtracted.
* @return {@code this} - {@code v}.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
*/
public RealVector subtract(RealVector v) {
RealVector result = v.copy();
Iterator<Entry> it = sparseIterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
final int index = e.getIndex();
result.setEntry(index, e.getValue() - result.getEntry(index));
}
return result;
}
/**
* Add a value to each entry.
* Returns a new vector. Does not change instance data.
*
* @param d Value to be added to each entry.
* @return {@code this} + {@code d}.
*/
public RealVector mapAdd(double d) {
return copy().mapAddToSelf(d);
}
/**
* Add a value to each entry.
* The instance is changed in-place.
*
* @param d Value to be added to each entry.
* @return {@code this}.
*/
public RealVector mapAddToSelf(double d) {
if (d != 0) {
return mapToSelf(FunctionUtils.fix2ndArgument(new Add(), d));
}
return this;
}
/**
* Returns a (deep) copy of this vector.
*
* @return a vector copy.
*/
public abstract RealVector copy();
/**
* Compute the dot product of this vector with {@code v}.
*
* @param v Vector with which dot product should be computed
* @return the scalar dot product between this instance and {@code v}.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
*/
public double dotProduct(RealVector v) {
checkVectorDimensions(v);
double d = 0;
Iterator<Entry> it = sparseIterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
d += e.getValue() * v.getEntry(e.getIndex());
}
return d;
}
/**
* Computes the cosine of the angle between this vector and the
* argument.
*
* @param v Vector.
* @return the cosine of the angle between this vector and {@code v}.
*/
public double cosine(RealVector v) {
final double norm = getNorm();
final double vNorm = v.getNorm();
if (norm == 0 ||
vNorm == 0) {
throw new MathArithmeticException(LocalizedFormats.ZERO_NORM);
}
return dotProduct(v) / (norm * vNorm);
}
/**
* Element-by-element division.
*
* @param v Vector by which instance elements must be divided.
* @return a vector containing this[i] / v[i] for all i.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
*/
public abstract RealVector ebeDivide(RealVector v);
/**
* Element-by-element multiplication.
*
* @param v Vector by which instance elements must be multiplied
* @return a vector containing this[i] * v[i] for all i.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
*/
public abstract RealVector ebeMultiply(RealVector v);
/**
* Distance between two vectors.
* <p>This method computes the distance consistent with the
* L<sub>2</sub> norm, i.e. the square root of the sum of
* element differences, or Euclidian distance.</p>
*
* @param v Vector to which distance is requested.
* @return the distance between two vectors.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
* @see #getL1Distance(RealVector)
* @see #getLInfDistance(RealVector)
* @see #getNorm()
*/
public double getDistance(RealVector v) {
checkVectorDimensions(v);
double d = 0;
Iterator<Entry> it = iterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
final double diff = e.getValue() - v.getEntry(e.getIndex());
d += diff * diff;
}
return FastMath.sqrt(d);
}
/**
* Returns the L<sub>2</sub> norm of the vector.
* <p>The L<sub>2</sub> norm is the root of the sum of
* the squared elements.</p>
*
* @return the norm.
* @see #getL1Norm()
* @see #getLInfNorm()
* @see #getDistance(RealVector)
*/
public double getNorm() {
double sum = 0;
Iterator<Entry> it = sparseIterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
final double value = e.getValue();
sum += value * value;
}
return FastMath.sqrt(sum);
}
/**
* Returns the L<sub>1</sub> norm of the vector.
* <p>The L<sub>1</sub> norm is the sum of the absolute
* values of the elements.</p>
*
* @return the norm.
* @see #getNorm()
* @see #getLInfNorm()
* @see #getL1Distance(RealVector)
*/
public double getL1Norm() {
double norm = 0;
Iterator<Entry> it = sparseIterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
norm += FastMath.abs(e.getValue());
}
return norm;
}
/**
* Returns the L<sub>∞</sub> norm of the vector.
* <p>The L<sub>∞</sub> norm is the max of the absolute
* values of the elements.</p>
*
* @return the norm.
* @see #getNorm()
* @see #getL1Norm()
* @see #getLInfDistance(RealVector)
*/
public double getLInfNorm() {
double norm = 0;
Iterator<Entry> it = sparseIterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
norm = FastMath.max(norm, FastMath.abs(e.getValue()));
}
return norm;
}
/**
* Distance between two vectors.
* <p>This method computes the distance consistent with
* L<sub>1</sub> norm, i.e. the sum of the absolute values of
* the elements differences.</p>
*
* @param v Vector to which distance is requested.
* @return the distance between two vectors.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
*/
public double getL1Distance(RealVector v) {
checkVectorDimensions(v);
double d = 0;
Iterator<Entry> it = iterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
d += FastMath.abs(e.getValue() - v.getEntry(e.getIndex()));
}
return d;
}
/**
* Distance between two vectors.
* <p>This method computes the distance consistent with
* L<sub>∞</sub> norm, i.e. the max of the absolute values of
* element differences.</p>
*
* @param v Vector to which distance is requested.
* @return the distance between two vectors.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
* @see #getDistance(RealVector)
* @see #getL1Distance(RealVector)
* @see #getLInfNorm()
*/
public double getLInfDistance(RealVector v) {
checkVectorDimensions(v);
double d = 0;
Iterator<Entry> it = iterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
d = FastMath.max(FastMath.abs(e.getValue() - v.getEntry(e.getIndex())), d);
}
return d;
}
/**
* Get the index of the minimum entry.
*
* @return the index of the minimum entry or -1 if vector length is 0
* or all entries are {@code NaN}.
*/
public int getMinIndex() {
int minIndex = -1;
double minValue = Double.POSITIVE_INFINITY;
Iterator<Entry> iterator = iterator();
while (iterator.hasNext()) {
final Entry entry = iterator.next();
if (entry.getValue() <= minValue) {
minIndex = entry.getIndex();
minValue = entry.getValue();
}
}
return minIndex;
}
/**
* Get the value of the minimum entry.
*
* @return the value of the minimum entry or {@code NaN} if all
* entries are {@code NaN}.
*/
public double getMinValue() {
final int minIndex = getMinIndex();
return minIndex < 0 ? Double.NaN : getEntry(minIndex);
}
/**
* Get the index of the maximum entry.
*
* @return the index of the maximum entry or -1 if vector length is 0
* or all entries are {@code NaN}
*/
public int getMaxIndex() {
int maxIndex = -1;
double maxValue = Double.NEGATIVE_INFINITY;
Iterator<Entry> iterator = iterator();
while (iterator.hasNext()) {
final Entry entry = iterator.next();
if (entry.getValue() >= maxValue) {
maxIndex = entry.getIndex();
maxValue = entry.getValue();
}
}
return maxIndex;
}
/**
* Get the value of the maximum entry.
*
* @return the value of the maximum entry or {@code NaN} if all
* entries are {@code NaN}.
*/
public double getMaxValue() {
final int maxIndex = getMaxIndex();
return maxIndex < 0 ? Double.NaN : getEntry(maxIndex);
}
/**
* Multiply each entry by the argument. Returns a new vector.
* Does not change instance data.
*
* @param d Multiplication factor.
* @return {@code this} * {@code d}.
*/
public RealVector mapMultiply(double d) {
return copy().mapMultiplyToSelf(d);
}
/**
* Multiply each entry.
* The instance is changed in-place.
*
* @param d Multiplication factor.
* @return {@code this}.
*/
public RealVector mapMultiplyToSelf(double d){
return mapToSelf(FunctionUtils.fix2ndArgument(new Multiply(), d));
}
/**
* Subtract a value from each entry. Returns a new vector.
* Does not change instance data.
*
* @param d Value to be subtracted.
* @return {@code this} - {@code d}.
*/
public RealVector mapSubtract(double d) {
return copy().mapSubtractToSelf(d);
}
/**
* Subtract a value from each entry.
* The instance is changed in-place.
*
* @param d Value to be subtracted.
* @return {@code this}.
*/
public RealVector mapSubtractToSelf(double d){
return mapAddToSelf(-d);
}
/**
* Divide each entry by the argument. Returns a new vector.
* Does not change instance data.
*
* @param d Value to divide by.
* @return {@code this} / {@code d}.
*/
public RealVector mapDivide(double d) {
return copy().mapDivideToSelf(d);
}
/**
* Divide each entry by the argument.
* The instance is changed in-place.
*
* @param d Value to divide by.
* @return {@code this}.
*/
public RealVector mapDivideToSelf(double d){
return mapToSelf(FunctionUtils.fix2ndArgument(new Divide(), d));
}
/**
* Compute the outer product.
*
* @param v Vector with which outer product should be computed.
* @return the matrix outer product between this instance and {@code v}.
*/
public RealMatrix outerProduct(RealVector v) {
RealMatrix product;
if (v instanceof SparseRealVector || this instanceof SparseRealVector) {
product = new OpenMapRealMatrix(this.getDimension(),
v.getDimension());
} else {
product = new Array2DRowRealMatrix(this.getDimension(),
v.getDimension());
}
Iterator<Entry> thisIt = sparseIterator();
Entry thisE = null;
while (thisIt.hasNext() && (thisE = thisIt.next()) != null) {
Iterator<Entry> otherIt = v.sparseIterator();
Entry otherE = null;
while (otherIt.hasNext() && (otherE = otherIt.next()) != null) {
product.setEntry(thisE.getIndex(), otherE.getIndex(),
thisE.getValue() * otherE.getValue());
}
}
return product;
}
/**
* Find the orthogonal projection of this vector onto another vector.
*
* @param v vector onto which instance must be projected.
* @return projection of the instance onto {@code v}.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code v} is not the same size as this vector.
*/
public abstract RealVector projection(RealVector v);
/**
* Set all elements to a single value.
*
* @param value Single value to set for all elements.
*/
public void set(double value) {
Iterator<Entry> it = iterator();
Entry e = null;
while (it.hasNext() && (e = it.next()) != null) {
e.setValue(value);
}
}
/**
* Convert the vector to an array of {@code double}s.
* The array is independent from this vector data: the elements
* are copied.
*
* @return an array containing a copy of the vector elements.
*/
public double[] toArray() {
int dim = getDimension();
double[] values = new double[dim];
for (int i = 0; i < dim; i++) {
values[i] = getEntry(i);
}
return values;
}
/**
* Convert the vector to an array of {@code double}s.
* The array is independent from this vector data: the elements
* are copied.
*
* @return an array containing a copy of the vector elements.
*/
public double[] getData() {
return toArray();
}
/**
* Creates a unit vector pointing in the direction of this vector.
* The instance is not changed by this method.
*
* @return a unit vector pointing in direction of this vector.
* @throws ArithmeticException if the norm is {@code null}.
*/
public RealVector unitVector() {
RealVector copy = copy();
copy.unitize();
return copy;
}
/**
* Converts this vector into a unit vector.
* The instance itself is changed by this method.
*
* @throws test.org.apache.commons.math.exception.MathArithmeticException
* if the norm is zero.
*/
public void unitize() {
mapDivideToSelf(getNorm());
}
/**
* Create a sparse iterator over the vector, which may omit some entries.
* Specialized implementations may choose to not iterate over all
* dimensions, either because those values are unset, or are equal
* to defaultValue(), or are small enough to be ignored for the
* purposes of iteration. No guarantees are made about order of iteration.
* In dense implementations, this method will often delegate to
* {@link #iterator()}.
*
* @return a sparse iterator.
*/
public Iterator<Entry> sparseIterator() {
return new SparseEntryIterator();
}
/**
* Generic dense iterator. Iteration is in increasing order
* of the vector index.
*
* @return a dense iterator.
*/
public Iterator<Entry> iterator() {
final int dim = getDimension();
return new Iterator<Entry>() {
/** Current index. */
private int i = 0;
/** Current entry. */
private Entry e = new Entry();
/** {@inheritDoc} */
public boolean hasNext() {
return i < dim;
}
/** {@inheritDoc} */
public Entry next() {
e.setIndex(i++);
return e;
}
/** {@inheritDoc} */
public void remove() {
throw new MathUnsupportedOperationException();
}
};
}
/**
* Acts as if implemented as:
* <pre>
* return copy().mapToSelf(function);
* </pre>
* Returns a new vector. Does not change instance data.
*
* @param function Function to apply to each entry.
* @return a new vector.
* @throws test.org.apache.commons.math.exception.MathUserException
* if the function throws it.
*/
public RealVector map(UnivariateRealFunction function) {
return copy().mapToSelf(function);
}
/**
* Acts as if it is implemented as:
* <pre>
* Entry e = null;
* for(Iterator<Entry> it = iterator(); it.hasNext(); e = it.next()) {
* e.setValue(function.value(e.getValue()));
* }
* </pre>
* Entries of this vector are modified in-place by this method.
*
* @param function Function to apply to each entry.
* @return a reference to this vector.
* @throws test.org.apache.commons.math.exception.MathUserException
* if the function throws it.
*/
public RealVector mapToSelf(UnivariateRealFunction function) {
Iterator<Entry> it = (function.value(0) == 0) ? sparseIterator() : iterator();
Entry e;
while (it.hasNext() && (e = it.next()) != null) {
e.setValue(function.value(e.getValue()));
}
return this;
}
/**
* Returns a new vector representing {@code a * this + b * y}, the linear
* combination of {@code this} and {@code y}.
* Returns a new vector. Does not change instance data.
*
* @param a Coefficient of {@code this}.
* @param b Coefficient of {@code y}.
* @param y Vector with which {@code this} is linearly combined.
* @return a vector containing {@code a * this[i] + b * y[i]} for all
* {@code i}.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code y} is not the same size as this vector.
*/
public RealVector combine(double a, double b, RealVector y) {
return copy().combineToSelf(a, b, y);
}
/**
* Updates {@code this} with the linear combination of {@code this} and
* {@code y}.
*
* @param a Weight of {@code this}.
* @param b Weight of {@code y}.
* @param y Vector with which {@code this} is linearly combined.
* @return {@code this}, with components equal to
* {@code a * this[i] + b * y[i]} for all {@code i}.
* @throws test.org.apache.commons.math.exception.DimensionMismatchException
* if {@code y} is not the same size as this vector.
*/
public RealVector combineToSelf(double a, double b, RealVector y) {
checkVectorDimensions(y);
for (int i = 0; i < getDimension(); i++) {
final double xi = getEntry(i);
final double yi = y.getEntry(i);
setEntry(i, a * xi + b * yi);
}
return this;
}
/**
* An entry in the vector.
*/
protected class Entry {
/** Index of this entry. */
private int index;
/** Simple constructor. */
public Entry() {
setIndex(0);
}
/**
* Get the value of the entry.
*
* @return the value of the entry.
*/
public double getValue() {
return getEntry(getIndex());
}
/**
* Set the value of the entry.
*
* @param value New value for the entry.
*/
public void setValue(double value) {
setEntry(getIndex(), value);
}
/**
* Get the index of the entry.
*
* @return the index of the entry.
*/
public int getIndex() {
return index;
}
/**
* Set the index of the entry.
*
* @param index New index for the entry.
*/
public void setIndex(int index) {
this.index = index;
}
}
/**
* This class should rarely be used, but is here to provide
* a default implementation of sparseIterator(), which is implemented
* by walking over the entries, skipping those whose values are the default one.
*
* Concrete subclasses which are SparseVector implementations should
* make their own sparse iterator, rather than using this one.
*
* This implementation might be useful for ArrayRealVector, when expensive
* operations which preserve the default value are to be done on the entries,
* and the fraction of non-default values is small (i.e. someone took a
* SparseVector, and passed it into the copy-constructor of ArrayRealVector)
*/
protected class SparseEntryIterator implements Iterator<Entry> {
/** Dimension of the vector. */
private final int dim;
/** Last entry returned by {@link #next()}. */
private Entry current;
/** Next entry for {@link #next()} to return. */
private Entry next;
/** Simple constructor. */
protected SparseEntryIterator() {
dim = getDimension();
current = new Entry();
next = new Entry();
if (next.getValue() == 0) {
advance(next);
}
}
/**
* Advance an entry up to the next nonzero one.
*
* @param e entry to advance.
*/
protected void advance(Entry e) {
if (e == null) {
return;
}
do {
e.setIndex(e.getIndex() + 1);
} while (e.getIndex() < dim && e.getValue() == 0);
if (e.getIndex() >= dim) {
e.setIndex(-1);
}
}
/** {@inheritDoc} */
public boolean hasNext() {
return next.getIndex() >= 0;
}
/** {@inheritDoc} */
public Entry next() {
int index = next.getIndex();
if (index < 0) {
throw new NoSuchElementException();
}
current.setIndex(index);
advance(next);
return current;
}
/** {@inheritDoc} */
public void remove() {
throw new MathUnsupportedOperationException();
}
}
/**
* Returns an unmodifiable view of the specified vector.
* The returned vector has read-only access. An attempt to modify it will
* result in a {@link MathUnsupportedOperationException}. However, the
* returned vector is <em>not</em> immutable, since any modification of
* {@code v} will also change the returned view.
* For example, in the following piece of code
* <pre>
* RealVector v = new ArrayRealVector(2);
* RealVector w = RealVector.unmodifiableRealVector(v);
* v.setEntry(0, 1.2);
* v.setEntry(1, -3.4);
* </pre>
* the changes will be seen in the {@code w} view of {@code v}.
*
* @param v Vector for which an unmodifiable view is to be returned.
* @return an unmodifiable view of {@code v}.
*/
public static RealVector unmodifiableRealVector(final RealVector v) {
/**
* This anonymous class is an implementation of {@link RealVector}
* with read-only access.
* It wraps any {@link RealVector}, and exposes all methods which
* do not modify it. Invoking methods which should normally result
* in the modification of the calling {@link RealVector} results in
* a {@link MathUnsupportedOperationException}. It should be noted
* that {@link UnmodifiableVector} is <em>not</em> immutable.
*/
return new RealVector() {
/** {@inheritDoc} */
@Override
public double[] getData() {
return v.getData();
}
/** {@inheritDoc} */
@Override
public RealVector mapToSelf(UnivariateRealFunction function) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public RealVector map(UnivariateRealFunction function) {
return v.map(function);
}
/** {@inheritDoc} */
@Override
public Iterator<Entry> iterator() {
final Iterator<Entry> i = v.iterator();
return new Iterator<Entry>() {
/** The current entry. */
private final UnmodifiableEntry e = new UnmodifiableEntry();
/** {@inheritDoc} */
public boolean hasNext() {
return i.hasNext();
}
/** {@inheritDoc} */
public Entry next() {
e.setIndex(i.next().getIndex());
return e;
}
/** {@inheritDoc} */
public void remove() {
throw new MathUnsupportedOperationException();
}
};
}
/** {@inheritDoc} */
@Override
public Iterator<Entry> sparseIterator() {
final Iterator<Entry> i = v.sparseIterator();
return new Iterator<Entry>() {
/** The current entry. */
private final UnmodifiableEntry e = new UnmodifiableEntry();
/** {@inheritDoc} */
public boolean hasNext() {
return i.hasNext();
}
/** {@inheritDoc} */
public Entry next() {
e.setIndex(i.next().getIndex());
return e;
}
/** {@inheritDoc} */
public void remove() {
throw new MathUnsupportedOperationException();
}
};
}
/** {@inheritDoc} */
@Override
public RealVector copy() {
return v.copy();
}
/** {@inheritDoc} */
@Override
public RealVector add(RealVector w) {
return v.add(w);
}
/** {@inheritDoc} */
@Override
public RealVector subtract(RealVector w) {
return v.subtract(w);
}
/** {@inheritDoc} */
@Override
public RealVector mapAdd(double d) {
return v.mapAdd(d);
}
/** {@inheritDoc} */
@Override
public RealVector mapAddToSelf(double d) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public RealVector mapSubtract(double d) {
return v.mapSubtract(d);
}
/** {@inheritDoc} */
@Override
public RealVector mapSubtractToSelf(double d) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public RealVector mapMultiply(double d) {
return v.mapMultiply(d);
}
/** {@inheritDoc} */
@Override
public RealVector mapMultiplyToSelf(double d) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public RealVector mapDivide(double d) {
return v.mapDivide(d);
}
/** {@inheritDoc} */
@Override
public RealVector mapDivideToSelf(double d) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public RealVector ebeMultiply(RealVector w) {
return v.ebeMultiply(w);
}
/** {@inheritDoc} */
@Override
public RealVector ebeDivide(RealVector w) {
return v.ebeDivide(w);
}
/** {@inheritDoc} */
@Override
public double dotProduct(RealVector w) {
return v.dotProduct(w);
}
/** {@inheritDoc} */
@Override
public double cosine(RealVector w) {
return v.cosine(w);
}
/** {@inheritDoc} */
@Override
public double getNorm() {
return v.getNorm();
}
/** {@inheritDoc} */
@Override
public double getL1Norm() {
return v.getL1Norm();
}
/** {@inheritDoc} */
@Override
public double getLInfNorm() {
return v.getLInfNorm();
}
/** {@inheritDoc} */
@Override
public double getDistance(RealVector w) {
return v.getDistance(w);
}
/** {@inheritDoc} */
@Override
public double getL1Distance(RealVector w) {
return v.getL1Distance(w);
}
/** {@inheritDoc} */
@Override
public double getLInfDistance(RealVector w) {
return v.getLInfDistance(w);
}
/** {@inheritDoc} */
@Override
public RealVector unitVector() {
return v.unitVector();
}
/** {@inheritDoc} */
@Override
public void unitize() {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public RealVector projection(RealVector w) {
return v.projection(w);
}
/** {@inheritDoc} */
@Override
public RealMatrix outerProduct(RealVector w) {
return v.outerProduct(w);
}
/** {@inheritDoc} */
@Override
public double getEntry(int index) {
return v.getEntry(index);
}
/** {@inheritDoc} */
@Override
public void setEntry(int index, double value) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public int getDimension() {
return v.getDimension();
}
/** {@inheritDoc} */
@Override
public RealVector append(RealVector w) {
return v.append(w);
}
/** {@inheritDoc} */
@Override
public RealVector append(double d) {
return v.append(d);
}
/** {@inheritDoc} */
@Override
public RealVector getSubVector(int index, int n) {
return v.getSubVector(index, n);
}
/** {@inheritDoc} */
@Override
public void setSubVector(int index, RealVector w) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public void set(double value) {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public double[] toArray() {
return v.toArray();
}
/** {@inheritDoc} */
@Override
public boolean isNaN() {
return v.isNaN();
}
/** {@inheritDoc} */
@Override
public boolean isInfinite() {
return v.isInfinite();
}
/** {@inheritDoc} */
@Override
public RealVector combine(double a, double b, RealVector y) {
return v.combine(a, b, y);
}
/** {@inheritDoc} */
@Override
public RealVector combineToSelf(double a, double b, RealVector y) {
throw new MathUnsupportedOperationException();
}
/** An entry in the vector. */
class UnmodifiableEntry extends Entry {
/** {@inheritDoc} */
@Override
public double getValue() {
return v.getEntry(getIndex());
}
/** {@inheritDoc} */
@Override
public void setValue(double value) {
throw new MathUnsupportedOperationException();
}
}
};
}
}
|
9230bbe39aa98beb8bc28bf75369fd5fe6a9a73e | 5,215 | java | Java | ifs-resources/src/main/java/org/innovateuk/ifs/user/resource/Role.java | danielholdsworth/innovation-funding-service | 39748ba4f574c29f3d09adde7af60ca85ffeec06 | [
"MIT"
] | null | null | null | ifs-resources/src/main/java/org/innovateuk/ifs/user/resource/Role.java | danielholdsworth/innovation-funding-service | 39748ba4f574c29f3d09adde7af60ca85ffeec06 | [
"MIT"
] | null | null | null | ifs-resources/src/main/java/org/innovateuk/ifs/user/resource/Role.java | danielholdsworth/innovation-funding-service | 39748ba4f574c29f3d09adde7af60ca85ffeec06 | [
"MIT"
] | null | null | null | 37.517986 | 113 | 0.623394 | 995,587 | package org.innovateuk.ifs.user.resource;
import com.google.common.collect.Sets;
import org.innovateuk.ifs.identity.Identifiable;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import static com.google.common.collect.Lists.newArrayList;
/**
* Role defines database relations and a model to use client side and server side.
*/
public enum Role implements Identifiable {
LEADAPPLICANT ( 1, "leadapplicant", "Lead Applicant"),
COLLABORATOR ( 2, "collaborator", "Collaborator"),
ASSESSOR ( 3, "assessor", "Assessor"),
APPLICANT ( 4, "applicant", "Applicant"),
COMP_ADMIN ( 5, "comp_admin", "Competition Administrator"),
SYSTEM_REGISTRATION_USER ( 6, "system_registrar", "System Registration User"),
SYSTEM_MAINTAINER ( 7, "system_maintainer", "System Maintainer"),
PROJECT_FINANCE ( 8, "project_finance", "Project Finance"),
FINANCE_CONTACT ( 9, "finance_contact", "Finance Contact"),
PARTNER (10, "partner", "Partner"),
PROJECT_MANAGER (11, "project_manager", "Project Manager"),
COMP_EXEC (12, "competition_executive", "Portfolio Manager"),
INNOVATION_LEAD (13, "innovation_lead", "Innovation Lead"),
IFS_ADMINISTRATOR (14, "ifs_administrator", "IFS Administrator"),
SUPPORT (15, "support", "IFS Support User"),
PANEL_ASSESSOR (16, "panel_assessor", "Panel Assessor"),
INTERVIEW_ASSESSOR (17, "interview_assessor", "Interview Assessor"),
INTERVIEW_LEAD_APPLICANT (18, "interview_lead_applicant", "Interview Lead Applicant"),
MONITORING_OFFICER (19, "monitoring_officer", "Monitoring Officer"),
STAKEHOLDER (20, "stakeholder", "Stakeholder"),
LIVE_PROJECTS_USER (21, "live_projects_user", "Live projects user"),
EXTERNAL_FINANCE (22, "external_finance", "External finance reviewer"),
KNOWLEDGE_TRANSFER_ADVISER (23, "knowledge_transfer_adviser", "Knowledge transfer adviser"),
SUPPORTER (24, "supporter", "Supporter");
final long id;
final String name;
final String displayName;
Role(final long id, final String name, final String displayName) {
this.id = id;
this.name = name;
this.displayName = displayName;
}
public static Role getByName(String name) {
return Stream.of(values()).filter(role -> role.name.equals(name)).findFirst().get();
}
public static Role getById (long id) {
return Stream.of(values()).filter(role -> role.id == id).findFirst().get();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getDisplayName() {
return displayName;
}
public boolean isPartner() {
return this == PARTNER;
}
public boolean isLeadApplicant() {
return this == LEADAPPLICANT;
}
public boolean isCollaborator() {
return this == COLLABORATOR;
}
public boolean isProjectManager() {
return this == PROJECT_MANAGER;
}
public boolean isStakeHolder() {return this == STAKEHOLDER; }
public boolean isAssessor() {return this == ASSESSOR; }
public boolean isKta() {
return this == KNOWLEDGE_TRANSFER_ADVISER;
}
public static Set<Role> applicantProcessRoles() {
return EnumSet.of(LEADAPPLICANT, COLLABORATOR);
}
public static Set<Role> assessorProcessRoles() {
return EnumSet.of(ASSESSOR, INTERVIEW_ASSESSOR, PANEL_ASSESSOR);
}
public static Set<Role> internalRoles(){
return EnumSet.of(IFS_ADMINISTRATOR, PROJECT_FINANCE, COMP_ADMIN, SUPPORT, INNOVATION_LEAD);
}
public static Set<Role> inviteExternalRoles(){
return EnumSet.of(KNOWLEDGE_TRANSFER_ADVISER);
}
public static Set<Role> externalApplicantRoles(){
return EnumSet.of(APPLICANT, COLLABORATOR, FINANCE_CONTACT, PARTNER, PROJECT_MANAGER);
}
public static Set<Role> externalRoles() {
return Sets.union(externalApplicantRoles(), EnumSet.of(ASSESSOR, KNOWLEDGE_TRANSFER_ADVISER, SUPPORTER));
}
public static List<Role> multiDashboardRoles() {
return newArrayList(APPLICANT, ASSESSOR, STAKEHOLDER, MONITORING_OFFICER, LIVE_PROJECTS_USER, SUPPORTER);
}
public List<String> getAuthorities() {
if (this == KNOWLEDGE_TRANSFER_ADVISER) {
return newArrayList(this.name, ASSESSOR.name, MONITORING_OFFICER.name);
} if (this == SYSTEM_MAINTAINER) {
return newArrayList(this.name, IFS_ADMINISTRATOR.name, PROJECT_FINANCE.name);
}
return newArrayList(this.name);
}
public static Set<Role> externalRolesToInvite() {
return EnumSet.of(KNOWLEDGE_TRANSFER_ADVISER, SUPPORTER);
}
} |
9230bc6ea11d2d13c3e80011a2b16d250468d78a | 16,918 | java | Java | moe/test/xosrt_tests/src/test/java/org/moe/xosrt/binding/test/uikit/controllers/UIViewControllerViewController.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/test/xosrt_tests/src/test/java/org/moe/xosrt/binding/test/uikit/controllers/UIViewControllerViewController.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/test/xosrt_tests/src/test/java/org/moe/xosrt/binding/test/uikit/controllers/UIViewControllerViewController.java | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | 53.707937 | 137 | 0.698664 | 995,588 | package org.moe.xosrt.binding.test.uikit.controllers;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ptr.Ptr;
import org.moe.natj.general.ptr.impl.PtrFactory;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.Selector;
import org.moe.xosrt.binding.test.uikit.testhelpers.SimpleViewController;
import ios.NSObject;
import ios.coregraphics.c.CoreGraphics;
import ios.coregraphics.struct.CGRect;
import ios.foundation.*;
import ios.uikit.*;
import ios.uikit.enums.UIBarButtonItemStyle;
public class UIViewControllerViewController extends UIViewController {
static {
NatJ.register();
}
protected UIViewControllerViewController(Pointer peer) {
super(peer);
}
@Selector("alloc")
public static native UIViewControllerViewController alloc();
@Selector("init")
public native UIViewControllerViewController init();
UIView view1;
UIView controllerView;
NSMutableArray testResults;
public static volatile boolean testView1 = false;
public static volatile boolean testSetView1 = false;
public static volatile boolean testTitle1 = false;
public static volatile boolean testTitle2 = false;
public static volatile boolean testLoadView1 = false;
public static volatile boolean testViewDidLoad1 = false;
public static volatile boolean testViewWillAppear1 = false;
public static volatile boolean testViewDidAppear1 = false;
public static volatile boolean testNavigationItem1 = false;
public static volatile boolean testNavigationController1 = false;
public static volatile boolean testTabBarItem1 = false;
public static volatile boolean testTabBarController1 = false;
public static volatile boolean testToolbarItems1 = false;
public static volatile boolean testHidesBottomBarWhenPushed1 = false;
public void testProperties() {
testView1 = (view() == controllerView && view().tag() == 24948);
controllerView = UIView.alloc().initWithFrame(CoreGraphics.CGRectMake(0, 0, 320, 480));
controllerView.setBackgroundColor(UIColor.blueColor());
controllerView.setTag(610841);
setView(controllerView);
testSetView1 = (view() == controllerView);
UIViewController viewController1 = SimpleViewController.alloc().init();
UIViewController viewController2 = SimpleViewController.alloc().init();
UIViewController viewController3 = SimpleViewController.alloc().init();
UIViewController viewController4 = SimpleViewController.alloc().init();
UIViewController viewController5 = SimpleViewController.alloc().init();
String title1 = "title 1";
String navigationTitle1 = "navigationTitle 1";
String tabBarTitle1 = "tabBarTitle 1";
String title2 = "title 2";
String navigationTitle2 = "navigationTitle 2";
String title3 = "title 3";
String tabBarTitle3 = "tabBarTitle 3";
String title4 = "title 4";
String navigationTitle4 = "navigationTitle 4";
String tabBarTitle4 = "tabBarTitle 4";
String navigationTitle5 = "navigationTitle 5";
String tabBarTitle5 = "tabBarTitle 5";
boolean testSelfTitle = (title().equals(title1) && navigationItem().title().equals(title1)
&& tabBarItem().title().equals(title1));
viewController1.navigationItem().setTitle(tabBarTitle1);
viewController1.tabBarItem().setTitle(navigationTitle1);
viewController1.setTitle(title1);
boolean testViewController1Title = viewController1.title().equals(title1)
&& viewController1.navigationItem().title().equals(title1)
&& viewController1.tabBarItem().title().equals(title1);
viewController2.setTitle(title2);
viewController2.navigationItem().setTitle(navigationTitle2);
boolean testViewController2Title = viewController2.title().equals(title2)
&& viewController2.navigationItem().title().equals(navigationTitle2)
&& viewController2.tabBarItem().title().equals(title2);
viewController3.setTitle(title3);
viewController3.tabBarItem().setTitle(tabBarTitle3);
boolean testViewController3Title = viewController3.title().equals(title3)
&& viewController3.navigationItem().title().equals(title3)
&& viewController3.tabBarItem().title().equals(tabBarTitle3);
viewController4.setTitle(title4);
viewController4.navigationItem().setTitle(navigationTitle4);
viewController4.tabBarItem().setTitle(tabBarTitle4);
boolean testViewController4Title = viewController4.title().equals(title4)
&& viewController4.navigationItem().title().equals(navigationTitle4)
&& viewController4.tabBarItem().title().equals(tabBarTitle4);
viewController5.navigationItem().setTitle(navigationTitle5);
viewController5.tabBarItem().setTitle(tabBarTitle5);
boolean testViewController5Title = viewController5.title() == null
&& viewController5.navigationItem().title().equals(navigationTitle5)
&& viewController5.tabBarItem().title().equals(tabBarTitle5);
testTitle1 = (testSelfTitle && testViewController1Title && testViewController2Title
&& testViewController3Title && testViewController4Title && testViewController5Title);
SimpleViewController viewController6 = SimpleViewController.alloc().init();
SimpleViewController viewController7 = SimpleViewController.alloc().init();
SimpleViewController viewController8 = SimpleViewController.alloc().init();
SimpleViewController viewController9 = SimpleViewController.alloc().init();
UINavigationController navigationController1 = UINavigationController.alloc().initWithRootViewController(viewController6);
navigationController1.setTitle(title1);
viewController6.setTitle(title2);
navigationController1.pushViewControllerAnimated(viewController7, false);
viewController7.setTitle(title3);
UINavigationController navigationController2 = UINavigationController.alloc().init();
navigationController2.setTitle(title1);
navigationController2.setViewControllers(NSArray.arrayWithObjectsCount(
(Ptr) PtrFactory.newObjectArray(UIViewController.class, new UIViewController[]{
viewController8, viewController9
}), 2));
viewController8.setTitle(title2);
viewController9.setTitle(title3);
viewController8.setTitle(title4);
testTitle2 = (navigationController1.title().equals(title2) && viewController6.title().equals(title2)
&& viewController7.title().equals(title3) && navigationController2.title().equals(title4)
&& viewController8.title().equals(title4) && viewController9.title().equals(title3));
}
public void testViewLifeCycleMethods() {
String auxStr = (String)testResults.objectAtIndex(0);
testLoadView1 = ("loadView".equals(auxStr));
auxStr = (String)testResults.objectAtIndex(1);
testViewDidLoad1 = "viewDidLoad".equals(auxStr);
auxStr = (String)testResults.objectAtIndex(2);
testViewWillAppear1 = "viewWillAppear".equals(auxStr);
auxStr = (String)testResults.objectAtIndex(3);
testViewDidAppear1 = "viewDidAppear".equals(auxStr);
}
public void testNavigationProperties() {
UIViewController viewController1 = UIViewController.alloc().init();
String testTitle1 = "testTitle1";
viewController1.setTitle(testTitle1);
testNavigationItem1 = (viewController1.navigationItem() != null
&& viewController1.navigationItem().title().equals(testTitle1));
UIViewController viewController2 = UIViewController.alloc().init();
UINavigationController navigationController1 = UINavigationController.alloc().initWithRootViewController(viewController2);
testNavigationController1 = (viewController2.navigationController() == navigationController1);
}
public void testTabBarProperties() {
UIViewController viewController1 = UIViewController.alloc().init();
String testTitle1 = "testTitle1";
viewController1.setTitle(testTitle1);
testTabBarItem1 = (viewController1.tabBarItem() != null
&& viewController1.tabBarItem().title().equals(testTitle1));
UIViewController viewController2 = SimpleViewController.alloc().init();
UIViewController viewController3 = SimpleViewController.alloc().init();
UIViewController viewController4 = SimpleViewController.alloc().init();
UIViewController viewController5 = SimpleViewController.alloc().init();
UIViewController viewController6 = SimpleViewController.alloc().init();
UINavigationController navigationController1 = UINavigationController.alloc().initWithRootViewController(viewController4);
navigationController1.pushViewControllerAnimated(viewController5, false);
navigationController1.pushViewControllerAnimated(viewController6, false);
navigationController1.popViewControllerAnimated(false);
UITabBarController tabBarController1 = UITabBarController.alloc().init();
tabBarController1.setViewControllers(NSArray.arrayWithObjectsCount(
(Ptr)PtrFactory.newObjectArray(UIViewController.class, new UIViewController[]{
viewController2, viewController3, navigationController1
}), 3));
testTabBarController1 = (viewController2.tabBarController() == tabBarController1
&& viewController3.tabBarController() == tabBarController1
&& viewController4.tabBarController() == tabBarController1
&& viewController5.tabBarController() == tabBarController1
&& viewController6.tabBarController() == null
&& navigationController1.tabBarController() == tabBarController1);
}
public void testToolbarProperties() {
UIViewController viewController2 = UIViewController.alloc().init();
UIViewController viewController3 = UIViewController.alloc().init();
UIViewController viewController4 = UIViewController.alloc().init();
UIBarButtonItem barButtonItem0 = UIBarButtonItem.alloc().initWithTitleStyleTargetAction(
"item0", UIBarButtonItemStyle.Bordered, this, null);
UIBarButtonItem barButtonItem1 = UIBarButtonItem.alloc().initWithTitleStyleTargetAction(
"item1", UIBarButtonItemStyle.Bordered, this, null);
UIBarButtonItem barButtonItem2 = UIBarButtonItem.alloc().initWithTitleStyleTargetAction(
"item2", UIBarButtonItemStyle.Bordered, this, null);
UIBarButtonItem barButtonItem3 = UIBarButtonItem.alloc().initWithTitleStyleTargetAction(
"item2", UIBarButtonItemStyle.Bordered, this, null);
UIBarButtonItem barButtonItem4 = UIBarButtonItem.alloc().initWithTitleStyleTargetAction(
"item2", UIBarButtonItemStyle.Bordered, this, null);
viewController2.setToolbarItems(NSArray.arrayWithObjectsCount(
(Ptr) PtrFactory.newObjectArray(UIBarButtonItem.class, new UIBarButtonItem[]{
barButtonItem0, barButtonItem1
}), 2));
viewController3.setToolbarItems(NSArray.arrayWithObjectsCount(
(Ptr) PtrFactory.newObjectArray(UIBarButtonItem.class, new UIBarButtonItem[]{
barButtonItem2, barButtonItem3, barButtonItem4
}), 3));
testToolbarItems1 = (viewController2.toolbarItems().count() == 2
&& viewController2.toolbarItems().objectAtIndex(0) == barButtonItem0
&& viewController2.toolbarItems().objectAtIndex(1) == barButtonItem1
&& viewController3.toolbarItems().count() == 3
&& viewController3.toolbarItems().objectAtIndex(0) == barButtonItem2
&& viewController3.toolbarItems().objectAtIndex(1) == barButtonItem3
&& viewController3.toolbarItems().objectAtIndex(2) == barButtonItem4
&& viewController4.toolbarItems() == null);
UIViewController viewController0 = UIViewController.alloc().init();
UIViewController viewController1 = UIViewController.alloc().init();
viewController0.setHidesBottomBarWhenPushed(true);
viewController1.setHidesBottomBarWhenPushed(false);
SimpleViewController simpleViewController0 = SimpleViewController.alloc().init();
simpleViewController0.setHidesBottomBarWhenPushed(false);
SimpleViewController simpleSimpleViewController = SimpleViewController.alloc().init();
simpleSimpleViewController.setHidesBottomBarWhenPushed(true);
UINavigationController navigationController0 = UINavigationController.alloc().initWithRootViewController(simpleViewController0);
navigationController0.setToolbarHidden(false);
navigationController0.pushViewControllerAnimated(simpleSimpleViewController, false);
SimpleViewController simpleViewController2 = SimpleViewController.alloc().init();
simpleViewController2.setHidesBottomBarWhenPushed(false);
SimpleViewController simpleViewController3 = SimpleViewController.alloc().init();
simpleViewController3.setHidesBottomBarWhenPushed(true);
UINavigationController navigationController1 = UINavigationController.alloc().initWithRootViewController(simpleViewController2);
navigationController1.setToolbarHidden(false);
navigationController1.pushViewControllerAnimated(simpleViewController3, false);
performSelectorWithObjectAfterDelay(
new SEL("assertHidesBottomBarWhenPushed1:"),
NSArray.arrayWithObjectsCount(
(Ptr) PtrFactory.newObjectArray(UIViewController.class, new UIViewController[]{
viewController0, viewController1, navigationController0, navigationController1
}), 4)
, 1);
}
@Selector("assertHidesBottomBarWhenPushed1:")
public void assertHidesBottomBarWhenPushed1(NSArray arrayOfViewControllers) {
//arrayOfViewControllers.retain();
UIViewController viewController0 = (UIViewController)arrayOfViewControllers.objectAtIndex(0);
UIViewController viewController1 = (UIViewController)arrayOfViewControllers.objectAtIndex(1);
UINavigationController navigationController0 = (UINavigationController)arrayOfViewControllers.objectAtIndex(2);
UINavigationController navigationController1 = (UINavigationController)arrayOfViewControllers.objectAtIndex(3);
navigationController1.setToolbarHidden(false);
testHidesBottomBarWhenPushed1 = (viewController0.hidesBottomBarWhenPushed()
&& !viewController1.hidesBottomBarWhenPushed()
&& navigationController0.isToolbarHidden()
&& navigationController1.topViewController().hidesBottomBarWhenPushed());
//arrayOfViewControllers.release();
}
@Selector("loadView")
@Override
public void loadView() {
controllerView = UIView.alloc().initWithFrame(CoreGraphics.CGRectMake(0,0,320, 480));
controllerView.setTag(24948);
setView(controllerView);
view().setBackgroundColor(UIColor.greenColor());
view1 = UIView.alloc().initWithFrame(CoreGraphics.CGRectMake(100, 200, 50, 80));
view1.setBackgroundColor(UIColor.yellowColor());
view().addSubview(view1);
testResults = NSMutableArray.alloc().init();
testResults.addObject(NSString.stringWithString("loadView"));
}
@Selector("viewDidLoad")
@Override
public void viewDidLoad() {
testResults.addObject(NSString.stringWithString("viewDidLoad"));
super.viewDidLoad();
}
@Selector("viewWillAppear:")
@Override
public void viewWillAppear(boolean animated) {
testResults.addObject(NSString.stringWithString("viewWillAppear"));
}
@Selector("viewDidAppear:")
@Override
public void viewDidAppear(boolean animated) {
testResults.addObject(NSString.stringWithString("viewDidAppear"));
testProperties();
testViewLifeCycleMethods();
testNavigationProperties();
testTabBarProperties();
testToolbarProperties();
}
public void dealloc() {
super.dealloc();
}
}
|
9230bc7ea2f12671f1431eb16e093dd72f16dfea | 3,901 | java | Java | flinkx-core/src/main/java/com/dtstack/flinkx/config/DataTransferConfig.java | hunanjsd/flinkx | 00beb8e24d94b6833751f5d4e5e24d53815fc24c | [
"Apache-2.0"
] | 14 | 2021-04-16T06:32:14.000Z | 2022-03-11T12:25:34.000Z | flinkx-core/src/main/java/com/dtstack/flinkx/config/DataTransferConfig.java | hunanjsd/flinkx | 00beb8e24d94b6833751f5d4e5e24d53815fc24c | [
"Apache-2.0"
] | null | null | null | flinkx-core/src/main/java/com/dtstack/flinkx/config/DataTransferConfig.java | hunanjsd/flinkx | 00beb8e24d94b6833751f5d4e5e24d53815fc24c | [
"Apache-2.0"
] | 9 | 2021-06-09T06:11:15.000Z | 2022-03-09T03:57:38.000Z | 31.991803 | 108 | 0.702024 | 995,589 | /**
* 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 com.dtstack.flinkx.config;
import com.dtstack.flinkx.util.MapUtil;
import com.google.gson.Gson;
import org.apache.flink.util.Preconditions;
import java.io.Reader;
import java.util.List;
import java.util.Map;
/**
* The class of Data transfer task configuration
*
* Company: www.dtstack.com
* @author envkt@example.com
*/
public class DataTransferConfig extends AbstractConfig {
JobConfig job;
public DataTransferConfig(Map<String, Object> map) {
super(map);
job = new JobConfig((Map<String, Object>) map.get("job"));
}
public JobConfig getJob() {
return job;
}
public void setJob(JobConfig job) {
this.job = job;
}
String monitorUrls;
public String getMonitorUrls() {
return monitorUrls;
}
public void setMonitorUrls(String monitorUrls) {
this.monitorUrls = monitorUrls;
}
String pluginRoot;
public String getPluginRoot() {
return pluginRoot;
}
public void setPluginRoot(String pluginRoot) {
this.pluginRoot = pluginRoot;
}
private static void checkConfig(DataTransferConfig config) {
Preconditions.checkNotNull(config);
JobConfig jobConfig = config.getJob();
Preconditions.checkNotNull(jobConfig, "Must spedify job element");
List<ContentConfig> contentConfig = jobConfig.getContent();
Preconditions.checkNotNull(contentConfig, "Must specify content array");
Preconditions.checkArgument(contentConfig.size() != 0, "Must specify at least one content element");
// 暂时只考虑只包含一个Content元素的情况
ContentConfig content = contentConfig.get(0);
// 检查reader配置
ReaderConfig readerConfig = content.getReader();
Preconditions.checkNotNull(readerConfig, "Must specify a reader element");
Preconditions.checkNotNull(readerConfig.getName(), "Must specify reader name");
ReaderConfig.ParameterConfig readerParameter = readerConfig.getParameter();
Preconditions.checkNotNull(readerParameter, "Must specify parameter for reader");
// 检查我writer配置
WriterConfig writerConfig = content.getWriter();
Preconditions.checkNotNull(writerConfig, "Must specify a writer element");
Preconditions.checkNotNull(writerConfig.getName(), "Must specify the writer name");
WriterConfig.ParameterConfig writerParameter = writerConfig.getParameter();
Preconditions.checkNotNull(writerParameter, "Must specify parameter for the writer");
}
public static DataTransferConfig parse(String json) {
Gson gson = new Gson();
Map<String,Object> map = gson.fromJson(json, Map.class);
map = MapUtil.convertToHashMap(map);
DataTransferConfig config = new DataTransferConfig(map);
checkConfig(config);
return config;
}
public static DataTransferConfig parse(Reader reader) {
Gson gson = new Gson();
DataTransferConfig config = gson.fromJson(reader, DataTransferConfig.class);
checkConfig(config);
return config;
}
}
|
9230bd543224f82a4eff7a5145dd2e67ec208fdc | 4,496 | java | Java | src/org/sosy_lab/cpachecker/cpa/arg/ARGMergeJoin.java | lembergerth/cpachecker | 3287f149ee9f881892152439fc9e7d8036f7a75b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/org/sosy_lab/cpachecker/cpa/arg/ARGMergeJoin.java | lembergerth/cpachecker | 3287f149ee9f881892152439fc9e7d8036f7a75b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-11-11T14:23:56.000Z | 2019-11-11T14:23:56.000Z | src/org/sosy_lab/cpachecker/cpa/arg/ARGMergeJoin.java | lembergerth/cpachecker | 3287f149ee9f881892152439fc9e7d8036f7a75b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 39.787611 | 123 | 0.746441 | 995,590 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cpa.arg;
import java.util.HashSet;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.cpachecker.core.interfaces.AbstractDomain;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.core.interfaces.MergeOperator;
import org.sosy_lab.cpachecker.core.interfaces.Precision;
import org.sosy_lab.cpachecker.exceptions.CPAException;
@Options
public class ARGMergeJoin implements MergeOperator {
private final MergeOperator wrappedMerge;
private final AbstractDomain wrappedDomain;
@Option(
secure = true,
name = "cpa.arg.mergeOnWrappedSubsumption",
description = "If this option is enabled, ARG states will also be merged if the first wrapped state is \n"
+ " subsumed by the second wrapped state (and the parents are not yet subsumed).")
private boolean mergeOnWrappedSubsumption = false;
public ARGMergeJoin(MergeOperator pWrappedMerge, AbstractDomain pWrappedDomain, Configuration config)
throws InvalidConfigurationException {
wrappedMerge = pWrappedMerge;
wrappedDomain = pWrappedDomain;
config.inject(this);
}
@Override
public AbstractState merge(AbstractState pElement1,
AbstractState pElement2, Precision pPrecision) throws CPAException, InterruptedException {
ARGState argElement1 = (ARGState)pElement1;
ARGState argElement2 = (ARGState)pElement2;
assert !argElement1.isCovered() : "Trying to merge covered element " + argElement1;
if (!argElement2.mayCover()) {
// elements that may not cover should also not be used for merge
return pElement2;
}
if (argElement1.getMergedWith() != null) {
// element was already merged into another element, don't try to widen argElement2
// TODO In the optimal case (if all merge & stop operators as well as the reached set partitioning fit well together)
// this case shouldn't happen, but it does sometimes (at least with ExplicitCPA+FeatureVarsCPA).
return pElement2;
}
AbstractState wrappedState1 = argElement1.getWrappedState();
AbstractState wrappedState2 = argElement2.getWrappedState();
AbstractState retElement = wrappedMerge.merge(wrappedState1, wrappedState2, pPrecision);
boolean continueMerge = !retElement.equals(wrappedState2);
if (mergeOnWrappedSubsumption) {
HashSet<ARGState> parents1 = new HashSet<>(argElement1.getParents());
HashSet<ARGState> parents2 = new HashSet<>(argElement2.getParents());
continueMerge = continueMerge ||
((!parents2.containsAll(parents1) && wrappedDomain.isLessOrEqual(wrappedState1,wrappedState2)));
}
if (!continueMerge) {
return pElement2;
}
ARGState mergedElement = new ARGState(retElement, null);
// now replace argElement2 by mergedElement in ARG
argElement2.replaceInARGWith(mergedElement);
// and also replace argElement1 with it
for (ARGState parentOfElement1 : argElement1.getParents()) {
mergedElement.addParent(parentOfElement1);
}
// argElement1 is the current successor, it does not have any children yet and covered nodes yet
assert argElement1.getChildren().isEmpty();
assert argElement1.getCoveredByThis().isEmpty();
// ARGElement1 will only be removed from ARG if stop(e1, reached) returns true.
// So we can't actually remove it now, but we need to remember this later.
argElement1.setMergedWith(mergedElement);
return mergedElement;
}
}
|
9230bf06854196ee5efed06e176feeb347e457d1 | 1,815 | java | Java | src/de/javagl/jgltf/model/v1/IndexMappingSets.java | AntonioNoack/jGLTF | 0a558b6501c00b04c2ddad7b4921a91656b7fd37 | [
"Apache-2.0"
] | null | null | null | src/de/javagl/jgltf/model/v1/IndexMappingSets.java | AntonioNoack/jGLTF | 0a558b6501c00b04c2ddad7b4921a91656b7fd37 | [
"Apache-2.0"
] | null | null | null | src/de/javagl/jgltf/model/v1/IndexMappingSets.java | AntonioNoack/jGLTF | 0a558b6501c00b04c2ddad7b4921a91656b7fd37 | [
"Apache-2.0"
] | null | null | null | 40.333333 | 71 | 0.683196 | 995,591 | package de.javagl.jgltf.model.v1;
import de.javagl.jgltf.impl.v1.GlTF;
/**
* Utility methods to create {@link IndexMappingSet} instances
*/
class IndexMappingSets {
/**
* Compute the {@link IndexMappingSet} for the given glTF instance.
* The {@link IndexMappingSet} will contain index mappings for all
* top-level dictionaries of the given glTF.
*
* @param gltf The glTF
* @return The {@link IndexMappingSet}
*/
static IndexMappingSet create(GlTF gltf) {
IndexMappingSet indexMappingSet = new IndexMappingSet();
indexMappingSet.generate("accessors", gltf.getAccessors());
indexMappingSet.generate("animations", gltf.getAnimations());
indexMappingSet.generate("buffers", gltf.getBuffers());
indexMappingSet.generate("bufferViews", gltf.getBufferViews());
indexMappingSet.generate("cameras", gltf.getCameras());
indexMappingSet.generate("images", gltf.getImages());
indexMappingSet.generate("materials", gltf.getMaterials());
indexMappingSet.generate("meshes", gltf.getMeshes());
indexMappingSet.generate("nodes", gltf.getNodes());
indexMappingSet.generate("programs", gltf.getPrograms());
indexMappingSet.generate("samplers", gltf.getSamplers());
indexMappingSet.generate("scenes", gltf.getScenes());
indexMappingSet.generate("shaders", gltf.getShaders());
indexMappingSet.generate("skins", gltf.getSkins());
indexMappingSet.generate("techniques", gltf.getTechniques());
indexMappingSet.generate("textures", gltf.getTextures());
return indexMappingSet;
}
/**
* Private constructor to prevent instantiation
*/
private IndexMappingSets() {
// Private constructor to prevent instantiation
}
}
|
9230c1c1bc5d755019742ecf9ea2d3ae83e667c6 | 10,806 | java | Java | bt-core/src/main/java/bt/runtime/BtRuntime.java | java-app-scans/bt | dcd0f41a5b2f5250b0b9af24dd0f1ccac23eed4d | [
"Apache-2.0"
] | 2,199 | 2016-08-11T18:02:48.000Z | 2022-03-31T11:02:54.000Z | bt-core/src/main/java/bt/runtime/BtRuntime.java | java-app-scans/bt | dcd0f41a5b2f5250b0b9af24dd0f1ccac23eed4d | [
"Apache-2.0"
] | 179 | 2016-09-01T22:42:54.000Z | 2022-01-28T06:18:30.000Z | bt-core/src/main/java/bt/runtime/BtRuntime.java | java-app-scans/bt | dcd0f41a5b2f5250b0b9af24dd0f1ccac23eed4d | [
"Apache-2.0"
] | 380 | 2016-11-03T14:39:10.000Z | 2022-03-26T08:31:48.000Z | 32.256716 | 161 | 0.608366 | 995,592 | /*
* Copyright (c) 2016—2021 Andrei Tomashpolskiy and individual contributors.
*
* 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 bt.runtime;
import bt.BtException;
import bt.event.EventSource;
import bt.module.ClientExecutor;
import bt.service.IRuntimeLifecycleBinder;
import bt.service.IRuntimeLifecycleBinder.LifecycleEvent;
import bt.service.LifecycleBinding;
import com.google.inject.Injector;
import com.google.inject.Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/**
* A runtime is an orchestrator of multiple simultaneous torrent sessions.
* It provides a DI container with shared services and manages the application's lifecycle.
*
* @since 1.0
*/
public class BtRuntime {
private static final Logger LOGGER = LoggerFactory.getLogger(BtRuntime.class);
/**
* @return Runtime builder with default configuration
* @since 1.0
*/
public static BtRuntimeBuilder builder() {
return new BtRuntimeBuilder();
}
/**
* @param config Custom configuration
* @return Runtime builder
* @since 1.0
*/
public static BtRuntimeBuilder builder(Config config) {
return new BtRuntimeBuilder(config);
}
/**
* Creates a vanilla runtime with default configuration
*
* @return Runtime without any extensions
* @since 1.0
*/
public static BtRuntime defaultRuntime() {
return builder().build();
}
private Injector injector;
private Config config;
private Set<BtClient> knownClients;
private ExecutorService clientExecutor;
private AtomicBoolean started;
private final Object lock;
private Thread hook;
private boolean manualShutdownOnly;
BtRuntime(Injector injector, Config config) {
this.injector = injector;
this.config = config;
this.knownClients = ConcurrentHashMap.newKeySet();
this.clientExecutor = injector.getBinding(Key.get(ExecutorService.class, ClientExecutor.class))
.getProvider().get();
this.started = new AtomicBoolean(false);
this.lock = new Object();
}
/**
* Disable automatic runtime shutdown, when all clients have been stopped.
*
* @since 1.0
*/
void disableAutomaticShutdown() {
this.manualShutdownOnly = true;
}
/**
* @return Injector instance
* @since 1.0
*/
public Injector getInjector() {
return injector;
}
/**
* @return Runtime configuration
* @since 1.0
*/
public Config getConfig() {
return config;
}
/**
* Convenience method to get an instance of a shared DI service.
*
* @return Instance of a shared DI service
* @since 1.0
*/
public <T> T service(Class<T> serviceType) {
return injector.getInstance(serviceType);
}
/**
* @return true if this runtime is up and running
* @since 1.0
*/
public boolean isRunning() {
return started.get();
}
/**
* Manually start the runtime (possibly with no clients attached).
*
* @since 1.0
*/
public void startup() {
if (started.compareAndSet(false, true)) {
synchronized (lock) {
runHooks(LifecycleEvent.STARTUP, e -> LOGGER.error("Error on runtime startup", e));
// add JVM shutdown hook
String threadName = String.format("%d.bt.runtime.shutdown-manager", config.getAcceptorPort());
this.hook = new Thread(threadName) {
@Override
public void run() {
shutdown();
}
};
Runtime.getRuntime().addShutdownHook(hook);
}
}
}
/**
* Attach the provided client to this runtime.
*
* @since 1.0
*/
public void attachClient(BtClient client) {
knownClients.add(client);
}
/**
* Detach the client from this runtime.
*
* @since 1.0
*/
public void detachClient(BtClient client) {
if (knownClients.remove(client)) {
if (!manualShutdownOnly && knownClients.isEmpty()) {
shutdown();
}
} else {
throw new IllegalArgumentException("Unknown client: " + client);
}
}
/**
* Get all clients, that are attached to this runtime.
*
* @since 1.1
*/
public Collection<BtClient> getClients() {
return Collections.unmodifiableCollection(knownClients);
}
/**
* @since 1.5
*/
public EventSource getEventSource() {
return service(EventSource.class);
}
/**
* Manually initiate the runtime shutdown procedure, which includes:
* - stopping all attached clients
* - stopping all workers and executors, that were created inside this runtime
* and registered via {@link IRuntimeLifecycleBinder}
*
* @since 1.0
*/
public void shutdown() {
if (started.compareAndSet(true, false)) {
synchronized (lock) {
knownClients.forEach(client -> {
try {
client.stop();
} catch (Throwable e) {
LOGGER.error("Error when stopping client", e);
}
});
try {
runHooks(LifecycleEvent.SHUTDOWN, this::onShutdownHookError);
clientExecutor.shutdownNow();
} finally {
try {
Runtime.getRuntime().removeShutdownHook(hook);
} catch (IllegalStateException e) {
// ISE means that the JVM is shutting down, no need to re-throw
}
}
}
}
}
private void runHooks(LifecycleEvent event, Consumer<Throwable> errorConsumer) {
ExecutorService executor = createLifecycleExecutor(event);
Map<LifecycleBinding, CompletableFuture<Void>> futures = new HashMap<>();
List<LifecycleBinding> syncBindings = new ArrayList<>();
service(IRuntimeLifecycleBinder.class).visitBindings(
event,
binding -> {
if (binding.isAsync()) {
futures.put(binding, CompletableFuture.runAsync(toRunnable(event, binding), executor));
} else {
syncBindings.add(binding);
}
});
syncBindings.forEach(binding -> {
String errorMessage = createErrorMessage(event, binding);
try {
toRunnable(event, binding).run();
} catch (Throwable e) {
errorConsumer.accept(new BtException(errorMessage, e));
}
});
// if the app is shutting down, then we must wait for the futures to complete
if (event == LifecycleEvent.SHUTDOWN) {
futures.forEach((binding, future) -> {
String errorMessage = createErrorMessage(event, binding);
try {
future.get(config.getShutdownHookTimeout().toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
errorConsumer.accept(new BtException(errorMessage, e));
}
});
}
shutdownGracefully(executor);
}
private String createErrorMessage(LifecycleEvent event, LifecycleBinding binding) {
Optional<String> descriptionOptional = binding.getDescription();
String errorMessage = "Failed to execute " + event.name().toLowerCase() + " hook: ";
errorMessage += ": " + (descriptionOptional.orElseGet(() -> binding.getRunnable().toString()));
return errorMessage;
}
private ExecutorService createLifecycleExecutor(LifecycleEvent event) {
AtomicInteger threadCount = new AtomicInteger();
return Executors.newCachedThreadPool(r -> {
String threadName = String.format("%d.bt.runtime.%s.worker-%d", config.getAcceptorPort(), event.name().toLowerCase(), threadCount.incrementAndGet());
Thread t = new Thread(r, threadName);
t.setDaemon(true);
return t;
});
}
private void shutdownGracefully(ExecutorService executor) {
executor.shutdown();
try {
long timeout = config.getShutdownHookTimeout().toMillis();
boolean terminated = executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
if (!terminated) {
LOGGER.warn("Failed to shutdown executor in {} millis", timeout);
}
} catch (InterruptedException e) {
// ignore
LOGGER.warn("Interrupted while waiting for shutdown", e);
executor.shutdownNow();
}
}
private Runnable toRunnable(LifecycleEvent event, LifecycleBinding binding) {
return () -> {
Runnable r = binding.getRunnable();
Optional<String> descriptionOptional = binding.getDescription();
String description = descriptionOptional.orElseGet(r::toString);
LOGGER.debug("Running " + event.name().toLowerCase() + " hook: " + description);
r.run();
};
}
private void onShutdownHookError(Throwable e) {
// logging facilities might be unavailable at this moment,
// so using standard output
e.printStackTrace(System.err);
System.err.flush();
}
}
|
9230c360513ef3eeb760562375d3ba7c609f333f | 686 | java | Java | src/main/java/com/synopsys/integration/wait/BooleanWaitJobCompleter.java | blackducksoftware/integration-common | ead99c1ac157be5b98349502482d2d793187f4f3 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/synopsys/integration/wait/BooleanWaitJobCompleter.java | blackducksoftware/integration-common | ead99c1ac157be5b98349502482d2d793187f4f3 | [
"Apache-2.0"
] | 24 | 2016-12-07T20:15:57.000Z | 2020-10-08T15:59:05.000Z | src/main/java/com/synopsys/integration/wait/BooleanWaitJobCompleter.java | blackducksoftware/integration-common | ead99c1ac157be5b98349502482d2d793187f4f3 | [
"Apache-2.0"
] | 5 | 2017-11-03T00:16:19.000Z | 2022-03-28T13:40:13.000Z | 27.44 | 142 | 0.762391 | 995,593 | /*
* integration-common
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.wait;
import com.synopsys.integration.exception.IntegrationException;
import com.synopsys.integration.exception.IntegrationTimeoutException;
public class BooleanWaitJobCompleter implements WaitJobCompleter<Boolean> {
@Override
public Boolean complete() throws IntegrationException {
return true;
}
@Override
public Boolean handleTimeout() throws IntegrationTimeoutException {
return false;
}
}
|
9230c423bef2392b5bab0156e5baa7ca551e60c6 | 14,732 | java | Java | platform/execution-impl/src/com/intellij/terminal/TerminalExecutionConsole.java | anatawa12/intellij-community | d2557a13699986aa174a8969952711130718e7a1 | [
"Apache-2.0"
] | null | null | null | platform/execution-impl/src/com/intellij/terminal/TerminalExecutionConsole.java | anatawa12/intellij-community | d2557a13699986aa174a8969952711130718e7a1 | [
"Apache-2.0"
] | null | null | null | platform/execution-impl/src/com/intellij/terminal/TerminalExecutionConsole.java | anatawa12/intellij-community | d2557a13699986aa174a8969952711130718e7a1 | [
"Apache-2.0"
] | null | null | null | 35.159905 | 141 | 0.726582 | 995,594 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.terminal;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.filters.Filter;
import com.intellij.execution.filters.HyperlinkInfo;
import com.intellij.execution.process.*;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.ObservableConsoleView;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.encoding.EncodingProjectManager;
import com.intellij.util.LineSeparator;
import com.intellij.util.ObjectUtils;
import com.jediterm.terminal.HyperlinkStyle;
import com.jediterm.terminal.TerminalStarter;
import com.jediterm.terminal.TtyConnector;
import com.jediterm.terminal.model.JediTerminal;
import com.jediterm.terminal.model.StyleState;
import com.jediterm.terminal.model.TerminalTextBuffer;
import com.jediterm.terminal.ui.settings.SettingsProvider;
import com.jediterm.terminal.util.CharUtils;
import com.pty4j.PtyProcess;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
public class TerminalExecutionConsole implements ConsoleView, ObservableConsoleView {
private static final Logger LOG = Logger.getInstance(TerminalExecutionConsole.class);
private final JBTerminalWidget myTerminalWidget;
private final Project myProject;
private final AppendableTerminalDataStream myDataStream;
private final AtomicBoolean myAttachedToProcess = new AtomicBoolean(false);
private volatile boolean myLastCR = false;
private final TerminalConsoleContentHelper myContentHelper = new TerminalConsoleContentHelper(this);
private boolean myEnterKeyDefaultCodeEnabled = true;
private boolean myConvertLfToCrlfForNonPtyProcess = false;
public TerminalExecutionConsole(@NotNull Project project, @Nullable ProcessHandler processHandler) {
this(project, 200, 24, processHandler);
}
public TerminalExecutionConsole(@NotNull Project project, int columns, int lines, @Nullable ProcessHandler processHandler) {
myProject = project;
myDataStream = new AppendableTerminalDataStream();
myTerminalWidget = new ConsoleTerminalWidget(project, columns, lines, getProvider());
if (processHandler != null) {
attachToProcess(processHandler);
}
}
@NotNull
private static JBTerminalSystemSettingsProviderBase getProvider() {
return new JBTerminalSystemSettingsProviderBase() {
@Override
public HyperlinkStyle.HighlightMode getHyperlinkHighlightingMode() {
return HyperlinkStyle.HighlightMode.ALWAYS;
}
};
}
public @NotNull JBTerminalWidget getTerminalWidget() {
return myTerminalWidget;
}
private void printText(@NotNull String text, @Nullable ConsoleViewContentType contentType) throws IOException {
Color foregroundColor = contentType != null ? contentType.getAttributes().getForegroundColor() : null;
if (foregroundColor != null) {
myDataStream.append(encodeColor(foregroundColor));
}
myDataStream.append(text);
if (foregroundColor != null) {
myDataStream.append((char)CharUtils.ESC + "[39m"); //restore default foreground color
}
myContentHelper.onContentTypePrinted(text, ObjectUtils.notNull(contentType, ConsoleViewContentType.NORMAL_OUTPUT));
}
@Override
public void addChangeListener(@NotNull ChangeListener listener, @NotNull Disposable parent) {
myContentHelper.addChangeListener(listener, parent);
}
@NotNull
private static String encodeColor(@NotNull Color color) {
return ((char)CharUtils.ESC) + "[" + "38;2;" + color.getRed() + ";" + color.getGreen() + ";" +
color.getBlue() + "m";
}
/**
* @deprecated use {@link #withEnterKeyDefaultCodeEnabled(boolean)}
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public void setAutoNewLineMode(@SuppressWarnings("unused") boolean enabled) {
}
@NotNull
public TerminalExecutionConsole withEnterKeyDefaultCodeEnabled(boolean enterKeyDefaultCodeEnabled) {
myEnterKeyDefaultCodeEnabled = enterKeyDefaultCodeEnabled;
return this;
}
public @NotNull TerminalExecutionConsole withConvertLfToCrlfForNonPtyProcess(boolean convertLfToCrlfForNonPtyProcess) {
myConvertLfToCrlfForNonPtyProcess = convertLfToCrlfForNonPtyProcess;
return this;
}
/**
* @deprecated use {{@link #addMessageFilter(Filter)}} instead
*/
@ApiStatus.ScheduledForRemoval(inVersion = "2020.3")
@Deprecated
public void addMessageFilter(Project project, Filter filter) {
myTerminalWidget.addMessageFilter(filter);
}
@Override
public void print(@NotNull String text, @NotNull ConsoleViewContentType contentType) {
// Convert line separators to CRLF to behave like ConsoleViewImpl.
// For example, stacktraces passed to com.intellij.execution.testframework.sm.runner.SMTestProxy.setTestFailed have
// only LF line separators on Unix.
String textCRLF = convertTextToCRLF(text);
try {
printText(textCRLF, contentType);
}
catch (IOException e) {
LOG.info(e);
}
}
@NotNull
private String convertTextToCRLF(@NotNull String text) {
if (text.isEmpty()) return text;
// Handle the case when \r and \n are in different chunks: "text1 \r" and "\n text2"
boolean preserveFirstLF = text.startsWith(LineSeparator.LF.getSeparatorString()) && myLastCR;
boolean preserveLastCR = text.endsWith(LineSeparator.CR.getSeparatorString());
myLastCR = preserveLastCR;
String textToConvert = text.substring(preserveFirstLF ? 1 : 0, preserveLastCR ? text.length() - 1 : text.length());
String textCRLF = StringUtil.convertLineSeparators(textToConvert, LineSeparator.CRLF.getSeparatorString());
if (preserveFirstLF) {
textCRLF = LineSeparator.LF.getSeparatorString() + textCRLF;
}
if (preserveLastCR) {
textCRLF += LineSeparator.CR.getSeparatorString();
}
return textCRLF;
}
/**
* Clears history and screen buffers, positions the cursor at the top left corner.
*/
@Override
public void clear() {
myLastCR = false;
myTerminalWidget.getTerminalPanel().clearBuffer();
}
@Override
public void scrollTo(int offset) {
}
@Override
public void attachToProcess(@NotNull ProcessHandler processHandler) {
attachToProcess(processHandler, true);
}
/**
* @param processHandler ProcessHandler instance wrapping underlying PtyProcess
* @param attachToProcessOutput true if process output should be printed in the console,
* false if output printing is managed externally, e.g. by testing
* console {@link com.intellij.execution.testframework.ui.BaseTestsOutputConsoleView}
*/
protected final void attachToProcess(@NotNull ProcessHandler processHandler, boolean attachToProcessOutput) {
if (!myAttachedToProcess.compareAndSet(false, true)) {
return;
}
myTerminalWidget.createTerminalSession(new ProcessHandlerTtyConnector(
processHandler, EncodingProjectManager.getInstance(myProject).getDefaultCharset())
);
myTerminalWidget.start();
processHandler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
if (attachToProcessOutput) {
try {
ConsoleViewContentType contentType = null;
if (outputType != ProcessOutputTypes.STDOUT) {
contentType = ConsoleViewContentType.getConsoleViewType(outputType);
}
String text = event.getText();
if (outputType == ProcessOutputTypes.SYSTEM) {
text = StringUtil.convertLineSeparators(text, LineSeparator.CRLF.getSeparatorString());
}
else if (shouldConvertLfToCrlf(processHandler)) {
text = convertTextToCRLF(text);
}
printText(text, contentType);
}
catch (IOException e) {
LOG.info(e);
}
}
}
@Override
public void processTerminated(@NotNull ProcessEvent event) {
myAttachedToProcess.set(false);
ApplicationManager.getApplication().invokeLater(() -> {
myTerminalWidget.getTerminalPanel().setCursorVisible(false);
}, ModalityState.any());
}
});
}
private boolean shouldConvertLfToCrlf(@NotNull ProcessHandler processHandler) {
return myConvertLfToCrlfForNonPtyProcess && isNonPtyProcess(processHandler);
}
private static boolean isNonPtyProcess(@NotNull ProcessHandler processHandler) {
if (processHandler instanceof BaseProcessHandler) {
Process process = ((BaseProcessHandler<?>)processHandler).getProcess();
return !(process instanceof PtyProcess);
}
return true;
}
@Override
public void setOutputPaused(boolean value) {
}
@Override
public boolean isOutputPaused() {
return false;
}
@Override
public boolean hasDeferredOutput() {
return false;
}
@Override
public void performWhenNoDeferredOutput(@NotNull Runnable runnable) {
}
@Override
public void setHelpId(@NotNull String helpId) {
}
@Override
public void addMessageFilter(@NotNull Filter filter) {
myTerminalWidget.addMessageFilter(filter);
}
@Override
public void printHyperlink(@NotNull String hyperlinkText, @Nullable HyperlinkInfo info) {
}
@Override
public int getContentSize() {
return 0;
}
@Override
public boolean canPause() {
return false;
}
@Override
public AnAction @NotNull [] createConsoleActions() {
return new AnAction[]{new ScrollToTheEndAction(), new ClearAction()};
}
@Override
public void allowHeavyFilters() {
}
@NotNull
@Override
public JComponent getComponent() {
return myTerminalWidget.getComponent();
}
@Override
public JComponent getPreferredFocusableComponent() {
return myTerminalWidget.getComponent();
}
@Override
public void dispose() {
}
public static boolean isAcceptable(@NotNull ProcessHandler processHandler) {
return processHandler instanceof OSProcessHandler &&
((OSProcessHandler)processHandler).getProcess() instanceof PtyProcess &&
!(processHandler instanceof ColoredProcessHandler);
}
private final class ConsoleTerminalWidget extends JBTerminalWidget implements DataProvider {
private ConsoleTerminalWidget(@NotNull Project project, int columns, int lines, @NotNull JBTerminalSystemSettingsProviderBase provider) {
super(project, columns, lines, provider, TerminalExecutionConsole.this, TerminalExecutionConsole.this);
}
@Override
protected JBTerminalPanel createTerminalPanel(@NotNull SettingsProvider settingsProvider,
@NotNull StyleState styleState,
@NotNull TerminalTextBuffer textBuffer) {
JBTerminalPanel panel = new JBTerminalPanel((JBTerminalSystemSettingsProviderBase)settingsProvider, textBuffer, styleState) {
@Override
public void clearBuffer() {
super.clearBuffer(false);
}
};
Disposer.register(this, panel);
return panel;
}
@Override
protected TerminalStarter createTerminalStarter(JediTerminal terminal, TtyConnector connector) {
return new TerminalStarter(terminal, connector, myDataStream) {
@Override
public byte[] getCode(int key, int modifiers) {
if (key == KeyEvent.VK_ENTER && modifiers == 0 && myEnterKeyDefaultCodeEnabled) {
PtyProcess process = getPtyProcess();
return process != null ? new byte[]{process.getEnterKeyCode()} : LineSeparator.CR.getSeparatorBytes();
}
return super.getCode(key, modifiers);
}
};
}
@Nullable
@Override
public Object getData(@NotNull String dataId) {
if (LangDataKeys.CONSOLE_VIEW.is(dataId)) {
return TerminalExecutionConsole.this;
}
return super.getData(dataId);
}
}
private @Nullable PtyProcess getPtyProcess() {
ProcessHandlerTtyConnector phc = ObjectUtils.tryCast(myTerminalWidget.getTtyConnector(), ProcessHandlerTtyConnector.class);
return phc != null ? phc.getPtyProcess() : null;
}
private final class ClearAction extends DumbAwareAction {
private ClearAction() {
super(ExecutionBundle.messagePointer("clear.all.from.console.action.name"),
ExecutionBundle.messagePointer("clear.all.from.console.action.text"), AllIcons.Actions.GC);
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(true);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
clear();
}
}
private final class ScrollToTheEndAction extends DumbAwareAction {
private ScrollToTheEndAction() {
super(ActionsBundle.messagePointer("action.EditorConsoleScrollToTheEnd.text"),
ActionsBundle.messagePointer("action.EditorConsoleScrollToTheEnd.text"),
AllIcons.RunConfigurations.Scroll_down);
}
@Override
public void update(@NotNull AnActionEvent e) {
BoundedRangeModel model = getBoundedRangeModel();
e.getPresentation().setEnabled(model != null && model.getValue() != 0);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
BoundedRangeModel model = getBoundedRangeModel();
if (model != null) {
model.setValue(0);
}
}
@Nullable
private BoundedRangeModel getBoundedRangeModel() {
return myTerminalWidget != null ? myTerminalWidget.getTerminalPanel().getBoundedRangeModel() : null;
}
}
}
|
9230c44093081e510d83569e3c801a583d800f10 | 1,108 | java | Java | src/test/java/jgraphs/subsystem/traceability/TraceabilityTest.java | vicegd/jgraphs | 7a58124e816667573b4024f93d562081ec2dd075 | [
"Unlicense"
] | 3 | 2020-01-29T13:38:03.000Z | 2021-12-27T20:56:23.000Z | src/test/java/jgraphs/subsystem/traceability/TraceabilityTest.java | vicegd/jgraphs | 7a58124e816667573b4024f93d562081ec2dd075 | [
"Unlicense"
] | 1 | 2022-01-21T23:34:58.000Z | 2022-01-21T23:34:58.000Z | src/test/java/jgraphs/subsystem/traceability/TraceabilityTest.java | vicegd/jgraphs | 7a58124e816667573b4024f93d562081ec2dd075 | [
"Unlicense"
] | null | null | null | 33.575758 | 137 | 0.756318 | 995,595 | package jgraphs.subsystem.traceability;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import jgraphs.algorithm.backtracking.BacktrackingAll;
import jgraphs.app.permutation.PermutationModule;
import jgraphs.app.permutation.PermutationSituation;
import jgraphs.utils.Dependency;
import jgraphs.utils.module.EModuleConfiguration;
public class TraceabilityTest {
private BacktrackingAll backtracking;
private DefaultTraceability tracebility;
@Before
public void initialize() {
this.backtracking = Dependency.getInstance(new PermutationModule(EModuleConfiguration.BASIC)).getInjector(BacktrackingAll.class);
this.tracebility = new DefaultTraceability();
this.backtracking.addTraceability(this.tracebility);
}
@Test
public void givenStructureWith2Nodes_tracebility_thenTrace() {
var tree = this.backtracking.getStructure();
tree.setFirstSituation(new PermutationSituation(1));
this.backtracking.run();
assertEquals(2, this.tracebility.getStops());
}
}
|
9230c45ad02923e43495bf148bad6b1b4d6cd2a5 | 1,509 | java | Java | app/src/main/java/com/codepath/ingram/simpletodo/EditActivity.java | Ing-Ram/simpletodo | c4b3b6c20818bc85f3009339fc9e2728d36665ff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/codepath/ingram/simpletodo/EditActivity.java | Ing-Ram/simpletodo | c4b3b6c20818bc85f3009339fc9e2728d36665ff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/codepath/ingram/simpletodo/EditActivity.java | Ing-Ram/simpletodo | c4b3b6c20818bc85f3009339fc9e2728d36665ff | [
"Apache-2.0"
] | null | null | null | 32.804348 | 128 | 0.654076 | 995,596 | package com.codepath.ingram.simpletodo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditActivity extends AppCompatActivity {
EditText etItem;
Button btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
etItem = findViewById(R.id.etText);
btnSave = findViewById(R.id.btnSave);
getSupportActionBar().setTitle("Edit item");
etItem.setText(getIntent().getStringExtra(MainActivity.KEY_ITEM_TEXT));
// When the user is done editing and click the save button
btnSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// create and in intent which will con the thr results
Intent intent = new Intent();
// pass the data[results of editing the data
intent.putExtra(MainActivity.KEY_ITEM_TEXT, etItem.getText().toString());
intent.putExtra(MainActivity.KEY_ITEM_POSITION, getIntent().getExtras().getInt(MainActivity.KEY_ITEM_POSITION));
// set the results of the intent
setResult(RESULT_OK, intent);
//finish the activity
finish();
}
});
}
} |
9230c54709d524ac860c2765e5290886f4e5813b | 411 | java | Java | src/main/java/com/mindware/capture/repository/informix/PrconRepository.java | ideat/capture | 2b8a33075cc6d834530f201b003ea8401707487e | [
"Unlicense"
] | null | null | null | src/main/java/com/mindware/capture/repository/informix/PrconRepository.java | ideat/capture | 2b8a33075cc6d834530f201b003ea8401707487e | [
"Unlicense"
] | null | null | null | src/main/java/com/mindware/capture/repository/informix/PrconRepository.java | ideat/capture | 2b8a33075cc6d834530f201b003ea8401707487e | [
"Unlicense"
] | null | null | null | 31.615385 | 90 | 0.83455 | 995,597 | package com.mindware.capture.repository.informix;
import com.mindware.capture.model.informix.Prcon;
import com.mindware.capture.model.informix.PrconId;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface PrconRepository extends JpaRepository<Prcon, PrconId> {
Optional<Prcon> findByIdPrconprefAndIdPrconcorr(Integer prconprer, Integer prconcorr);
}
|
9230c6b346a9bab865f0e74716f5ea8d2f365ca7 | 849 | java | Java | YukCommon/src/yukcommon/net/NetWrapper.java | yukyongsoo/csp | a40e168b9ce835c718d5f5881595d2cfe309c398 | [
"Apache-2.0"
] | 1 | 2018-09-11T17:32:39.000Z | 2018-09-11T17:32:39.000Z | YukCommon/src/yukcommon/net/NetWrapper.java | yukyongsoo/csp | a40e168b9ce835c718d5f5881595d2cfe309c398 | [
"Apache-2.0"
] | null | null | null | YukCommon/src/yukcommon/net/NetWrapper.java | yukyongsoo/csp | a40e168b9ce835c718d5f5881595d2cfe309c398 | [
"Apache-2.0"
] | null | null | null | 35.375 | 103 | 0.812721 | 995,598 | package yukcommon.net;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import yukcommon.model.fileitem.IFileItem;
public interface NetWrapper {
void setFile(String localFile) throws FileNotFoundException;
void setFile(InputStream stream);
void addHeader(String name, String value);
IFileItem getFiles();
String getHeaderValue(String headerName) ;
String getHeaderValueNotException(String headerName);
void setResponse(HttpResponse response) throws IOException, InterruptedException, ExecutionException;
HttpUriRequest getRequest() throws URISyntaxException;
void close() throws IOException;
} |
9230c6e1dff75c9f9e12b984b792500b8adba097 | 4,128 | java | Java | hackerrank/src/com/matija/medium/QueensAttack.java | matija94/show-me-the-code | 7e98b15da03712e28417f2c808c4324989ce9bd7 | [
"MIT"
] | 1 | 2017-07-10T21:05:46.000Z | 2017-07-10T21:05:46.000Z | hackerrank/src/com/matija/medium/QueensAttack.java | matija94/show-me-the-code | 7e98b15da03712e28417f2c808c4324989ce9bd7 | [
"MIT"
] | null | null | null | hackerrank/src/com/matija/medium/QueensAttack.java | matija94/show-me-the-code | 7e98b15da03712e28417f2c808c4324989ce9bd7 | [
"MIT"
] | null | null | null | 26.632258 | 92 | 0.425145 | 995,599 | package com.matija.medium;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class QueensAttack {
static int queensAttack(int n, int k, int r_q, int c_q, int[][] obstacles) {
List<String> cells = new ArrayList<>();
Set<String> obstaclez = getObstacles(obstacles);
leftUpD(n, r_q, c_q, cells, obstaclez);
up(n, r_q, c_q, cells, obstaclez);
rightUpD(n, r_q, c_q, cells, obstaclez);
left(n, r_q, c_q, cells, obstaclez);
right(n, r_q, c_q, cells, obstaclez);
leftDownD(n, r_q, c_q, cells, obstaclez);
down(n, r_q, c_q, cells, obstaclez);
rightDownD(n, r_q, c_q, cells, obstaclez);
return cells.size();
}
static Set<String> getObstacles(int[][] obstacles) {
Set<String> obstaclez = new HashSet<>();
for(int i = 0; i < obstacles.length; i++) {
String cell = obstacles[i][0] + " " + obstacles[i][1];
obstaclez.add(cell);
}
return obstaclez;
}
static void leftUpD(int n, int r, int c, List<String> cells, Set<String> obstacles) {
r++;
c--;
while(r <= n && c > 0) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
r++;
c--;
}
}
static void up(int n, int r, int c, List<String> cells, Set<String> obstacles) {
r++;
while (r <= n) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
r++;
}
}
static void rightUpD(int n, int r, int c, List<String> cells, Set<String> obstacles) {
r++;
c++;
while (r <= n && c <= n) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
r++;
c++;
}
}
static void left(int n, int r, int c, List<String> cells, Set<String> obstacles) {
c--;
while (c > 0) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
c--;
}
}
static void right(int n, int r, int c, List<String> cells, Set<String> obstacles) {
c++;
while (c <= n) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
c++;
}
}
static void leftDownD(int n, int r, int c, List<String> cells, Set<String> obstacles) {
r--;
c--;
while(r > 0 && c > 0) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
r--;
c--;
}
}
static void down(int n, int r, int c, List<String> cells, Set<String> obstacles) {
r--;
while (r > 0) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
r--;
}
}
static void rightDownD(int n, int r, int c, List<String> cells, Set<String> obstacles) {
r--;
c++;
while(r > 0 && c <= n) {
String cell = r + " " + c;
if (!obstacles.contains(cell)) {
cells.add(cell);
}else {
return;
}
r--;
c++;
}
}
public static void main(String[] args) {
System.out.println(queensAttack(5, 3, 4, 3, new int[][]{
new int[]{5, 5},
new int[]{4, 2},
new int[]{2, 3}
}));
}
}
|
9230c6fdd304b9092e59cc0ca4e808ba8032cb16 | 527 | java | Java | AndroidStudioSdk/xilqp/src/main/java/com/quanyou/xilqp/QuanyouApplication.java | cuibo10/Android_Unity_Sdk_Plugins | 269e34e86bf5ab8ae5367de63dd440b7a78d8afa | [
"Apache-2.0"
] | null | null | null | AndroidStudioSdk/xilqp/src/main/java/com/quanyou/xilqp/QuanyouApplication.java | cuibo10/Android_Unity_Sdk_Plugins | 269e34e86bf5ab8ae5367de63dd440b7a78d8afa | [
"Apache-2.0"
] | null | null | null | AndroidStudioSdk/xilqp/src/main/java/com/quanyou/xilqp/QuanyouApplication.java | cuibo10/Android_Unity_Sdk_Plugins | 269e34e86bf5ab8ae5367de63dd440b7a78d8afa | [
"Apache-2.0"
] | null | null | null | 19.518519 | 90 | 0.70019 | 995,600 | package com.quanyou.xilqp;
import android.app.Application;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
/**
* Created by MrLovelyCbb on 2017/11/13.
*/
public class QuanyouApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
Config.DEBUG = true;
UMShareAPI.get(this);
}
{
PlatformConfig.setWeixin("wx46d63814bc3ba66e","5daf0095dcb43e6e154f8294448e65cb");
}
}
|
9230c8d2e0e79f64b96f241882d35b9099ce20aa | 1,874 | java | Java | hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/HapiFlywayMigrateDatabaseCommand.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,194 | 2015-01-01T23:22:15.000Z | 2020-12-12T19:27:42.000Z | hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/HapiFlywayMigrateDatabaseCommand.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,994 | 2015-01-04T10:06:26.000Z | 2020-12-13T22:19:41.000Z | hapi-fhir-cli/hapi-fhir-cli-api/src/main/java/ca/uhn/fhir/cli/HapiFlywayMigrateDatabaseCommand.java | ShahimEssaid/hapi-fhir | 06030094c803deac725be5bf63e4d1ce7bb26b6d | [
"Apache-2.0"
] | 1,088 | 2015-01-04T19:31:43.000Z | 2020-12-12T20:56:04.000Z | 31.762712 | 101 | 0.772679 | 995,601 | package ca.uhn.fhir.cli;
/*-
* #%L
* HAPI FHIR - Command Line Client - API
* %%
* Copyright (C) 2014 - 2022 Smile CDR, Inc.
* %%
* 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.
* #L%
*/
import ca.uhn.fhir.jpa.migrate.BaseMigrator;
import ca.uhn.fhir.jpa.migrate.SchemaMigrator;
import ca.uhn.fhir.jpa.migrate.taskdef.BaseTask;
import ca.uhn.fhir.jpa.migrate.tasks.HapiFhirJpaMigrationTasks;
import ca.uhn.fhir.util.VersionEnum;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;
import java.util.Arrays;
import java.util.List;
public class HapiFlywayMigrateDatabaseCommand extends BaseFlywayMigrateDatabaseCommand<VersionEnum> {
@Override
protected List<VersionEnum> provideAllowedVersions() {
return Arrays.asList(VersionEnum.values());
}
@Override
protected Class<VersionEnum> provideVersionEnumType() {
return VersionEnum.class;
}
@Override
protected void addTasks(BaseMigrator theMigrator, String theSkipVersions) {
List<BaseTask> tasks = new HapiFhirJpaMigrationTasks(getFlags()).getAllTasks(VersionEnum.values());
super.setDoNothingOnSkippedTasks(tasks, theSkipVersions);
theMigrator.addTasks(tasks);
}
@Override
public void run(CommandLine theCommandLine) throws ParseException {
setMigrationTableName(SchemaMigrator.HAPI_FHIR_MIGRATION_TABLENAME);
super.run(theCommandLine);
}
}
|
9230c9234b4f6ce4f70e5056feb2cc01e6bb01e6 | 432 | java | Java | java-basic/design-pattern/src/main/java/com/desgin/principle/dependencyInversion/v2/Client.java | lastwhispers/code | 8d4b926c5577525828e4f077e3901f4e869c7e4a | [
"Apache-2.0"
] | 59 | 2020-04-08T06:48:13.000Z | 2021-11-10T06:20:36.000Z | java-basic/design-pattern/src/main/java/com/desgin/principle/dependencyInversion/v2/Client.java | lastwhispers/code | 8d4b926c5577525828e4f077e3901f4e869c7e4a | [
"Apache-2.0"
] | 26 | 2020-11-01T03:16:16.000Z | 2022-03-18T02:50:29.000Z | java-basic/design-pattern/src/main/java/com/desgin/principle/dependencyInversion/v2/Client.java | lastwhispers/code | 8d4b926c5577525828e4f077e3901f4e869c7e4a | [
"Apache-2.0"
] | 44 | 2020-04-09T01:34:40.000Z | 2021-03-02T12:33:23.000Z | 24 | 57 | 0.631944 | 995,602 | package com.desgin.principle.dependencyInversion.v2;
/**
* @author lastwhisper
*/
public class Client {
public static void main(String[] args){
// 此时动态修改轮胎的大小不需要修改Car、Framework、Bottom、Tire的内部代码
// 这段初始化代码就是 控制反转容器
Tire tire = new Tire(30);
Bottom bottom = new Bottom(tire);
Framework framework = new Framework(bottom);
Car car = new Car(framework);
car.run();
}
}
|
9230ca60a40476fd46e0fbc24465d4965b951a3b | 12,874 | java | Java | src/main/java/org/hzero/oauth/security/config/SecurityConfiguration.java | yang-zhang99/hzero-oauth | cd8a77c175aa7ed8e7e84b0dafe4539889fc990c | [
"Apache-2.0"
] | 5 | 2021-04-02T07:34:18.000Z | 2021-12-23T22:59:11.000Z | src/main/java/org/hzero/oauth/security/config/SecurityConfiguration.java | yang-zhang99/hzero-oauth | cd8a77c175aa7ed8e7e84b0dafe4539889fc990c | [
"Apache-2.0"
] | 2 | 2020-11-07T15:17:39.000Z | 2021-07-26T11:48:11.000Z | src/main/java/org/hzero/oauth/security/config/SecurityConfiguration.java | yang-zhang99/hzero-oauth | cd8a77c175aa7ed8e7e84b0dafe4539889fc990c | [
"Apache-2.0"
] | 19 | 2020-09-23T07:52:14.000Z | 2022-03-04T06:27:25.000Z | 43.491582 | 149 | 0.761709 | 995,603 | package org.hzero.oauth.security.config;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.PortMapperImpl;
import org.springframework.security.web.PortResolver;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.session.SessionRepository;
import org.hzero.boot.oauth.domain.repository.BaseClientRepository;
import org.hzero.boot.oauth.domain.repository.BaseLdapRepository;
import org.hzero.boot.oauth.domain.repository.BasePasswordPolicyRepository;
import org.hzero.boot.oauth.domain.service.BaseUserService;
import org.hzero.boot.oauth.domain.service.PasswordErrorTimesService;
import org.hzero.boot.oauth.policy.PasswordPolicyManager;
import org.hzero.core.captcha.CaptchaImageHelper;
import org.hzero.core.redis.RedisHelper;
import org.hzero.oauth.domain.repository.AuditLoginRepository;
import org.hzero.oauth.domain.repository.ClientRepository;
import org.hzero.oauth.domain.repository.UserRepository;
import org.hzero.oauth.domain.service.AuditLoginService;
import org.hzero.oauth.domain.service.impl.AuditLoginServiceImpl;
import org.hzero.oauth.infra.constant.Constants;
import org.hzero.oauth.infra.encrypt.EncryptClient;
import org.hzero.oauth.security.custom.*;
import org.hzero.oauth.security.custom.processor.login.LoginSuccessProcessor;
import org.hzero.oauth.security.custom.processor.logout.LogoutSuccessProcessor;
import org.hzero.oauth.security.resource.ResourceMatcher;
import org.hzero.oauth.security.resource.impl.MobileResourceMatcher;
import org.hzero.oauth.security.service.*;
import org.hzero.oauth.security.service.impl.*;
import org.hzero.oauth.security.social.*;
import org.hzero.oauth.security.sso.DefaultSsoUserAccountService;
import org.hzero.oauth.security.sso.DefaultSsoUserDetailsBuilder;
import org.hzero.oauth.security.util.LoginUtil;
import org.hzero.sso.core.config.SsoProperties;
import org.hzero.sso.core.domain.repository.DomainRepository;
import org.hzero.sso.core.security.service.SsoUserAccountService;
import org.hzero.sso.core.security.service.SsoUserDetailsBuilder;
import org.hzero.starter.social.core.provider.SocialProviderRepository;
import org.hzero.starter.social.core.provider.SocialUserProviderRepository;
import org.hzero.starter.social.core.security.SocialAuthenticationProvider;
import org.hzero.starter.social.core.security.SocialSuccessHandler;
import org.hzero.starter.social.core.security.SocialUserDetailsService;
/**
* Oauth 服务配置
*
* @author bojiangzhou 2018/08/02
*/
@Configuration
@EnableConfigurationProperties({SecurityProperties.class})
public class SecurityConfiguration {
@Autowired
private CaptchaImageHelper captchaImageHelper;
@Autowired
private RedisHelper redisHelper;
@Autowired
private UserRepository userRepository;
@Autowired
private SecurityProperties securityProperties;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Autowired
private LoginUtil loginUtil;
@Autowired(required = false)
private DomainRepository domainRepository;
@Autowired
private SsoProperties ssoProperties;
@Autowired
private BaseUserService baseUserService;
@Autowired
private BaseLdapRepository baseLdapRepository;
@Autowired
private BasePasswordPolicyRepository basePasswordPolicyRepository;
@Autowired
private BaseClientRepository baseClientRepository;
@Autowired
private PasswordErrorTimesService passwordErrorTimesService;
@Autowired
private PasswordPolicyManager passwordPolicyManager;
@Autowired
private SessionRepository<?> sessionRepository;
@Autowired
private AuditLoginRepository auditLoginRepository;
@Bean
@ConditionalOnMissingBean(ResourceMatcher.class)
@ConditionalOnProperty(prefix = SecurityProperties.PREFIX, name = "custom-resource-matcher", havingValue = "true")
public ResourceMatcher resourceMatcher () {
return new MobileResourceMatcher();
}
/**
* 用户账户业务服务
*/
@Bean
@ConditionalOnMissingBean(UserAccountService.class)
public UserAccountService userAccountService() {
return new DefaultUserAccountService(this.userRepository, this.baseUserService, this.passwordPolicyManager,
this.basePasswordPolicyRepository, this.baseClientRepository, this.securityProperties);
}
/**
* 登录记录业务服务
*/
@Bean
@ConditionalOnMissingBean(LoginRecordService.class)
public LoginRecordService loginRecordService() {
return new DefaultLoginRecordService(baseUserService, passwordErrorTimesService, basePasswordPolicyRepository, redisHelper);
}
@Bean
@ConditionalOnMissingBean(UserDetailsWrapper.class)
public UserDetailsWrapper userDetailsWrapper(RedisHelper redisHelper) {
return new DefaultUserDetailsWrapper(userRepository, redisHelper);
}
@Bean
@ConditionalOnMissingBean(ClientDetailsWrapper.class)
public ClientDetailsWrapper clientDetailsWrapper(ClientRepository clientRepository) {
return new DefaultClientDetailsWrapper(clientRepository);
}
@Bean
@ConditionalOnMissingBean(UserDetailsBuilder.class)
public UserDetailsBuilder userDetailsBuilder(UserDetailsWrapper userDetailsWrapper) {
return new DefaultUserDetailsBuilder(userDetailsWrapper, domainRepository, ssoProperties, userAccountService());
}
/**
* Sso用户账户业务服务
*/
@Bean
@ConditionalOnMissingBean(SsoUserAccountService.class)
public SsoUserAccountService ssoUserAccountService() {
return new DefaultSsoUserAccountService(userRepository, securityProperties);
}
@Bean
@ConditionalOnMissingBean(SsoUserDetailsBuilder.class)
public SsoUserDetailsBuilder ssoUserDetailsBuilder(UserDetailsWrapper userDetailsWrapper) {
return new DefaultSsoUserDetailsBuilder(userDetailsWrapper, domainRepository, ssoProperties, userAccountService());
}
@Bean
@ConditionalOnMissingBean(CustomAuthenticationDetailsSource.class)
public CustomAuthenticationDetailsSource authenticationDetailsSource () {
return new CustomAuthenticationDetailsSource(captchaImageHelper);
}
@Bean
@ConditionalOnMissingBean(CustomAuthenticationSuccessHandler.class)
public CustomAuthenticationSuccessHandler authenticationSuccessHandler (List<LoginSuccessProcessor> successProcessors) {
return new CustomAuthenticationSuccessHandler(securityProperties, successProcessors);
}
@Bean
@ConditionalOnMissingBean(AuditLoginService.class)
public AuditLoginService auditLoginService () {
return new AuditLoginServiceImpl(auditLoginRepository, userRepository, tokenStore());
}
@Bean
@ConditionalOnMissingBean(CustomAuthenticationFailureHandler.class)
public CustomAuthenticationFailureHandler authenticationFailureHandler () {
return new CustomAuthenticationFailureHandler(loginRecordService(), securityProperties, auditLoginService());
}
@Bean
@ConditionalOnMissingBean(CustomLogoutSuccessHandler.class)
public CustomLogoutSuccessHandler logoutSuccessHandler (List<LogoutSuccessProcessor> postProcessors) {
return new CustomLogoutSuccessHandler(tokenStore(), loginRecordService(), securityProperties, ssoProperties,domainRepository,
userAccountService() , postProcessors);
}
@Bean
@ConditionalOnMissingBean(CustomUserDetailsService.class)
public CustomUserDetailsService userDetailsService (UserAccountService userAccountService,
UserDetailsBuilder userDetailsBuilder,
LoginRecordService loginRecordService) {
return new CustomUserDetailsService(userAccountService, userDetailsBuilder, loginRecordService);
}
//@Bean
dycjh@example.com)
//public CustomClientDetailsService clientDetailsService (BaseClientRepository baseClientRepository, ClientDetailsWrapper clientDetailsWrapper) {
// return new CustomClientDetailsService(baseClientRepository, clientDetailsWrapper);
//}
@Bean
@ConditionalOnMissingBean(CustomAuthenticationProvider.class)
public CustomAuthenticationProvider authenticationProvider (CustomUserDetailsService userDetailsService,
EncryptClient encryptClient,
PasswordEncoder passwordEncoder) {
CustomAuthenticationProvider provider = new CustomAuthenticationProvider(
userDetailsService, baseLdapRepository,
userAccountService(), loginRecordService(),
captchaImageHelper, securityProperties,
encryptClient, userRepository);
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
@Bean
@ConditionalOnMissingBean(CustomAuthenticationKeyGenerator.class)
public CustomAuthenticationKeyGenerator authenticationKeyGenerator () {
return new CustomAuthenticationKeyGenerator(loginUtil);
}
@Bean
@ConditionalOnMissingBean(CustomRedisTokenStore.class)
public CustomRedisTokenStore tokenStore() {
CustomRedisTokenStore redisTokenStore = new CustomRedisTokenStore(redisConnectionFactory, loginUtil, sessionRepository);
redisTokenStore.setAuthenticationKeyGenerator(authenticationKeyGenerator());
redisTokenStore.setPrefix(Constants.CacheKey.ACCESS_TOKEN);
return redisTokenStore;
}
//
// social config
// ------------------------------------------------------------------------------
@Bean
@ConditionalOnMissingBean(SocialProviderRepository.class)
public SocialProviderRepository socialProviderRepository() {
return new CustomSocialProviderRepository();
}
@Bean
@ConditionalOnMissingBean(SocialUserProviderRepository.class)
public SocialUserProviderRepository socialUserProviderRepository() {
return new CustomSocialUserProviderRepository();
}
@Bean
@ConditionalOnMissingBean(SocialUserDetailsService.class)
public SocialUserDetailsService socialUserDetailsService(UserAccountService userAccountService,
UserDetailsBuilder userDetailsBuilder,
LoginRecordService loginRecordService) {
return new CustomSocialUserDetailsService(userAccountService, userDetailsBuilder, loginRecordService);
}
@Bean
@ConditionalOnMissingBean(SocialAuthenticationProvider.class)
public SocialAuthenticationProvider socialAuthenticationProvider(SocialUserProviderRepository socialUserProviderRepository,
SocialUserDetailsService socialUserDetailsService) {
return new CustomSocialAuthenticationProvider(socialUserProviderRepository, socialUserDetailsService);
}
@Bean
@ConditionalOnMissingBean(SocialSuccessHandler.class)
public SocialSuccessHandler socialSuccessHandler(SecurityProperties securityProperties,
List<LoginSuccessProcessor> successProcessors) {
return new CustomSocialSuccessHandler(securityProperties, successProcessors);
}
@Bean
@ConditionalOnMissingBean(CustomSocialFailureHandler.class)
public CustomSocialFailureHandler socialFailureHandler(SecurityProperties securityProperties) {
return new CustomSocialFailureHandler(securityProperties);
}
@Bean
public PortMapper portMapper() {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> portMap = securityProperties.getPortMapper().stream()
.collect(Collectors.toMap(m -> String.valueOf(m.getSourcePort()), m -> String.valueOf(m.getSourcePort())));
portMapper.setPortMappings(portMap);
return portMapper;
}
@Bean
public PortResolver portResolver() {
PortResolverImpl portResolver = new PortResolverImpl();
portResolver.setPortMapper(portMapper());
return portResolver;
}
}
|
9230ca8f249e217ff39931ec28bd1f28d1fd63c8 | 8,523 | java | Java | tests/robotests/src/com/android/settings/development/qstile/WirelessDebuggingTest.java | Deepak5310/packages_apps_Settings | 0b341cc2a61f913d3c5474d53fc961bf00ae7924 | [
"Apache-2.0"
] | null | null | null | tests/robotests/src/com/android/settings/development/qstile/WirelessDebuggingTest.java | Deepak5310/packages_apps_Settings | 0b341cc2a61f913d3c5474d53fc961bf00ae7924 | [
"Apache-2.0"
] | null | null | null | tests/robotests/src/com/android/settings/development/qstile/WirelessDebuggingTest.java | Deepak5310/packages_apps_Settings | 0b341cc2a61f913d3c5474d53fc961bf00ae7924 | [
"Apache-2.0"
] | null | null | null | 38.565611 | 94 | 0.722398 | 995,604 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.development.qstile;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings.Global;
import android.widget.Toast;
import com.android.settings.testutils.shadow.ShadowWirelessDebuggingPreferenceController;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowWirelessDebuggingPreferenceController.class})
public class WirelessDebuggingTest {
@Mock
private Toast mToast;
@Mock
private KeyguardManager mKeyguardManager;
private Context mContext;
private DevelopmentTiles.WirelessDebugging mWirelessDebugging;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mWirelessDebugging = spy(new DevelopmentTiles.WirelessDebugging());
doReturn(mContext.getContentResolver()).when(mWirelessDebugging).getContentResolver();
ReflectionHelpers.setField(mWirelessDebugging, "mKeyguardManager", mKeyguardManager);
ReflectionHelpers.setField(mWirelessDebugging, "mToast", mToast);
}
@After
public void tearDown() {
ShadowWirelessDebuggingPreferenceController.reset();
}
@Test
public void adbWifiEnabled_shouldReturnEnabled() {
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 1 /* setting enabled */);
assertThat(mWirelessDebugging.isEnabled()).isTrue();
}
@Test
public void adbWifiDisabled_shouldReturnDisabled() {
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 0 /* setting disabled */);
assertThat(mWirelessDebugging.isEnabled()).isFalse();
}
@Test
public void setIsEnabled_false_keyguardUnlocked_WifiDisconnected_shouldDisableAdbWifi() {
// Precondition: set the tile to enabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 1 /* setting enabled */);
// Unlocked keyguard
doReturn(false).when(mKeyguardManager).isKeyguardLocked();
// Wifi disconnected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(false);
mWirelessDebugging.setIsEnabled(false);
assertThat(mWirelessDebugging.isEnabled()).isFalse();
}
@Test
public void setIsEnabled_false_keyguardLocked_WifiDisconnected_shouldDisableAdbWifi() {
// Precondition: set the tile to enabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 1 /* setting enabled */);
// Locked keyguard
doReturn(true).when(mKeyguardManager).isKeyguardLocked();
// Wifi disconnected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(false);
mWirelessDebugging.setIsEnabled(false);
assertThat(mWirelessDebugging.isEnabled()).isFalse();
}
@Test
public void setIsEnabled_false_keyguardUnlocked_WifiConnected_shouldDisableAdbWifi() {
// Precondition: set the tile to enabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 1 /* setting enabled */);
// Unlocked keyguard
doReturn(false).when(mKeyguardManager).isKeyguardLocked();
// Wifi connected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(true);
mWirelessDebugging.setIsEnabled(false);
assertThat(mWirelessDebugging.isEnabled()).isFalse();
}
@Test
public void setIsEnabled_false_keyguardLocked_WifiConnected_shouldDisableAdbWifi() {
// Precondition: set the tile to enabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 1 /* setting enabled */);
// Locked keyguard
doReturn(true).when(mKeyguardManager).isKeyguardLocked();
// Wifi connected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(true);
mWirelessDebugging.setIsEnabled(false);
assertThat(mWirelessDebugging.isEnabled()).isFalse();
}
@Test
public void setIsEnabled_true_keyguardUnlocked_WifiDisconnected_shouldDisableAdbWifi() {
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
doNothing().when(mWirelessDebugging).sendBroadcast(intentCaptor.capture());
// Precondition: set the tile to disabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 0 /* setting enabled */);
// Unlocked keyguard
doReturn(false).when(mKeyguardManager).isKeyguardLocked();
// Wifi disconnected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(false);
mWirelessDebugging.setIsEnabled(true);
assertThat(mWirelessDebugging.isEnabled()).isFalse();
// The notification shade should be hidden by sending a broadcast to SysUI
// so the toast can be seen
verify(mWirelessDebugging, times(1)).sendBroadcast(eq(intentCaptor.getValue()));
assertThat(intentCaptor.getValue().getAction())
.isEqualTo(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
// Should also get a toast that wifi is not connected
verify(mToast).show();
}
@Test
public void setIsEnabled_true_keyguardLocked_WifiDisconnected_shouldDisableAdbWifi() {
// Precondition: set the tile to disabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 0 /* setting enabled */);
// Locked keyguard
doReturn(true).when(mKeyguardManager).isKeyguardLocked();
// Wifi disconnected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(false);
mWirelessDebugging.setIsEnabled(true);
// Shouldn't be able to enable wireless debugging from locked screen
assertThat(mWirelessDebugging.isEnabled()).isFalse();
}
@Test
public void setIsEnabled_true_keyguardUnlocked_WifiConnected_shouldDisableAdbWifi() {
// Precondition: set the tile to disabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 0 /* setting enabled */);
// Unlocked keyguard
doReturn(false).when(mKeyguardManager).isKeyguardLocked();
// Wifi connected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(true);
mWirelessDebugging.setIsEnabled(true);
assertThat(mWirelessDebugging.isEnabled()).isTrue();
}
@Test
public void setIsEnabled_true_keyguardLocked_WifiConnected_shouldDisableAdbWifi() {
// Precondition: set the tile to disabled
Global.putInt(mContext.getContentResolver(),
Global.ADB_WIFI_ENABLED, 0 /* setting enabled */);
// Locked keyguard
doReturn(true).when(mKeyguardManager).isKeyguardLocked();
// Wifi connected
ShadowWirelessDebuggingPreferenceController.setIsWifiConnected(true);
mWirelessDebugging.setIsEnabled(true);
// Shouldn't be able to enable wireless debugging from locked screen
assertThat(mWirelessDebugging.isEnabled()).isFalse();
}
}
|
9230caece0aa19b0495e4bfa748ea61b3c67d134 | 746 | java | Java | app/src/main/java/kr/co/softcampus/tooksampoom/RunningFragment.java | osamhack2020/APP_TookSamPoom_Navy3Generals | 07835636b1c0c9586e0b05fc20cb758918373b37 | [
"MIT"
] | 1 | 2020-10-23T11:54:31.000Z | 2020-10-23T11:54:31.000Z | app/src/main/java/kr/co/softcampus/tooksampoom/RunningFragment.java | osamhack2020/APP_TookSamPoom_Navy3Generals | 07835636b1c0c9586e0b05fc20cb758918373b37 | [
"MIT"
] | 1 | 2020-11-02T06:17:45.000Z | 2020-11-02T06:17:45.000Z | app/src/main/java/kr/co/softcampus/tooksampoom/RunningFragment.java | osamhack2020/APP_TookSamPoom_Navy3Generals | 07835636b1c0c9586e0b05fc20cb758918373b37 | [
"MIT"
] | null | null | null | 28.692308 | 80 | 0.710456 | 995,605 | package kr.co.softcampus.tooksampoom;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class RunningFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_running, container, false);
return rootView;
}
public void onClickRun(View view) {
Intent runningIntent = new Intent(getActivity(), RunningActivity.class);
startActivity(runningIntent);
}
} |
9230cb1cb2ac1e0ec6823795fa601ffa9476efce | 2,606 | java | Java | src/main/java/io/choerodon/iam/api/dto/payload/OrganizationRegisterPayload.java | xforcecloud/iam-service | 26facb704dc1dc2412d926ff173f2d2c27f488d0 | [
"Apache-2.0"
] | 40 | 2018-05-20T07:35:52.000Z | 2021-09-26T05:43:07.000Z | src/main/java/io/choerodon/iam/api/dto/payload/OrganizationRegisterPayload.java | xforcecloud/iam-service | 26facb704dc1dc2412d926ff173f2d2c27f488d0 | [
"Apache-2.0"
] | 10 | 2018-08-30T01:27:38.000Z | 2019-08-28T14:12:32.000Z | src/main/java/io/choerodon/iam/api/dto/payload/OrganizationRegisterPayload.java | xxxxxxxxcloud/iam-service | 26facb704dc1dc2412d926ff173f2d2c27f488d0 | [
"Apache-2.0"
] | 30 | 2018-06-01T07:04:28.000Z | 2021-04-23T06:45:10.000Z | 23.690909 | 85 | 0.61627 | 995,606 | package io.choerodon.iam.api.dto.payload;
/**
* @author suplerlee
*/
public class OrganizationRegisterPayload {
private Long organizationId;
private String organizationName;
private String organizationCode;
private Long userId;
private String realName;
private String loginName;
private String email;
private Long fromUserId;
public Long getOrganizationId() {
return organizationId;
}
public OrganizationRegisterPayload setOrganizationId(Long organizationId) {
this.organizationId = organizationId;
return this;
}
public String getOrganizationName() {
return organizationName;
}
public OrganizationRegisterPayload setOrganizationName(String organizationName) {
this.organizationName = organizationName;
return this;
}
public String getOrganizationCode() {
return organizationCode;
}
public OrganizationRegisterPayload setOrganizationCode(String organizationCode) {
this.organizationCode = organizationCode;
return this;
}
public Long getFromUserId() {
return fromUserId;
}
public OrganizationRegisterPayload setFromUserId(Long fromUserId) {
this.fromUserId = fromUserId;
return this;
}
public Long getUserId() {
return userId;
}
public OrganizationRegisterPayload setUserId(Long userId) {
this.userId = userId;
return this;
}
public String getRealName() {
return realName;
}
public OrganizationRegisterPayload setRealName(String realName) {
this.realName = realName;
return this;
}
public String getLoginName() {
return loginName;
}
public OrganizationRegisterPayload setLoginName(String loginName) {
this.loginName = loginName;
return this;
}
public String getEmail() {
return email;
}
public OrganizationRegisterPayload setEmail(String email) {
this.email = email;
return this;
}
@Override
public String toString() {
return "OrganizationRegisterPayload{" +
"organizationId=" + organizationId +
", organizationName='" + organizationName + '\'' +
", organizationCode='" + organizationCode + '\'' +
", userId=" + userId +
", realName='" + realName + '\'' +
", loginName='" + loginName + '\'' +
", email='" + email + '\'' +
", fromUserId=" + fromUserId +
'}';
}
}
|
9230cdfc4c17c3d5f800b16aa461171d209f3e4e | 374 | java | Java | json/src/test/java/com/obsidiandynamics/json/fieldpatch/StandardFieldPatchDeserializerTest.java | obsidiandynamics/fulcrum | 6640d771e2c71c5d9d42bd0950376e4cb81baa99 | [
"BSD-3-Clause"
] | 5 | 2017-10-09T11:25:20.000Z | 2022-03-12T14:52:01.000Z | json/src/test/java/com/obsidiandynamics/json/fieldpatch/StandardFieldPatchDeserializerTest.java | obsidiandynamics/fulcrum | 6640d771e2c71c5d9d42bd0950376e4cb81baa99 | [
"BSD-3-Clause"
] | null | null | null | json/src/test/java/com/obsidiandynamics/json/fieldpatch/StandardFieldPatchDeserializerTest.java | obsidiandynamics/fulcrum | 6640d771e2c71c5d9d42bd0950376e4cb81baa99 | [
"BSD-3-Clause"
] | 1 | 2021-10-17T13:51:44.000Z | 2021-10-17T13:51:44.000Z | 24.933333 | 66 | 0.794118 | 995,607 | package com.obsidiandynamics.json.fieldpatch;
import java.io.*;
import org.junit.*;
import com.fasterxml.jackson.core.*;
public final class StandardFieldPatchDeserializerTest {
@Test(expected=UnsupportedOperationException.class)
public void test() throws JsonProcessingException, IOException {
new StandardFieldPatchDeserializer().deserialize(null, null);
}
}
|
9230cf43a624cb903c15bed59562560006c94839 | 14,712 | java | Java | plugin-flappybatta/src/main/java/cn/iam007/plugin/flappybatta/GameFragment.java | jiangerji/android-plugin-framework | 77c362715e4e5b67952c81a6a4b28650b4085fd4 | [
"MIT"
] | null | null | null | plugin-flappybatta/src/main/java/cn/iam007/plugin/flappybatta/GameFragment.java | jiangerji/android-plugin-framework | 77c362715e4e5b67952c81a6a4b28650b4085fd4 | [
"MIT"
] | null | null | null | plugin-flappybatta/src/main/java/cn/iam007/plugin/flappybatta/GameFragment.java | jiangerji/android-plugin-framework | 77c362715e4e5b67952c81a6a4b28650b4085fd4 | [
"MIT"
] | null | null | null | 32.912752 | 96 | 0.535277 | 995,608 | package cn.iam007.plugin.flappybatta;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import cn.iam007.plugin.base.PluginBaseFragment;
import cn.iam007.plugin.loader.PluginResourceLoader;
public class GameFragment extends PluginBaseFragment implements Callback, OnClickListener {
/**
* set to true in order to print fps in screen.
*/
private static final boolean SHOW_FPS = false;
/**
* set to false to disable coins.
*/
private static final boolean ENABLE_COIN = true;
private ImageView ivBackground;
private SurfaceView surfaceView;
private SurfaceHolder holder;
private LinkedList<Sprite> sprites;
private SoundPool soundPool;
@SuppressWarnings("unused")
private static final String TAG = "GameFragment";
private Drawable blockerUp;
private Drawable blockerDown;
private Drawable coin;
private static final long GAP = 20;
private static final long NEW_BLOCKER_COUNT = 60;
private static final long NEW_COIN_COUNT = 60;
private static final int[] BACKGROUND = new int[]{
R.drawable.bg_general_day, R.drawable.bg_general_night};
private Paint globalPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean surfaceCreated = false;
;
private Thread drawingTheard;
private int[] soundIds;
private Dialog alertDialog;
private static final int SOUND_DIE = 0;
private static final int SOUND_HIT = 1;
private static final int SOUND_POINT = 2;
private static final int SOUND_SWOOSHING = 3;
private static final int SOUND_WING = 4;
private BattaSprite battaSprite;
private ScoreSprite scoreSprite;
private GroundSprite groundSprite;
private SplashSprite splashSprite;
private FpsSprite fpsSprite;
private int blockerCount = 0;
private int coinCount = 0;
private int lastBlockY = 0;
private volatile int currentPoint = 0;
private volatile int currentStatus = Sprite.STATUS_NOT_STARTED;
private Random random = new Random();
public static PluginResourceLoader mResources;
public static PluginResourceLoader getPluginResource() {
return mResources;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mResources = getResource();
}
@Override
public void onDetach() {
super.onDetach();
mResources = null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mResources = getResource();
View view = mResources.inflate(getActivity(), R.layout.activity_game, container, false);
ivBackground = (ImageView) view.findViewById(R.id.iv_background);
surfaceView = (SurfaceView) view.findViewById(R.id.surface_view);
surfaceView.setKeepScreenOn(true);
holder = surfaceView.getHolder();
surfaceView.setZOrderOnTop(true);
surfaceView.setOnClickListener(this);
holder.addCallback(this);
holder.setFormat(PixelFormat.TRANSLUCENT);
loadRes();
return view;
}
@Override
public void onResume() {
super.onResume();
restart();
}
@Override
public void onPause() {
super.onPause();
stopDrawingThread();
}
@Override
public void onDestroy() {
super.onDestroy();
stopDrawingThread();
soundPool.release();
mResources = null;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
surfaceCreated = true;
startDrawingThread();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
surfaceCreated = false;
stopDrawingThread();
}
public void showRestartDialog() {
int highest = PrefUtil.getHighestScore(getActivity());
String text = null;
if (currentPoint > highest) {
highest = currentPoint;
PrefUtil.setHighestScore(getActivity(), currentPoint);
} else {
}
text = "本次分数:" + currentPoint + "\n历史高分:" + highest;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Game Over");
builder.setMessage(text);
builder.setPositiveButton("再玩一次",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
playSwooshing();
restart();
}
});
builder.setNegativeButton("退出游戏",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
playSwooshing();
getActivity().finish();
}
});
builder.setCancelable(false);
alertDialog = builder.show();
}
private void restart() {
if (!getActivity().isFinishing()) {
ivBackground.setImageResource(BACKGROUND[random
.nextInt(BACKGROUND.length)]);
soundPool.play(soundIds[SOUND_SWOOSHING], 0.5f, 0.5f, 1, 0, 1);
sprites = new LinkedList<Sprite>();
battaSprite = new BattaSprite(getActivity());
scoreSprite = new ScoreSprite(getActivity());
groundSprite = new GroundSprite(getActivity());
splashSprite = null;
sprites.add(scoreSprite);
sprites.add(groundSprite);
if (SHOW_FPS) {
fpsSprite = new FpsSprite(getActivity());
sprites.add(fpsSprite);
} else {
fpsSprite = null;
}
sprites.add(battaSprite);
HintSprite hintSprite = new HintSprite(getActivity());
sprites.add(hintSprite);
blockerCount = 0;
coinCount = (int) (NEW_COIN_COUNT / 2);
currentPoint = 0;
lastBlockY = 0;
currentStatus = Sprite.STATUS_NOT_STARTED;
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
alertDialog = null;
}
if (surfaceCreated) {
startDrawingThread();
}
}
}
private void loadRes() {
// Resources res = getResources();
blockerUp = mResources.getDrawable(R.drawable.img_block_up);
blockerDown = mResources.getDrawable(R.drawable.img_block_down);
coin = mResources.getDrawable(R.drawable.img_coin);
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
AssetManager assetManager = mResources.getAssets();
soundIds = new int[5];
try {
soundIds[SOUND_DIE] = soundPool.load(assetManager.openFd("sfx_die.ogg"),
1);
soundIds[SOUND_HIT] = soundPool.load(assetManager.openFd("sfx_hit.ogg"),
1);
soundIds[SOUND_POINT] = soundPool.load(
assetManager.openFd("sfx_point.ogg"), 1);
soundIds[SOUND_SWOOSHING] = soundPool.load(
assetManager.openFd("sfx_swooshing.ogg"), 1);
soundIds[SOUND_WING] = soundPool.load(
assetManager.openFd("sfx_wing.ogg"), 1);
} catch (IOException e) {
e.printStackTrace();
}
}
private void startDrawingThread() {
stopDrawingThread();
drawingTheard = new DrawingThread();
drawingTheard.start();
}
private void stopDrawingThread() {
if (drawingTheard != null) {
drawingTheard.interrupt();
try {
drawingTheard.join();
} catch (InterruptedException e) {
}
drawingTheard = null;
}
}
@SuppressLint("WrongCall")
private class DrawingThread extends Thread {
@Override
public void run() {
super.run();
while (!Thread.interrupted()) {
long startTime = System.currentTimeMillis();
Canvas canvas = holder.lockCanvas();
try {
cleanCanvas(canvas);
Iterator<Sprite> iterator = sprites.iterator();
while (iterator.hasNext()) {
Sprite sprite = iterator.next();
if (sprite.isAlive()) {
sprite.onDraw(canvas, globalPaint, currentStatus);
} else {
iterator.remove();
// Log.d(TAG, "remove sprite");
}
}
} finally {
holder.unlockCanvasAndPost(canvas);
}
long duration = (System.currentTimeMillis() - startTime);
long gap = GAP - duration;
if (gap > 0) {
try {
sleep(gap);
} catch (Exception e) {
break;
}
}
if (currentStatus == Sprite.STATUS_NOT_STARTED) {
continue;
}
if (currentStatus == Sprite.STATUS_GAME_OVER) {
if (battaSprite.isHit(battaSprite)
&& !splashSprite.isAlive()) {
onGameOver();
break;
} else {
continue;
}
}
boolean hit = false;
for (Sprite sprite : sprites) {
if (sprite.isHit(battaSprite)) {
onHit();
hit = true;
break;
}
}
if (hit) {
sprites.addLast(splashSprite = new SplashSprite());
currentStatus = Sprite.STATUS_GAME_OVER;
continue;
}
if (blockerCount > NEW_BLOCKER_COUNT) {
blockerCount = 0;
BlockerSprite sprite = BlockerSprite.obtainRandom(getActivity(),
blockerUp,
blockerDown,
battaSprite.getX(),
lastBlockY);
lastBlockY = sprite.getUpHeight();
sprites.addFirst(sprite);
// Log.d(TAG, "new sprite");
} else {
blockerCount++;
}
if (ENABLE_COIN) {
if (coinCount > NEW_COIN_COUNT) {
coinCount = 0;
CoinSprite sprite = new CoinSprite(getActivity(),
coin);
sprites.addFirst(sprite);
// Log.d(TAG, "new coin");
} else {
coinCount++;
}
}
for (Sprite sprite : sprites) {
int point = sprite.getScore();
if (point > 0) {
onGetPoint(point);
}
}
}
Log.d("DrawingThread", "quit");
}
}
private void onGetPoint(int point) {
currentPoint += point;
scoreSprite.setCurrentScore(currentPoint);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!getActivity().isFinishing()) {
soundPool.play(soundIds[SOUND_POINT], 0.5f, 0.5f, 1, 0, 1);
}
}
});
}
private void onGameOver() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!getActivity().isFinishing()) {
soundPool.play(soundIds[SOUND_DIE], 0.5f, 0.5f, 1, 0, 1);
showRestartDialog();
}
}
});
}
private void onHit() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!getActivity().isFinishing()) {
soundPool.play(soundIds[SOUND_HIT], 0.5f, 0.5f, 1, 0, 1);
}
}
});
}
private void playSwooshing() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!getActivity().isFinishing()) {
soundPool.play(soundIds[SOUND_SWOOSHING],
0.5f,
0.5f,
1,
0,
1);
}
}
});
}
private void cleanCanvas(Canvas canvas) {
canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
}
@Override
public void onClick(View v) {
switch (currentStatus) {
case Sprite.STATUS_NOT_STARTED:
currentStatus = Sprite.STATUS_NORMAL;
case Sprite.STATUS_NORMAL:
battaSprite.onTap();
soundPool.play(soundIds[SOUND_WING], 0.5f, 0.5f, 1, 0, 1);
break;
default:
break;
}
}
}
|
9230cf4ec3cfbbeda79282742bba496b90d8e0cc | 563 | java | Java | src/test/java/offer/sort/MergeSortTest.java | physicsLoveJava/algorithms-practice-record | d0ad21214b2e008d81ba07717da3dca062a7071b | [
"MIT"
] | null | null | null | src/test/java/offer/sort/MergeSortTest.java | physicsLoveJava/algorithms-practice-record | d0ad21214b2e008d81ba07717da3dca062a7071b | [
"MIT"
] | null | null | null | src/test/java/offer/sort/MergeSortTest.java | physicsLoveJava/algorithms-practice-record | d0ad21214b2e008d81ba07717da3dca062a7071b | [
"MIT"
] | null | null | null | 22.52 | 64 | 0.62167 | 995,609 | package offer.sort;
import org.junit.Test;
import util.PrintUtils;
import java.util.Comparator;
import static org.junit.Assert.*;
public class MergeSortTest {
@Test
public void sort() throws Exception {
Integer[] arr = CommonSortUtility.generateRandomArray();
PrintUtils.printArray(arr);
MergeSort.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
PrintUtils.printArray(arr);
}
} |
9230d0167a86782b1d29252cebf153d38ed84a7d | 7,067 | java | Java | message-builder-terminology/src/main/java/ca/infoway/messagebuilder/terminology/codeset/domain/CodedValue.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | 1 | 2022-03-09T12:17:41.000Z | 2022-03-09T12:17:41.000Z | message-builder-terminology/src/main/java/ca/infoway/messagebuilder/terminology/codeset/domain/CodedValue.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | null | null | null | message-builder-terminology/src/main/java/ca/infoway/messagebuilder/terminology/codeset/domain/CodedValue.java | CanadaHealthInfoway/message-builder | a24b368b6ad7330ce8e1319e6bae130cea981818 | [
"Apache-2.0"
] | null | null | null | 23.556667 | 133 | 0.699448 | 995,610 | /**
* Copyright 2013 Canada Health Infoway, Inc.
*
* 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.
*
* Author: $LastChangedBy$
* Last modified: $LastChangedDate$
* Revision: $LastChangedRevision$
*/
package ca.infoway.messagebuilder.terminology.codeset.domain;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.annotations.Index;
/**
* A single term taken from a code system.
*
* @author <a href="http://www.intelliware.ca/">Intelliware Development</a>
*/
@Entity
@Table(name="coded_value")
@org.hibernate.annotations.Table(indexes=@Index(name="codeIndex", columnNames={"code", "code_system_id"}), appliesTo = "coded_value")
//@Table(name="coded_value", uniqueConstraints=@UniqueConstraint(columnNames={"code, code_system_id"}))
public class CodedValue {
private Long id;
private String code;
private CodeSystem codeSystem;
private String createUserId;
private Date createDatetime;
private Date lastUpdateDatetime;
private Map<String, String> descriptions = Collections.synchronizedMap(new HashMap<String,String>());
private List<CodedValue> parents = Collections.synchronizedList(new ArrayList<CodedValue>());
private List<CodedValue> children = Collections.synchronizedList(new ArrayList<CodedValue>());
/**
* <p>Instantiates a new coded value.
*/
public CodedValue() {
}
/**
* <p>Gets the id.
*
* @return the id
*/
@Id @GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return this.id;
}
/**
* <p>Sets the id.
*
* @param id the new id
*/
public void setId(Long id) {
this.id = id;
}
/**
* <p>Gets the code.
*
* @return the code
*/
public String getCode() {
return code;
}
/**
* <p>Sets the code.
*
* @param code the new code
*/
public void setCode(String code) {
this.code = code;
}
/**
* <p>Gets the code system.
*
* @return the code system
*/
@ManyToOne(cascade = {CascadeType.ALL},optional=false)
@JoinColumn(name = "code_system_id")
public CodeSystem getCodeSystem() {
return codeSystem;
}
/**
* <p>Sets the code system.
*
* @param system the new code system
*/
public void setCodeSystem(CodeSystem system) {
this.codeSystem = system;
}
/**
* <p>Compare to.
*
* @param obj the obj
* @return the int
*/
public int compareTo(Object obj) {
CodedValue that = (CodedValue) obj;
return new CompareToBuilder()
.append(this.getCodeSystem(), that.getCodeSystem())
.append(this.getCode(), that.getCode())
.append(this.getId(), that.getId())
.toComparison();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (o.getClass() != getClass()) {
return false;
} else {
return equals((CodedValue) o);
}
}
private boolean equals(CodedValue that) {
return new EqualsBuilder().append(this.id, that.id)
.append(this.getCodeSystem(), that.getCodeSystem())
.append(this.getCode(), that.getCode())
.append(this.getId(), that.getId())
.isEquals();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.id)
.append(this.code)
.append(this.codeSystem)
.toHashCode();
}
/**
* <p>Gets the creates the datetime.
*
* @return the creates the datetime
*/
public Date getCreateDatetime() {
return createDatetime;
}
/**
* <p>Sets the creates the datetime.
*
* @param createDatetime the new creates the datetime
*/
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
/**
* <p>Gets the creates the user id.
*
* @return the creates the user id
*/
@Column(name = "create_userid")
public String getCreateUserId() {
return createUserId;
}
/**
* <p>Sets the creates the user id.
*
* @param createUserId the new creates the user id
*/
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
/**
* <p>Gets the last update datetime.
*
* @return the last update datetime
*/
public Date getLastUpdateDatetime() {
return lastUpdateDatetime;
}
/**
* <p>Sets the last update datetime.
*
* @param lastUpdateDatetime the new last update datetime
*/
public void setLastUpdateDatetime(Date lastUpdateDatetime) {
this.lastUpdateDatetime = lastUpdateDatetime;
}
/**
* <p>Gets the descriptions.
*
* @return the descriptions
*/
@CollectionOfElements
@org.hibernate.annotations.MapKey(columns={@Column(name="for_language",length=2)})
@JoinTable(name = "coded_value_description",joinColumns=@JoinColumn(name="coded_value_id"))
@Column(name="description")
@BatchSize(size=25)
public Map<String, String> getDescriptions() {
return this.descriptions;
}
/**
* <p>Sets the descriptions.
*
* @param descriptions the descriptions
*/
public void setDescriptions(Map<String, String> descriptions) {
this.descriptions = descriptions;
}
/**
* <p>Gets the parents.
*
* @return the parents
*/
@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name="coded_value_to_coded_value",
joinColumns=@JoinColumn(name="child_id"),
inverseJoinColumns=@JoinColumn(name="parent_id"))
public List<CodedValue> getParents() {
return this.parents;
}
/**
* <p>Sets the parents.
*
* @param parents the new parents
*/
public void setParents(List<CodedValue> parents) {
this.parents = parents;
}
/**
* <p>Gets the children.
*
* @return the children
*/
@ManyToMany(cascade={CascadeType.ALL}, mappedBy="parents")
public List<CodedValue> getChildren() {
return this.children;
}
/**
* <p>Sets the children.
*
* @param children the new children
*/
public void setChildren(List<CodedValue> children) {
this.children = children;
}
}
|
9230d0c90c0fec31537de7d2bae0d948d139216b | 4,781 | java | Java | android/app/src/main/java/com/stube/app/MainApplication.java | bishop-shawn/stube | b2481e85e69a023accd407ec0f904723a394adcc | [
"MIT"
] | 1 | 2019-09-06T05:58:26.000Z | 2019-09-06T05:58:26.000Z | android/app/src/main/java/com/stube/app/MainApplication.java | bishop-shawn/stube | b2481e85e69a023accd407ec0f904723a394adcc | [
"MIT"
] | 3 | 2019-09-10T03:55:44.000Z | 2019-09-26T08:42:10.000Z | android/app/src/main/java/com/stube/app/MainApplication.java | bishop-shawn/STube | b2481e85e69a023accd407ec0f904723a394adcc | [
"MIT"
] | null | null | null | 37.062016 | 96 | 0.65342 | 995,611 | package com.stube.app;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.github.yamill.orientation.OrientationPackage;
import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;
import com.ninty.system.setting.SystemSettingPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.pilloxa.backgroundjob.BackgroundJobPackage;
import com.rnfs.RNFSPackage;
import com.stube.app.core.DownloaderPackage;
import com.stube.app.deviceInfo.RNDeviceInfo;
import com.stube.app.helper.BlackList;
import com.stube.app.helper.Config;
import com.stube.app.helper.HelperPackage;
import com.stube.app.notification.ReactNativePushNotificationPackage;
import com.stube.app.player.ReactAPlayerPackage;
import com.stube.app.proxy.ProxyPackage;
import com.stube.app.share.RNSharePackage;
import com.stube.app.share.ShareApplication;
import com.stube.app.toast.ToastPackage;
import com.stube.app.webview.RNCWebViewPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import com.flurry.android.FlurryAgent;
import org.devio.rn.splashscreen.SplashScreenReactPackage;
import java.util.Arrays;
import java.util.List;
import fr.greweb.reactnativeviewshot.RNViewShotPackage;
import io.realm.react.RealmReactPackage;
import ui.fileselector.RNFileSelectorPackage;
// import com.tencent.bugly.crashreport.CrashReport;
public class MainApplication extends Application implements ShareApplication, ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new BackgroundJobPackage(),
new ReactNativePushNotificationPackage(),
new SystemSettingPackage(),
new RNSharePackage(),
new RNFileSelectorPackage(),
new RNViewShotPackage(),
new RNCWebViewPackage(),
new RealmReactPackage(),
new OrientationPackage(),
new ReactAPlayerPackage(),
new RNFSPackage(),
new RNDeviceInfo(),
new SplashScreenReactPackage(),
new VectorIconsPackage(),
new RNGestureHandlerPackage(),
new DownloaderPackage(),
new HelperPackage(),
new ToastPackage(),
new ProxyPackage(),
new ReactNativeConfigPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
// // get FLURRY_KEY from market
// private String getFlurryKey(String market) {
// switch(market) {
// case "01": return BuildConfig.FLURRY_KEY01;
// case "02": return BuildConfig.FLURRY_KEY02;
// case "03": return BuildConfig.FLURRY_KEY03;
// case "04": return BuildConfig.FLURRY_KEY04;
// case "05": return BuildConfig.FLURRY_KEY05;
// case "06": return BuildConfig.FLURRY_KEY06;
// case "07": return BuildConfig.FLURRY_KEY07;
// case "08": return BuildConfig.FLURRY_KEY08;
// case "09": return BuildConfig.FLURRY_KEY09;
// default: return BuildConfig.FLURRY_KEY;
// }
// }
@Override
public void onCreate() {
super.onCreate();
// CrashReport.initCrashReport(getApplicationContext(), "d9764b3f63", true);
// String[] urls = {"http:"};
// BlackList.init(this, urls);
BlackList.init(this);
Config.init(getApplicationContext());
SoLoader.init(this, /* native exopackage */ false);
if (!BuildConfig.DEBUG && BuildConfig.FLURRY_KEY != null) {
new FlurryAgent.Builder()
.withLogEnabled(true)
.build(this, BuildConfig.FLURRY_KEY);
}
// Properties prop = System.getProperties();
// prop.setProperty("proxySet", "true");
// prop.setProperty("proxyHost", "localhost");
// prop.setProperty("proxyPort", "8888");
}
@Override
public String getFileProviderAuthority() {
return BuildConfig.APPLICATION_ID + ".provider";
}
}
|
9230d100e872a000ca143997e1bd08cce4cab7af | 1,122 | java | Java | chess/src/test/java/ru/job4j/chess/LogicTest.java | DmitryPoturaev/games_oop_javafx | 7174a03c922f5eebff9e1a08c00e93d4b589d818 | [
"Apache-2.0"
] | null | null | null | chess/src/test/java/ru/job4j/chess/LogicTest.java | DmitryPoturaev/games_oop_javafx | 7174a03c922f5eebff9e1a08c00e93d4b589d818 | [
"Apache-2.0"
] | null | null | null | chess/src/test/java/ru/job4j/chess/LogicTest.java | DmitryPoturaev/games_oop_javafx | 7174a03c922f5eebff9e1a08c00e93d4b589d818 | [
"Apache-2.0"
] | null | null | null | 34 | 92 | 0.690731 | 995,612 | package ru.job4j.chess;
import org.junit.Test;
import ru.job4j.chess.firuges.Cell;
import ru.job4j.chess.firuges.black.BishopBlack;
public class LogicTest {
@Test(expected = FigureNotFoundException.class)
public void whenFigureNotFound()
throws FigureNotFoundException, OccupiedCellException, ImpossibleMoveException {
Logic logic = new Logic();
logic.add(new BishopBlack(Cell.C2));
logic.move(Cell.C1, Cell.E3);
}
@Test(expected = OccupiedCellException.class)
public void whenOccupiedCell()
throws FigureNotFoundException, OccupiedCellException, ImpossibleMoveException {
Logic logic = new Logic();
logic.add(new BishopBlack(Cell.C1));
logic.add(new BishopBlack(Cell.E3));
logic.move(Cell.C1, Cell.E3);
}
@Test(expected = ImpossibleMoveException.class)
public void whenImpossibleMove()
throws FigureNotFoundException, OccupiedCellException, ImpossibleMoveException {
Logic logic = new Logic();
logic.add(new BishopBlack(Cell.C1));
logic.move(Cell.C1, Cell.F3);
}
} |
9230d38d35c2b90b1e9eaccf962c597ab5bccbd1 | 5,398 | java | Java | base/src/com/google/idea/blaze/base/scope/scopes/TimingScope.java | ricebin/intellij | 33f15b87476cea7b2e006f51027526d97ceffc89 | [
"Apache-2.0"
] | 675 | 2016-07-11T15:24:50.000Z | 2022-03-21T20:35:53.000Z | base/src/com/google/idea/blaze/base/scope/scopes/TimingScope.java | ricebin/intellij | 33f15b87476cea7b2e006f51027526d97ceffc89 | [
"Apache-2.0"
] | 1,327 | 2016-07-11T20:30:17.000Z | 2022-03-30T18:57:25.000Z | base/src/com/google/idea/blaze/base/scope/scopes/TimingScope.java | ricebin/intellij | 33f15b87476cea7b2e006f51027526d97ceffc89 | [
"Apache-2.0"
] | 262 | 2016-07-11T17:51:01.000Z | 2022-03-21T09:05:19.000Z | 31.022989 | 99 | 0.694331 | 995,613 | /*
* Copyright 2016 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.base.scope.scopes;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.idea.blaze.base.scope.BlazeContext;
import com.google.idea.blaze.base.scope.BlazeScope;
import com.google.idea.blaze.base.scope.scopes.TimingScopeListener.TimedEvent;
import com.intellij.openapi.diagnostic.Logger;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
/** Collects and logs timing information. */
public class TimingScope implements BlazeScope {
private static final Logger logger = Logger.getInstance(TimingScope.class);
/** The type of event for which timing information is being recorded */
public enum EventType {
BlazeInvocation,
Prefetching,
Other,
}
private final String name;
private final EventType eventType;
private Instant startTime;
private Optional<Duration> duration = Optional.empty();
private final List<TimingScopeListener> scopeListeners = Lists.newArrayList();
@Nullable private TimingScope parentScope;
private final List<TimingScope> children = Lists.newArrayList();
public TimingScope(String name, EventType eventType) {
this.name = name;
this.eventType = eventType;
}
@Override
public void onScopeBegin(BlazeContext context) {
startTime = Instant.now();
parentScope = context.getParentScope(this);
if (parentScope != null) {
parentScope.children.add(this);
}
}
@Override
public void onScopeEnd(BlazeContext context) {
if (context.isCancelled()) {
duration = Optional.of(Duration.ZERO);
return;
}
Duration elapsedTime = Duration.between(startTime, Instant.now());
duration = Optional.of(elapsedTime);
if (!scopeListeners.isEmpty()) {
ImmutableList<TimedEvent> output = collectTimedEvents();
scopeListeners.forEach(l -> l.onScopeEnd(output, elapsedTime));
}
if (parentScope == null && elapsedTime.toMillis() > 100) {
logTimingData();
}
}
private TimedEvent getTimedEvent() {
return new TimedEvent(name, eventType, duration.orElse(Duration.ZERO), children.isEmpty());
}
/** Adds a TimingScope listener to its list of listeners. */
public TimingScope addScopeListener(TimingScopeListener listener) {
scopeListeners.add(listener);
return this;
}
private ImmutableList<TimedEvent> collectTimedEvents() {
List<TimedEvent> output = new ArrayList<>();
collectTimedEvents(this, output);
return ImmutableList.copyOf(output);
}
/** Recursively walk the scopes tree, collecting timing info. */
private static void collectTimedEvents(TimingScope timingScope, List<TimedEvent> data) {
data.add(timingScope.getTimedEvent());
for (TimingScope child : timingScope.children) {
collectTimedEvents(child, data);
}
}
private void logTimingData() {
logger.info("==== TIMING REPORT ====");
logTimingData(this, /* depth= */ 0);
}
private static void logTimingData(TimingScope timingScope, int depth) {
String selfString = "";
// Self time trivially 100% if no children
if (timingScope.children.size() > 0) {
// Calculate self time as <my duration> - <sum child duration>
Duration selfTime = timingScope.getDuration();
for (TimingScope child : timingScope.children) {
selfTime = selfTime.minus(child.getDuration());
}
if (selfTime.toMillis() > 100) {
selfString = String.format(" (%s)", durationStr(selfTime));
}
}
// TODO(brendandouglas): combine repeated child events with the same name (e.g. sharded builds)
logger.info(
String.format(
"%s%s: %s%s",
getIndentation(depth),
timingScope.name,
durationStr(timingScope.getDuration()),
selfString));
for (TimingScope child : timingScope.children) {
logTimingData(child, depth + 1);
}
}
private Duration getDuration() {
if (duration.isPresent()) {
return duration.get();
}
// Could happen if a TimingScope outlives the root context, so the actual duration is not yet
// known.
logger.warn(String.format("Duration not computed for TimingScope %s", name));
return Duration.ZERO;
}
private static String durationStr(Duration duration) {
long timeMillis = duration.toMillis();
return timeMillis >= 1000
? String.format("%.1fs", timeMillis / 1000d)
: String.format("%sms", timeMillis);
}
private static String getIndentation(int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; ++i) {
sb.append(" ");
}
return sb.toString();
}
}
|
9230d3fd6822be8179c6e242f9d90915c498b55c | 1,621 | java | Java | src/com/github/mc6pac/toolchainGPUTILS/GPUTILSMakeRuntimeProperties.java | mc6pac/toolchainGPUTILS | 10a9c1610c5e95af4ae83f75dcdc6e91942c3539 | [
"MIT"
] | null | null | null | src/com/github/mc6pac/toolchainGPUTILS/GPUTILSMakeRuntimeProperties.java | mc6pac/toolchainGPUTILS | 10a9c1610c5e95af4ae83f75dcdc6e91942c3539 | [
"MIT"
] | null | null | null | src/com/github/mc6pac/toolchainGPUTILS/GPUTILSMakeRuntimeProperties.java | mc6pac/toolchainGPUTILS | 10a9c1610c5e95af4ae83f75dcdc6e91942c3539 | [
"MIT"
] | null | null | null | 45.027778 | 140 | 0.674275 | 995,614 | package com.github.mc6pac.toolchainGPUTILS;
import com.microchip.crownking.Pair;
import com.microchip.mplab.nbide.embedded.makeproject.api.configurations.MakeConfiguration;
import com.microchip.mplab.nbide.embedded.makeproject.api.configurations.MakeConfigurationBook;
import com.microchip.mplab.nbide.embedded.makeproject.api.configurations.OptionConfiguration;
import java.util.List;
import java.util.Properties;
import org.openide.util.Utilities;
public class GPUTILSMakeRuntimeProperties {
public GPUTILSMakeRuntimeProperties(MakeConfigurationBook projectDescriptor, MakeConfiguration conf,Properties commandLineProperties) {
commandLineProperties.put("SINGLE_MODE", getCompilerMode(projectDescriptor, conf));
}
private boolean getCompilerMode(MakeConfigurationBook projectDescriptor, MakeConfiguration conf) {
boolean res = true;
if (!Utilities.isWindows())
return res;
// Check the option value
OptionConfiguration confObject = projectDescriptor.getSynthesizedOptionConfiguration(conf.getName(), "gpasm-config", null);
if (confObject != null) {
List<Pair<String, String>> emissionPairs = confObject.getEmissionPairs(null, null);
if (emissionPairs != null) {
for (Pair<String, String> p : emissionPairs) {
if (p.first.equals("older_coff_format") || p.first.equals("old_coff_format")) {
res = false;
break;
}
}
}
}
return res;
}
}
|
9230d4ba9d246014ff3a812f4bce3c074e9b3a34 | 4,709 | java | Java | src/org/olap4j/driver/xmla/DeferredNamedListImpl.java | AtScaleInc/olap4j-patch | 1acc44aa90279be9968d1002c80a4d83a2843ee1 | [
"Apache-2.0"
] | 160 | 2015-01-20T04:20:42.000Z | 2022-03-26T08:03:21.000Z | src/org/olap4j/driver/xmla/DeferredNamedListImpl.java | moodmass/olap4j | b8eccd85753ffddb66c9d8b7c2cd7de2bd510ce0 | [
"Apache-2.0"
] | 39 | 2015-01-20T10:57:43.000Z | 2021-04-26T07:01:23.000Z | src/org/olap4j/driver/xmla/DeferredNamedListImpl.java | moodmass/olap4j | b8eccd85753ffddb66c9d8b7c2cd7de2bd510ce0 | [
"Apache-2.0"
] | 112 | 2015-01-12T09:39:37.000Z | 2022-01-19T08:28:15.000Z | 31.817568 | 79 | 0.648121 | 995,615 | /*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde 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.olap4j.driver.xmla;
import org.olap4j.OlapException;
import org.olap4j.impl.Named;
import org.olap4j.impl.NamedListImpl;
import org.olap4j.metadata.NamedList;
import java.util.AbstractList;
import java.util.Map;
import java.util.concurrent.Semaphore;
/**
* Named list which instantiates itself on first use.
*
* <p><code>DeferredNamedListImpl</code> is useful way to load an object model
* representing a hierarchical schema. If a catalog contains schemas, which
* contain cubes, which contain dimensions, and so forth, and if all
* collections loaded immediately, loading the catalog would immediately load
* all sub-objects into memory, taking a lot of memory and time.
*
* <p>This class is not gc-friendly at present. Once populated,
* <code>DeferredNamedListImpl</code> holds hard references
* to the objects it contains, so they are not available to be
* garbage-collected. Support for weak references might be a future enhancement
* to this class.</p>
*
* @author jhyde
* @since Dec 4, 2007
*/
class DeferredNamedListImpl<T extends Named>
extends AbstractList<T>
implements NamedList<T>
{
private final NamedList<T> list = new NamedListImpl<T>();
private State state = State.NEW;
protected final XmlaOlap4jConnection.MetadataRequest metadataRequest;
protected final XmlaOlap4jConnection.Context context;
protected final XmlaOlap4jConnection.Handler<T> handler;
protected final Object[] restrictions;
protected final Semaphore semaphore = new Semaphore(1);
DeferredNamedListImpl(
XmlaOlap4jConnection.MetadataRequest metadataRequest,
XmlaOlap4jConnection.Context context,
XmlaOlap4jConnection.Handler<T> handler,
Object[] restrictions)
{
this.metadataRequest = metadataRequest;
this.context = context;
this.handler = handler;
this.restrictions = (restrictions == null)
? new Object[0] : restrictions;
}
/**
* Flushes the contents of the list. Next access will re-populate.
*/
void reset() {
state = State.NEW;
list.clear();
}
private NamedList<T> getList() {
try {
semaphore.acquire();
switch (state) {
case POPULATING:
throw new RuntimeException("recursive population");
case NEW:
try {
state = State.POPULATING;
populateList(list);
state = State.POPULATED;
} catch (Exception e) {
state = State.NEW;
// TODO: fetch metadata on getCollection() method, so we
// can't get an exception while traversing the list
throw new RuntimeException(e);
}
// fall through
case POPULATED:
default:
return list;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
semaphore.release();
}
}
public T get(int index) {
return getList().get(index);
}
public int size() {
return getList().size();
}
public T get(String name) {
return getList().get(name);
}
public int indexOfName(String name) {
return getList().indexOfName(name);
}
public String getName(Object element) {
return getList().getName(element);
}
public Map<String, T> asMap() {
return getList().asMap();
}
protected void populateList(NamedList<T> list) throws OlapException {
context.olap4jConnection.populateList(
list, context, metadataRequest, handler, restrictions);
}
private enum State {
NEW,
POPULATING,
POPULATED
}
}
// End DeferredNamedListImpl.java
|
9230d52820fabd9c4af03a5b5bbe12b17addbf4d | 5,954 | java | Java | app/src/main/java/com/flexfare/android/RegistrationPresenter.java | adiaghakhalu/FlexApp | e1ea5d69d412bfee1b9d51b17832903232fcfd44 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/flexfare/android/RegistrationPresenter.java | adiaghakhalu/FlexApp | e1ea5d69d412bfee1b9d51b17832903232fcfd44 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/flexfare/android/RegistrationPresenter.java | adiaghakhalu/FlexApp | e1ea5d69d412bfee1b9d51b17832903232fcfd44 | [
"Apache-2.0"
] | null | null | null | 33.829545 | 143 | 0.559456 | 995,616 | package com.flexfare.android;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Blessyn on 7/31/2017.
*/
public class RegistrationPresenter {
RegistrationValidation regValid;
private String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
public RegistrationPresenter(RegistrationValidation regValid){
this.regValid = regValid;
}
public void doValidation(String firstname, String lastname, String username, String password,String email, String mobile){
if(firstname.equals("") || lastname.equals("") || username.equals("") || password.equals("") || email.equals("")|| mobile.equals("")){
regValid.showEmptyFieldsError();
}
else if(!email.matches(emailPattern)){
regValid.showInvalidEmailError();
}
else if(mobile.length() < 8){
regValid.showInvalidPhoneNumberError();
}
else{
regValid.doRegistratio();
}
}
public void registerUser(List<Registration> registration) {
String f_name = registration.get(0).getFirstname();
String l_name = registration.get(0).getLastname();
String u_name = registration.get(0).getUsername();
String p_word = registration.get(0).getPassword();
String email = registration.get(0).getEmail();
String mobile = registration.get(0).getMobile();
Log.i("FlexApp", f_name + "\n" + l_name);
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
DataOutputStream dataout = null;
// Will contain the raw JSON response as a string.
String result = null;
try {
URL url = new URL("http://www.flexfare.org/signup.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlConnection.connect();
Map<String, Object> params = new LinkedHashMap<>();
params.put("firstname", f_name);
params.put("lastname", l_name);
params.put("username", u_name);
params.put("email", email);
params.put("password", p_word);
params.put("phonenumber", mobile);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
String urlParameters = postData.toString();
dataout = new DataOutputStream(urlConnection.getOutputStream());
// perform POST operation
dataout.writeBytes(urlParameters);
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.i("FlexApp", "Buffer Empty");
}
result = buffer.toString();
} catch (Exception e) {
Log.e("FlexApp", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("FlexApp", "Error closing stream", e);
}
}
}
Log.i("FlexApp", result);
Gson jsonResponse = new Gson();
Response convertedResponse = jsonResponse.fromJson(result, Response.class);
Log.i("FlexApp", convertedResponse.getStatus() + "\n" + convertedResponse.getMessage());
if(convertedResponse.getStatus() == "1"){
regValid.showRegistrationSuccess();
}
// regValid.showRegistrationSuccess();
/*try{
JSONObject obj = new JSONObject(result);
String status = obj.getString("status");
Log.i("FlexApp", "The code :"+ status);
if(status.equals("1")){
regValid.showRegistrationSuccess();
Log.i("FlexApp", "The code :"+ status);
}
}catch (JSONException je){
Log.e("FlexApp")
}*/
}
}
|
9230d67600b251108f05906dd6b56dc5989b6265 | 1,805 | java | Java | pantheon/src/main/java/tech/pegasys/pantheon/cli/rlp/IbftExtraDataCLIAdapter.java | notlesh/pantheon | 2e5833d26c37d6f82138b9bd7f840f208bfa879b | [
"Apache-2.0"
] | 1 | 2019-04-15T22:56:18.000Z | 2019-04-15T22:56:18.000Z | pantheon/src/main/java/tech/pegasys/pantheon/cli/rlp/IbftExtraDataCLIAdapter.java | notlesh/pantheon | 2e5833d26c37d6f82138b9bd7f840f208bfa879b | [
"Apache-2.0"
] | 1 | 2019-03-08T01:29:35.000Z | 2019-03-08T01:29:35.000Z | pantheon/src/main/java/tech/pegasys/pantheon/cli/rlp/IbftExtraDataCLIAdapter.java | notlesh/pantheon | 2e5833d26c37d6f82138b9bd7f840f208bfa879b | [
"Apache-2.0"
] | null | null | null | 37.604167 | 118 | 0.762881 | 995,617 | /*
* Copyright 2019 ConsenSys AG.
*
* 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 tech.pegasys.pantheon.cli.rlp;
import tech.pegasys.pantheon.consensus.ibft.IbftExtraData;
import tech.pegasys.pantheon.ethereum.core.Address;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Adapter to convert a typed JSON to an IbftExtraData object This adapter handles the JSON to RLP
* encoding
*/
public class IbftExtraDataCLIAdapter implements JSONToRLP {
@Override
public BytesValue encode(final String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
TypeReference<Collection<String>> typeRef = new TypeReference<Collection<String>>() {};
Collection<String> validatorAddresse = mapper.readValue(json, typeRef);
Collection<Address> addresses =
validatorAddresse.stream().map(Address::fromHexString).collect(Collectors.toList());
return new IbftExtraData(
BytesValue.wrap(new byte[32]), Collections.emptyList(), Optional.empty(), 0, addresses)
.encode();
}
}
|
9230d6b19c3a32d85d9e90757e7a23126ad8149f | 11,582 | java | Java | fractala/src/com/tarvon/fractala/util/ColorChooser.java | saybur/fractala | ea9a3bf6e4d3f3b08ed81e71dfb1e1246cbf5cbb | [
"MIT"
] | 2 | 2016-02-25T18:20:43.000Z | 2020-02-15T03:42:09.000Z | fractala/src/com/tarvon/fractala/util/ColorChooser.java | saybur/fractala | ea9a3bf6e4d3f3b08ed81e71dfb1e1246cbf5cbb | [
"MIT"
] | null | null | null | fractala/src/com/tarvon/fractala/util/ColorChooser.java | saybur/fractala | ea9a3bf6e4d3f3b08ed81e71dfb1e1246cbf5cbb | [
"MIT"
] | null | null | null | 27.510689 | 81 | 0.638404 | 995,618 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 saybur
*
* 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.tarvon.fractala.util;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.DoubleToIntFunction;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Doubles;
/**
* Class that helps pick out colors for a {@link Matrix} object.
* <p>
* Instances of this class are immutable and thread-safe. Unless specified
* otherwise, no methods will return <code>null</code>. All methods that accept
* parameters will throw <code>NullPointerException</code> if a parameter is
* <code>null</code>, and <code>IllegalArgumentException</code> if a parameter
* is invalid.
*
* @author saybur
*
*/
public final class ColorChooser implements DoubleToIntFunction
{
/**
* Builder class for creating instances of the color chooser.
* <p>
* At least one color stop must be specified prior to building.
*
* @author saybur
*
*/
public static final class Builder
{
private List<ColorStop> colorStops;
private Builder()
{
colorStops = new ArrayList<ColorStop>();
}
/**
* Adds a new color stop to the chooser.
* <p>
* Each color stop represents a position along the number space for a
* set of data. Data exactly at the stop will be exactly the same as the
* color. Data along the continuum between two color stops will be
* interpolated between the colors.
*
* @param value
* the number value corresponding to the color.
* @param color
* the color value at this stop.
* @return the builder, for chaining.
*/
public Builder add(double value, Color color)
{
colorStops.add(new ColorStop(value, color));
return this;
}
/**
* Adds a set of color stops to the chooser.
* <p>
* This is the same as {@link #add(double, Color)}, but for multiple
* entries in a <code>Map</code>. No members of the given
* <code>Map</code> are allowed to be <code>null</code>.
*
* @param map
* a mapping of number values to colors to insert into this
* chooser.
* @return the builder, for chaining.
*/
public Builder addAll(Map<Double, Color> map)
{
Preconditions.checkNotNull(map, "map cannot be null");
List<ColorStop> newStops = new ArrayList<ColorStop>();
for(Map.Entry<Double, Color> e : map.entrySet())
{
Double key = Preconditions.checkNotNull(e.getKey(),
"key in map cannot be null");
Color color = Preconditions.checkNotNull(e.getValue(),
"value in map cannot be null");
newStops.add(new ColorStop(key, color));
}
colorStops.addAll(newStops);
return this;
}
/**
* @return constructs and returns the new color chooser object.
*/
public ColorChooser create()
{
return new ColorChooser(this);
}
}
/**
* Internal class for storing color stop information.
* <p>
* This does not implement <code>equals(Object)</code> or
* <code>hashCode(Object)</code>. Instances of this object should not be
* shared between different threads, or away from the thread that calls
* {@link #create()}.
*
* @author saybur
*
*/
private static final class ColorStop
{
private final double value;
private final Color color;
private ColorStop(double value, Color color)
{
this.color = Preconditions.checkNotNull(color,
"color must not be null");
this.value = value;
Preconditions.checkArgument(Double.isFinite(value),
"value must be finite");
}
}
/**
* Bitmask for the alpha in ARGB color data.
*/
private static final int ABM = 0xff000000;
/**
* Bitmask for red in ARGB color data.
*/
private static final int RBM = 0x00ff0000;
/**
* Bitmask for green in ARGB color data.
*/
private static final int GBM = 0x0000ff00;
/**
* Bitmask for blue in ARGB color data.
*/
private static final int BBM = 0x000000ff;
/**
* Linear interpolation that blends two <code>Color</code> objects together.
* <p>
* Unless there is a good reason to work with <code>Color</code> objects,
* use {@link #blend(int, int, double)} instead: it involves less object
* manipulation, and should thus be faster.
*
* @param c1
* the first color to blend.
* @param c2
* the second color to blend.
* @param w1
* weight to assign to the first color, as described.
* @return the blended color.
*/
public static Color blend(Color c1, Color c2, double w1)
{
// get RGB values for colors as integers
int c1h = c1.getRGB();
int c2h = c2.getRGB();
// reverse weighting
double w2 = 1.0 - w1;
// each of these pulls the byte value for the color, weights it,
// and fast rounds to the nearest integer.
int a = (int)((((c1h & ABM) >>> 24) * w1
+ ((c2h & ABM) >>> 24) * w2)
+ 0.5);
int r = (int)((((c1h & RBM) >>> 16) * w1
+ ((c2h & RBM) >>> 16) * w2)
+ 0.5);
int g = (int)((((c1h & GBM) >>> 8) * w1
+ ((c2h & GBM) >>> 8) * w2)
+ 0.5);
int b = (int)((((c1h & BBM)) * w1
+ ((c2h & BBM)) * w2)
+ 0.5);
return new Color(r, g, b, a);
}
/**
* Linear interpolation that blends two <code>int</code> colors together.
* <p>
* The values provided should be the same as those provided by
* {@link Color#getRGB()}, where bits 24-31 are alpha, 16-23 are red, 8-15
* are green, and 0-7 are blue.
* <p>
* For the version that operates on {@link Color} objects use
* {@link #blend(Color, Color, double)}.
*
* @param c1
* the RGB value of the first color to blend.
* @param c2
* the RGB value of the second color to blend.
* @param w1
* weight to assign to the first color, between 0.0 and 1.0.
* @return the blended color.
*/
public static int blend(int c1, int c2, double w1)
{
// inverse weighting
double w2 = 1.0 - w1;
// each of these pulls the byte value for the color, weights it,
// and fast rounds to the nearest integer.
int a = (int)((((c1 & ABM) >>> 24) * w1
+ ((c2 & ABM) >>> 24) * w2)
+ 0.5);
int r = (int)((((c1 & RBM) >>> 16) * w1
+ ((c2 & RBM) >>> 16) * w2)
+ 0.5);
int g = (int)((((c1 & GBM) >>> 8) * w1
+ ((c2 & GBM) >>> 8) * w2)
+ 0.5);
int b = (int)((((c1 & BBM)) * w1
+ ((c2 & BBM)) * w2)
+ 0.5);
return (a << 24) + (r << 16) + (g << 8) + b;
}
/**
* @return a new builder for this class.
*/
public static Builder builder()
{
return new Builder();
}
/**
* Parses a <code>Color</code> from a <code>String</code>.
* <p>
* This is very similar to {@link Color#decode(String)}, but supports
* optional alpha channel information. The input for this method should be a
* hexadecimal <code>String</code> of format AARRGGBB. Any of
* <code>0x</code>, <code>0X</code>, or <code>#</code> may precede the
* number, but they are not required.
*
* @param colorStr
* the input to read.
* @return the read <code>Color</code>.
* @throws NumberFormatException
* when the input <code>String</code> cannot be rendered as a
* number.
*/
public static Color parseColor(String colorStr)
{
Preconditions.checkNotNull(colorStr,
"input color String cannot be null");
// strip prefixes
colorStr = colorStr.replaceAll("(0x)|(0X)|\\#", "");
// ban the - sign
if(colorStr.contains("-"))
{
throw new IllegalArgumentException("Cannot parse negative "
+ "hex data for a color (or any string containing "
+ "the - symbol).");
}
// if the length is 6 or less, we know that this will not
// contain alpha information
boolean hasAlpha = colorStr.length() > 6;
// attempt to parse
int value = Integer.parseInt(colorStr, 16);
// get the color data out
int a = (int) ((value & 0xFF000000) >> 24);
int r = (int) ((value & 0xFF0000) >> 16);
int g = (int) ((value & 0xFF00) >> 8);
int b = (int) ((value & 0xFF));
// then return, switching based on whether or not alpha
// data is present
if(hasAlpha)
{
return new Color(r, g, b, a);
}
else
{
return new Color(r, g, b);
}
}
private final int count;
private final double[] keys;
private final int[] colors;
private ColorChooser(Builder b)
{
ArrayList<ColorStop> stops = new ArrayList<ColorStop>(b.colorStops);
Preconditions.checkArgument(stops.size() > 0,
"must provide at least one color stop to be valid");
Collections.sort(stops, (l, r) -> Double.compare(l.value, r.value));
count = stops.size();
keys = new double[count];
colors = new int[count];
for(int i = 0; i < count; i++)
{
keys[i] = stops.get(i).value;
colors[i] = stops.get(i).color.getRGB();
}
}
@Override
public int applyAsInt(double value)
{
// get the appropriate index by binary search for log(n) performance
final int i = Arrays.binarySearch(keys, value);
if(i >= 0)
{
// dead-on match, just return
return colors[i];
}
else
{
// non direct match, adjust index
final int ai = -1 * (i + 1);
if(ai == 0)
{
// below all colors
return colors[0];
}
if(ai >= count)
{
// above all colors
return colors[count - 1];
}
else
{
// in between, blend between neighbors
double pKey = keys[ai - 1];
double nKey = keys[ai];
int pColor = colors[ai - 1];
int nColor = colors[ai];
double ratio = (value - pKey) / (nKey - pKey);
return blend(nColor, pColor, ratio);
}
}
}
@Override
public boolean equals(Object obj)
{
if(obj instanceof ColorChooser)
{
ColorChooser o = (ColorChooser) obj;
return count == o.count
&& Objects.equals(keys, o.keys)
&& Objects.equals(colors, o.colors);
}
else
{
return false;
}
}
@Override
public int hashCode()
{
return Objects.hash(count, keys, colors);
}
/**
* @return the keys for this chooser.
*/
public ImmutableList<Double> keys()
{
return ImmutableList.copyOf(Doubles.asList(keys));
}
/**
* @return the number of color stops within this chooser.
*/
public int size()
{
return keys.length;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("count", count)
.add("keys", Arrays.toString(keys))
.add("colors", Arrays.toString(colors))
.toString();
}
}
|
9230d76575c23dfd898c52749679d56e8bdfec80 | 18,070 | java | Java | litemall-wx-api/src/main/java/org/linlinjava/litemall/wx/web/WxAuthController.java | housery/litemall | 31bb92affb231cfcbc91ee6688a8cff2700d261c | [
"MIT"
] | null | null | null | litemall-wx-api/src/main/java/org/linlinjava/litemall/wx/web/WxAuthController.java | housery/litemall | 31bb92affb231cfcbc91ee6688a8cff2700d261c | [
"MIT"
] | null | null | null | litemall-wx-api/src/main/java/org/linlinjava/litemall/wx/web/WxAuthController.java | housery/litemall | 31bb92affb231cfcbc91ee6688a8cff2700d261c | [
"MIT"
] | null | null | null | 36.505051 | 130 | 0.627559 | 995,619 | package org.linlinjava.litemall.wx.web;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.util.CharUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.CouponAssignService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.dao.UserInfo;
import org.linlinjava.litemall.wx.dao.UserToken;
import org.linlinjava.litemall.wx.dao.WxLoginInfo;
import org.linlinjava.litemall.wx.service.CaptchaCodeManager;
import org.linlinjava.litemall.wx.service.UserTokenManager;
import org.linlinjava.litemall.wx.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.linlinjava.litemall.wx.util.WxResponseCode.*;
/**
* 鉴权服务
*/
@RestController
@RequestMapping("/wx/auth")
@Validated
@Api(value = "WxAuthController相关api",tags = "用户登陆注册接口")
public class WxAuthController {
private final Log logger = LogFactory.getLog(WxAuthController.class);
@Autowired
private LitemallUserService userService;
@Autowired
private WxMaService wxService;
@Autowired
private NotifyService notifyService;
@Autowired
private CouponAssignService couponAssignService;
/**
* 账号登录
*
* @param body 请求内容,{ username: xxx, password: xxx }
* @param request 请求对象
* @return 登录结果
*/
@ApiOperation("登陆方法")
@PostMapping("login")
public Object login(@RequestBody @ApiParam(value = "数据参数:username,password") String body, HttpServletRequest request) {
String username = JacksonUtil.parseString(body, "username");
String password = JacksonUtil.parseString(body, "password");
if (username == null || password == null) {
return ResponseUtil.badArgument();
}
List<LitemallUser> userList = userService.queryByUsername(username);
LitemallUser user = null;
if (userList.size() > 1) {
return ResponseUtil.serious();
} else if (userList.size() == 0) {
return ResponseUtil.badArgumentValue();
} else {
user = userList.get(0);
}
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
if (!encoder.matches(password, user.getPassword())) {
return ResponseUtil.fail(AUTH_INVALID_ACCOUNT, "账号密码不对");
}
// userInfo
UserInfo userInfo = new UserInfo();
userInfo.setNickName(username);
userInfo.setAvatarUrl(user.getAvatar());
// token
UserToken userToken = UserTokenManager.generateToken(user.getId());
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
result.put("userInfo", userInfo);
return ResponseUtil.ok(result);
}
/**
* 微信登录
*
* @param wxLoginInfo 请求内容,{ code: xxx, userInfo: xxx }
* @param request 请求对象
* @return 登录结果
*/
@PostMapping("login_by_weixin")
public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
String code = wxLoginInfo.getCode();
UserInfo userInfo = wxLoginInfo.getUserInfo();
if (code == null || userInfo == null) {
return ResponseUtil.badArgument();
}
String sessionKey = null;
String openId = null;
try {
WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
sessionKey = result.getSessionKey();
openId = result.getOpenid();
} catch (Exception e) {
e.printStackTrace();
}
if (sessionKey == null || openId == null) {
return ResponseUtil.fail();
}
LitemallUser user = userService.queryByOid(openId);
if (user == null) {
user = new LitemallUser();
user.setUsername(openId);
user.setPassword(openId);
user.setWeixinOpenid(openId);
user.setAvatar(userInfo.getAvatarUrl());
user.setNickname(userInfo.getNickName());
user.setGender(userInfo.getGender());
user.setUserLevel((byte) 0);
user.setStatus((byte) 0);
user.setLastLoginTime(LocalDateTime.now());
user.setLastLoginIp(IpUtil.client(request));
userService.add(user);
// 新用户发送注册优惠券
couponAssignService.assignForRegister(user.getId());
} else {
user.setLastLoginTime(LocalDateTime.now());
user.setLastLoginIp(IpUtil.client(request));
if (userService.updateById(user) == 0) {
return ResponseUtil.updatedDataFailed();
}
}
// token
UserToken userToken = UserTokenManager.generateToken(user.getId());
userToken.setSessionKey(sessionKey);
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
result.put("userInfo", userInfo);
return ResponseUtil.ok(result);
}
/**
* 请求验证码
*
* @param body 手机号码{mobile}
* @return
*/
@PostMapping("regCaptcha")
@ApiOperation("请求验证码")
public Object registerCaptcha(@RequestBody @ApiParam(value = "请求参数:mobile") String body) {
String phoneNumber = JacksonUtil.parseString(body, "mobile");
if (StringUtils.isEmpty(phoneNumber)) {
return ResponseUtil.badArgument();
}
if (!RegexUtil.isMobileExact(phoneNumber)) {
return ResponseUtil.badArgumentValue();
}
if (!notifyService.isSmsEnable()) {
return ResponseUtil.fail(AUTH_CAPTCHA_UNSUPPORT, "小程序后台验证码服务不支持");
}
String code = CharUtil.getRandomNum(6);
logger.info("短信验证码:"+ code);
notifyService.notifySmsTemplate(phoneNumber, NotifyType.CAPTCHA, new String[]{code});
boolean successful = CaptchaCodeManager.addToCache(phoneNumber, code);
if (!successful) {
return ResponseUtil.fail(AUTH_CAPTCHA_FREQUENCY, "验证码未超时1分钟,不能发送");
}
return ResponseUtil.ok();
}
/**
* 账号注册
*
* @param body 请求内容
* {
* username: xxx,
* password: xxx,
* mobile: xxx
* code: xxx
* }
* 其中code是手机验证码,目前还不支持手机短信验证码
* @param request 请求对象
* @return 登录结果
* 成功则
* {
* errno: 0,
* errmsg: '成功',
* data:
* {
* token: xxx,
* tokenExpire: xxx,
* userInfo: xxx
* }
* }
* 失败则 { errno: XXX, errmsg: XXX }
*/
@PostMapping("register")
public Object register(@RequestBody @ApiParam(value = "参数:username,password,mobile,code,wxCode(微信号)") String body,
HttpServletRequest request) {
String username = JacksonUtil.parseString(body, "username");
String password = JacksonUtil.parseString(body, "password");
String mobile = JacksonUtil.parseString(body, "mobile");
String code = JacksonUtil.parseString(body, "code");
String wxCode = JacksonUtil.parseString(body, "wxCode");
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(mobile)
|| StringUtils.isEmpty(wxCode) || StringUtils.isEmpty(code)) {
return ResponseUtil.badArgument();
}
List<LitemallUser> userList = userService.queryByUsername(username);
if (userList.size() > 0) {
return ResponseUtil.fail(AUTH_NAME_REGISTERED, "用户名已注册");
}
userList = userService.queryByMobile(mobile);
if (userList.size() > 0) {
return ResponseUtil.fail(AUTH_MOBILE_REGISTERED, "手机号已注册");
}
if (!RegexUtil.isMobileExact(mobile)) {
return ResponseUtil.fail(AUTH_INVALID_MOBILE, "手机号格式不正确");
}
//判断验证码是否正确
String cacheCode = CaptchaCodeManager.getCachedCaptcha(mobile);
if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(code)) {
return ResponseUtil.fail(AUTH_CAPTCHA_UNMATCH, "验证码错误");
}
String openId = null;
try {
WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(wxCode);
openId = result.getOpenid();
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.fail(AUTH_OPENID_UNACCESS, "openid 获取失败");
}
userList = userService.queryByOpenid(openId);
if (userList.size() > 1) {
return ResponseUtil.serious();
}
if (userList.size() == 1) {
LitemallUser checkUser = userList.get(0);
String checkUsername = checkUser.getUsername();
String checkPassword = checkUser.getPassword();
if (!checkUsername.equals(openId) || !checkPassword.equals(openId)) {
return ResponseUtil.fail(AUTH_OPENID_BINDED, "openid已绑定账号");
}
}
LitemallUser user = null;
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(password);
user = new LitemallUser();
user.setUsername(username);
user.setPassword(encodedPassword);
user.setMobile(mobile);
user.setWeixinOpenid(openId);
user.setAvatar("https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64");
user.setNickname(username);
user.setGender((byte) 0);
user.setUserLevel((byte) 0);
user.setStatus((byte) 0);
user.setLastLoginTime(LocalDateTime.now());
user.setLastLoginIp(IpUtil.client(request));
userService.add(user);
// 给新用户发送注册优惠券
couponAssignService.assignForRegister(user.getId());
// userInfo
UserInfo userInfo = new UserInfo();
userInfo.setNickName(username);
userInfo.setAvatarUrl(user.getAvatar());
// token
UserToken userToken = UserTokenManager.generateToken(user.getId());
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
result.put("userInfo", userInfo);
return ResponseUtil.ok(result);
}
/**
* 账号密码重置
*
* @param body 请求内容
* {
* password: xxx,
* mobile: xxx
* code: xxx
* }
* 其中code是手机验证码,目前还不支持手机短信验证码
* @param request 请求对象
* @return 登录结果
* 成功则 { errno: 0, errmsg: '成功' }
* 失败则 { errno: XXX, errmsg: XXX }
*/
@PostMapping("reset")
@ApiOperation("账号密码重置")
public Object reset(@RequestBody @ApiParam(value = "参数:password,mobile,code") String body, HttpServletRequest request) {
String password = JacksonUtil.parseString(body, "password");
String mobile = JacksonUtil.parseString(body, "mobile");
String code = JacksonUtil.parseString(body, "code");
if (mobile == null || code == null || password == null) {
return ResponseUtil.badArgument();
}
//判断验证码是否正确
String cacheCode = CaptchaCodeManager.getCachedCaptcha(mobile);
if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(code))
return ResponseUtil.fail(AUTH_CAPTCHA_UNMATCH, "验证码错误");
List<LitemallUser> userList = userService.queryByMobile(mobile);
LitemallUser user = null;
if (userList.size() > 1) {
return ResponseUtil.serious();
} else if (userList.size() == 0) {
return ResponseUtil.fail(AUTH_MOBILE_UNREGISTERED, "手机号未注册");
} else {
user = userList.get(0);
}
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(password);
user.setPassword(encodedPassword);
if (userService.updateById(user) == 0) {
return ResponseUtil.updatedDataFailed();
}
return ResponseUtil.ok();
}
@PostMapping("bindPhone")
public Object bindPhone(@LoginUser Integer userId, @RequestBody String body) {
String sessionKey = UserTokenManager.getSessionKey(userId);
String encryptedData = JacksonUtil.parseString(body, "encryptedData");
String iv = JacksonUtil.parseString(body, "iv");
WxMaPhoneNumberInfo phoneNumberInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
String phone = phoneNumberInfo.getPhoneNumber();
LitemallUser user = userService.findById(userId);
user.setMobile(phone);
if (userService.updateById(user) == 0) {
return ResponseUtil.updatedDataFailed();
}
return ResponseUtil.ok();
}
@PostMapping("logout")
@ApiOperation("登陆退出")
public Object logout(@LoginUser Integer userId) {
logger.info("用户id:" + userId);
if (userId == null) {
return ResponseUtil.unlogin();
}
UserTokenManager.removeToken(userId);
return ResponseUtil.ok();
}
/**
* 俱美账号注册
*
* @param body 请求内容
* {
* username: xxx,
* password: xxx,
* mobile: xxx
* code: xxx
* }
* 其中code是手机验证码,目前还不支持手机短信验证码
* @param request 请求对象
* @return 登录结果
* 成功则
* {
* errno: 0,
* errmsg: '成功',
* data:
* {
* token: xxx,
* tokenExpire: xxx,
* userInfo: xxx
* }
* }
* 失败则 { errno: XXX, errmsg: XXX }
*/
@PostMapping("registerjm")
@ApiOperation("俱美账号注册")
public Object registerjm(@RequestBody @ApiParam(value = "参数:username,password,mobile,code") String body,
HttpServletRequest request) {
String username = JacksonUtil.parseString(body, "username");
String password = JacksonUtil.parseString(body, "password");
String mobile = JacksonUtil.parseString(body, "mobile");
String code = JacksonUtil.parseString(body, "code");
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(mobile)
|| StringUtils.isEmpty(code)) {
return ResponseUtil.badArgument();
}
List<LitemallUser> userList = userService.queryByUsername(username);
if (userList.size() > 0) {
return ResponseUtil.fail(AUTH_NAME_REGISTERED, "用户名已注册");
}
userList = userService.queryByMobile(mobile);
if (userList.size() > 0) {
return ResponseUtil.fail(AUTH_MOBILE_REGISTERED, "手机号已注册");
}
if (!RegexUtil.isMobileExact(mobile)) {
return ResponseUtil.fail(AUTH_INVALID_MOBILE, "手机号格式不正确");
}
//判断验证码是否正确
String cacheCode = CaptchaCodeManager.getCachedCaptcha(mobile);
if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(code)) {
return ResponseUtil.fail(AUTH_CAPTCHA_UNMATCH, "验证码错误");
}
LitemallUser user = null;
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(password);
user = new LitemallUser();
user.setUsername(username);
user.setPassword(encodedPassword);
user.setMobile(mobile);
user.setAvatar("https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64");
user.setNickname(username);
user.setGender((byte) 0);
user.setUserLevel((byte) 0);
user.setStatus((byte) 0);
user.setLastLoginTime(LocalDateTime.now());
user.setLastLoginIp(IpUtil.client(request));
userService.add(user);
// 给新用户发送注册优惠券
couponAssignService.assignForRegister(user.getId());
// userInfo
UserInfo userInfo = new UserInfo();
userInfo.setNickName(username);
userInfo.setAvatarUrl(user.getAvatar());
// token
UserToken userToken = UserTokenManager.generateToken(user.getId());
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("token", userToken.getToken());
result.put("tokenExpire", userToken.getExpireTime().toString());
result.put("userInfo", userInfo);
return ResponseUtil.ok(result);
}
}
|
9230d780404a941a909c57516e4b1045f1e8ad78 | 2,311 | java | Java | schema-registry/common/src/main/java/com/hortonworks/registries/schemaregistry/serde/SnapshotDeserializer.java | kmmanu/registry | bead8c4def9892d89399ee7d72c0eb25709ef537 | [
"Apache-2.0"
] | null | null | null | schema-registry/common/src/main/java/com/hortonworks/registries/schemaregistry/serde/SnapshotDeserializer.java | kmmanu/registry | bead8c4def9892d89399ee7d72c0eb25709ef537 | [
"Apache-2.0"
] | 1 | 2019-03-13T19:46:11.000Z | 2019-03-13T19:46:11.000Z | schema-registry/common/src/main/java/com/hortonworks/registries/schemaregistry/serde/SnapshotDeserializer.java | sporting-innovations/registry | bead8c4def9892d89399ee7d72c0eb25709ef537 | [
"Apache-2.0"
] | null | null | null | 36.109375 | 117 | 0.702293 | 995,620 | /**
* Copyright 2016 Hortonworks.
*
* 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.hortonworks.registries.schemaregistry.serde;
import com.hortonworks.registries.schemaregistry.Resourceable;
/**
* Deserializer interface for de-serializing input {@code I} into output {@code O} according to the Schema {@code S}.
* <p>Common way to use this deserializer implementation is like below. </p>
* <pre>{@code
* SnapshotDeserializer deserializer = ...
* // initialize with given configuration
* deserializer.init(config);
*
* // this instance can be used for multiple serialization invocations
* deserializer.deserialize(input, readerSchemaInfo);
*
* // close it to release any resources held
* deserializer.close();
* }</pre>
*
* @param <I> Input type of the payload
* @param <O> Output type of the de-serialized content.
* @param <RS> Reader schema information.
*/
public interface SnapshotDeserializer<I, O, RS> extends Resourceable {
/**
* De-serializes the given {@code input} according to the writer schema {@code WS} and
* projects it based on the reader schema {@code RS} (if not null).
*
* @param input input payload to be de-serialized
* @param readerSchemaInfo schema information for reading/projection
* @return O the de-serialized output
* @throws SerDesException
*/
O deserialize(I input, RS readerSchemaInfo) throws SerDesException;
/**
* De-serializes the given {@code input} according to the writer schema {@code WS}.
*
* @param input input payload to be de-serialized
* @return O the de-serialized output
* @throws SerDesException
*/
default O deserialize(I input) throws SerDesException {
return deserialize(input, null);
}
}
|
9230d7dca719ed68c5c9f71b48773c32eafff705 | 3,037 | java | Java | nifi-commons/nifi-expression-language/src/main/java/org/apache/nifi/attribute/expression/language/evaluation/functions/bigdecimal/SetScaleBigDemEvaluator.java | kemixkoo/runtime | d648727d31c469540f06733d1078c7fcae278fbe | [
"MIT"
] | 7 | 2019-09-03T10:03:25.000Z | 2022-01-14T09:13:25.000Z | nifi-commons/nifi-expression-language/src/main/java/org/apache/nifi/attribute/expression/language/evaluation/functions/bigdecimal/SetScaleBigDemEvaluator.java | kemixkoo/runtime | d648727d31c469540f06733d1078c7fcae278fbe | [
"MIT"
] | 16 | 2019-11-13T11:56:39.000Z | 2021-12-09T21:35:11.000Z | nifi-commons/nifi-expression-language/src/main/java/org/apache/nifi/attribute/expression/language/evaluation/functions/bigdecimal/SetScaleBigDemEvaluator.java | kemixkoo/runtime | d648727d31c469540f06733d1078c7fcae278fbe | [
"MIT"
] | 3 | 2019-09-02T07:51:39.000Z | 2020-03-16T04:06:49.000Z | 37.036585 | 139 | 0.704313 | 995,621 | /*
* Licensed to the Orchsym Runtime under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* this file to You under the Orchsym License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/orchsym/runtime/blob/master/orchsym/LICENSE
*
* 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.nifi.attribute.expression.language.evaluation.functions.bigdecimal;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
import org.apache.nifi.attribute.expression.language.evaluation.BigDecimalEvaluator;
import org.apache.nifi.attribute.expression.language.evaluation.BigDecimalQueryResult;
import org.apache.nifi.attribute.expression.language.evaluation.Evaluator;
import org.apache.nifi.attribute.expression.language.evaluation.QueryResult;
/**
*
* @author LiGuo BigDecimal 设置精度
*/
public class SetScaleBigDemEvaluator extends BigDecimalEvaluator {
private final Evaluator<BigDecimal> subject;
private final Evaluator<Number> scale;
private final Evaluator<String> round;
public SetScaleBigDemEvaluator(final Evaluator<BigDecimal> subject, final Evaluator<Number> scale) {
this(subject, scale, null);
}
public SetScaleBigDemEvaluator(final Evaluator<BigDecimal> subject, final Evaluator<Number> scale, final Evaluator<String> roundMode) {
this.subject = subject;
this.scale = scale;
this.round = roundMode;
}
@Override
public QueryResult<BigDecimal> evaluate(final Map<String, String> attributes) {
final BigDecimal subjectValue = subject.evaluate(attributes).getValue();
if (subjectValue == null) {
return new BigDecimalQueryResult(null);
}
final Integer scalevalue = scale.evaluate(attributes).getValue().intValue();
RoundingMode roundMode = RoundingMode.HALF_UP;
if (null != round) {
final String roundStr = round.evaluate(attributes).getValue();
for (RoundingMode rm : RoundingMode.values()) {
if (rm.name().equalsIgnoreCase(roundStr)) {
roundMode = rm;
}
}
}
BigDecimal result = null;
if (null != roundMode) {
result = (BigDecimal) subjectValue.setScale(scalevalue, roundMode);
} else {
result = (BigDecimal) subjectValue.setScale(scalevalue);
}
return new BigDecimalQueryResult(result);
}
@Override
public Evaluator<?> getSubjectEvaluator() {
return subject;
}
}
|
9230d859c31f2afbbee41fd6a3efe461d9c9e8aa | 5,196 | java | Java | _/6440OS_06_code/jBPM5-Patient-Insurance/src/test/java/com/salaboy/jbpm5/dev/guide/ws/SlowWebServicesInteractionsTest.java | paullewallencom/jbpm5-978-1-8495-1644-0 | 704b79adca18dfc722ef6cd877fbb090ae86cd54 | [
"Apache-2.0"
] | null | null | null | _/6440OS_06_code/jBPM5-Patient-Insurance/src/test/java/com/salaboy/jbpm5/dev/guide/ws/SlowWebServicesInteractionsTest.java | paullewallencom/jbpm5-978-1-8495-1644-0 | 704b79adca18dfc722ef6cd877fbb090ae86cd54 | [
"Apache-2.0"
] | null | null | null | _/6440OS_06_code/jBPM5-Patient-Insurance/src/test/java/com/salaboy/jbpm5/dev/guide/ws/SlowWebServicesInteractionsTest.java | paullewallencom/jbpm5-978-1-8495-1644-0 | 704b79adca18dfc722ef6cd877fbb090ae86cd54 | [
"Apache-2.0"
] | null | null | null | 35.346939 | 121 | 0.71863 | 995,622 | package com.salaboy.jbpm5.dev.guide.ws;
import com.salaboy.jbpm5.dev.guide.util.SessionStoreUtil;
import com.salaboy.jbpm5.dev.guide.webservice.SlowService;
import com.salaboy.jbpm5.dev.guide.webservice.SlowServiceImpl;
import com.salaboy.jbpm5.dev.guide.workitems.AsyncGenericWorkItemHandler;
import java.util.HashMap;
import java.util.List;
import javax.xml.ws.Endpoint;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.*;
import org.drools.event.rule.DefaultAgendaEventListener;
import org.drools.io.impl.ClassPathResource;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.process.ProcessInstance;
import org.drools.runtime.process.WorkflowProcessInstance;
import org.jbpm.executor.ExecutorModule;
import org.jbpm.executor.ExecutorServiceEntryPoint;
import org.jbpm.executor.entities.RequestInfo;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class SlowWebServicesInteractionsTest {
protected ExecutorServiceEntryPoint executor;
protected StatefulKnowledgeSession session;
private Endpoint endpoint;
private SlowService service;
public SlowWebServicesInteractionsTest() {
}
@Before
public void setUp() throws Exception {
initializeExecutionEnvironment();
initializeWebService();
}
@After
public void tearDown() {
executor.clearAllRequests();
executor.clearAllErrors();
executor.destroy();
this.endpoint.stop();
}
private void initializeWebService() {
this.service = new SlowServiceImpl();
this.endpoint = Endpoint.publish(
"http://127.0.0.1:19999/SlowServiceImpl/slow",
service);
}
protected void initializeExecutionEnvironment() throws Exception {
executor = ExecutorModule.getInstance().getExecutorServiceEntryPoint();
executor.setThreadPoolSize(1);
executor.setInterval(3);
executor.init();
}
private void initializeSession(String processName) {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(new ClassPathResource(processName), ResourceType.BPMN2);
if (kbuilder.hasErrors()) {
KnowledgeBuilderErrors errors = kbuilder.getErrors();
for (KnowledgeBuilderError error : errors) {
System.out.println(">>> Error:" + error.getMessage());
}
throw new IllegalStateException(">>> Knowledge couldn't be parsed! ");
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
session = kbase.newStatefulKnowledgeSession();
KnowledgeRuntimeLoggerFactory.newConsoleLogger(session);
session.addEventListener(new DefaultAgendaEventListener() {
@Override
public void afterRuleFlowGroupActivated(org.drools.event.rule.RuleFlowGroupActivatedEvent event) {
session.fireAllRules();
}
});
}
@Test
public void testSlowWebServicesNoWait() throws InterruptedException {
initializeSession("three-systems-interactions-nowait.bpmn");
HashMap<String, Object> input = new HashMap<String, Object>();
String patientName = "John Doe";
input.put("bedrequest_patientname", patientName);
AsyncGenericWorkItemHandler webServiceHandler = new AsyncGenericWorkItemHandler(executor, session.getId());
session.getWorkItemManager().registerWorkItemHandler("Slow Web Service", webServiceHandler);
WorkflowProcessInstance pI = (WorkflowProcessInstance) session.startProcess("Three Systems Interactions", input);
assertEquals(ProcessInstance.STATE_COMPLETED, pI.getState());
Thread.sleep(25000);
List<RequestInfo> resultList = executor.getExecutedRequests();
assertEquals(3, resultList.size());
session.dispose();
}
@Test
public void testSlowWebServicesWait() throws InterruptedException {
initializeSession("three-systems-interactions-wait.bpmn");
SessionStoreUtil.sessionCache.put("sessionId=" + session.getId(), session);
HashMap<String, Object> input = new HashMap<String, Object>();
String patientName = "John Doe";
input.put("bedrequest_patientname", patientName);
AsyncGenericWorkItemHandler webServiceHandler = new AsyncGenericWorkItemHandler(executor, session.getId());
session.getWorkItemManager().registerWorkItemHandler("Slow Web Service", webServiceHandler);
WorkflowProcessInstance pI = (WorkflowProcessInstance) session.startProcess("Three Systems Interactions", input);
assertEquals(ProcessInstance.STATE_ACTIVE, pI.getState());
Thread.sleep(25000);
List<RequestInfo> resultList = executor.getExecutedRequests();
assertEquals(3, resultList.size());
assertEquals(ProcessInstance.STATE_COMPLETED, pI.getState());
session.dispose();
}
}
|
9230d8a859153cc8f36a277fc579483821085794 | 7,366 | java | Java | app/com/lily/models/FitbitUser.java | juned3you/lily-backend | cc02ee21cd2cc20795dd5634dddcd9a0a4d9f4b0 | [
"Apache-2.0"
] | null | null | null | app/com/lily/models/FitbitUser.java | juned3you/lily-backend | cc02ee21cd2cc20795dd5634dddcd9a0a4d9f4b0 | [
"Apache-2.0"
] | null | null | null | app/com/lily/models/FitbitUser.java | juned3you/lily-backend | cc02ee21cd2cc20795dd5634dddcd9a0a4d9f4b0 | [
"Apache-2.0"
] | null | null | null | 19.538462 | 73 | 0.745452 | 995,623 | package com.lily.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Fitbit user definition from Json.
*
* @author Mohammad
*/
@Entity
@Table(name = "fitbituser")
@PrimaryKeyJoinColumn(name = "user_id")
@JsonIgnoreProperties(ignoreUnknown = true )
public class FitbitUser extends User {
@Column(name = "age")
public Integer age;
@Column(name = "avatar")
public String avatar;
@Column(name = "avatar150")
public String avatar150;
@Column(name = "average_daily_steps")
public Integer averageDailySteps;
@Column(name = "corporate")
public Boolean corporate;
@Column(name = "corporate_admin")
public Boolean corporateAdmin;
@Column(name = "country")
public String country;
@Column(name = "date_of_birth")
public String dateOfBirth;
@Column(name = "display_name")
public String displayName;
@Column(name = "distance_unit")
public String distanceUnit;
@Column(name = "encoded_id")
public String encodedId; // user_id
@JsonIgnore
@Column(name = "features")
public String features;
@Column(name = "foods_locale")
public String foodsLocale;
@Column(name = "full_name")
public String fullName;
@Column(name = "gender")
public String gender;
@Column(name = "glucose_unit")
public String glucoseUnit; // unit
@Column(name = "height")
public Float height;
@Column(name = "height_unit")
public String heightUnit; // unit
@Column(name = "locale")
public String locale;
@Column(name = "member_since")
public String memberSince;
@Column(name = "offset_from_utc_millis")
public String offsetFromUTCMillis;
@Column(name = "start_day_of_week")
public String startDayOfWeek;
@Column(name = "stride_length_running")
public Float strideLengthRunning;
@Column(name = "stride_length_running_type")
public String strideLengthRunningType;
@Column(name = "stride_length_walking")
public Float strideLengthWalking;
@Column(name = "stride_length_walking_type")
public String strideLengthWalkingType;
@Column(name = "timezone")
public String timezone;
@JsonIgnore
@Column(name = "sedentary_time")
public String sedentaryTime;
@JsonIgnore
@Column(name = "top_badges")
public String topBadges;
@Column(name = "water_unit")
public String waterUnit; // unit
@Column(name = "water_unit_name")
public String waterUnitName;
@Column(name = "weight")
public Float weight;
@Column(name = "weight_unit")
public String weightUnit; // unit
@Column(name = "is_sync")
public Boolean isSync;
@Column(name = "clock_time_display_format")
public String clockTimeDisplayFormat;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getAvatar150() {
return avatar150;
}
public void setAvatar150(String avatar150) {
this.avatar150 = avatar150;
}
public Integer getAverageDailySteps() {
return averageDailySteps;
}
public void setAverageDailySteps(Integer averageDailySteps) {
this.averageDailySteps = averageDailySteps;
}
public Boolean getCorporate() {
return corporate;
}
public void setCorporate(Boolean corporate) {
this.corporate = corporate;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getEncodedId() {
return encodedId;
}
public void setEncodedId(String encodedId) {
this.encodedId = encodedId;
}
public String getFeatures() {
return features;
}
public void setFeatures(String features) {
this.features = features;
}
public String getFoodsLocale() {
return foodsLocale;
}
public void setFoodsLocale(String foodsLocale) {
this.foodsLocale = foodsLocale;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGlucoseUnit() {
return glucoseUnit;
}
public void setGlucoseUnit(String glucoseUnit) {
this.glucoseUnit = glucoseUnit;
}
public Float getHeight() {
return height;
}
public void setHeight(Float height) {
this.height = height;
}
public String getHeightUnit() {
return heightUnit;
}
public void setHeightUnit(String heightUnit) {
this.heightUnit = heightUnit;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getMemberSince() {
return memberSince;
}
public void setMemberSince(String memberSince) {
this.memberSince = memberSince;
}
public String getOffsetFromUTCMillis() {
return offsetFromUTCMillis;
}
public void setOffsetFromUTCMillis(String offsetFromUTCMillis) {
this.offsetFromUTCMillis = offsetFromUTCMillis;
}
public String getStartDayOfWeek() {
return startDayOfWeek;
}
public void setStartDayOfWeek(String startDayOfWeek) {
this.startDayOfWeek = startDayOfWeek;
}
public Float getStrideLengthRunning() {
return strideLengthRunning;
}
public void setStrideLengthRunning(Float strideLengthRunning) {
this.strideLengthRunning = strideLengthRunning;
}
public String getStrideLengthRunningType() {
return strideLengthRunningType;
}
public void setStrideLengthRunningType(String strideLengthRunningType) {
this.strideLengthRunningType = strideLengthRunningType;
}
public Float getStrideLengthWalking() {
return strideLengthWalking;
}
public void setStrideLengthWalking(Float strideLengthWalking) {
this.strideLengthWalking = strideLengthWalking;
}
public String getStrideLengthWalkingType() {
return strideLengthWalkingType;
}
public void setStrideLengthWalkingType(String strideLengthWalkingType) {
this.strideLengthWalkingType = strideLengthWalkingType;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getTopBadges() {
return topBadges;
}
public void setTopBadges(String topBadges) {
this.topBadges = topBadges;
}
public String getWaterUnit() {
return waterUnit;
}
public void setWaterUnit(String waterUnit) {
this.waterUnit = waterUnit;
}
public String getWaterUnitName() {
return waterUnitName;
}
public void setWaterUnitName(String waterUnitName) {
this.waterUnitName = waterUnitName;
}
public Float getWeight() {
return weight;
}
public void setWeight(Float weight) {
this.weight = weight;
}
public String getWeightUnit() {
return weightUnit;
}
public void setWeightUnit(String weightUnit) {
this.weightUnit = weightUnit;
}
} |
9230d948995420ae974cb20a6be9f875c0335720 | 284 | java | Java | app/src/main/java/com/tami/vmanager/entity/FeedbackResponseBean.java | tamigroup/V-Manager-Android | 7b39e109787b263657928087a82b3a7ae6e6779d | [
"Apache-2.0"
] | 3 | 2018-06-20T01:03:29.000Z | 2018-07-10T09:07:05.000Z | app/src/main/java/com/tami/vmanager/entity/FeedbackResponseBean.java | tamigroup/V-Manager-Android | 7b39e109787b263657928087a82b3a7ae6e6779d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/tami/vmanager/entity/FeedbackResponseBean.java | tamigroup/V-Manager-Android | 7b39e109787b263657928087a82b3a7ae6e6779d | [
"Apache-2.0"
] | null | null | null | 20.285714 | 81 | 0.78169 | 995,624 | package com.tami.vmanager.entity;
import java.io.Serializable;
/**
* Created by Tang on 2018/7/5
* 获取反馈的实体类
*/
@Deprecated
public class FeedbackResponseBean extends MobileMessage implements Serializable {
private static final long serialVersionUID = 8394454044257599959L;
}
|
9230d96271b94afecfb5cb1723a81a7eae5e304f | 1,992 | java | Java | coreapi-framework.mail/src/main/java/org/sylrsykssoft/coreapi/framework/mail/service/MailEntityApiFactoryService.java | sylarsykes/coreapi-framework | 3891cb2ab3067041f7d7bf7bb47edba4200ff571 | [
"Apache-2.0"
] | null | null | null | coreapi-framework.mail/src/main/java/org/sylrsykssoft/coreapi/framework/mail/service/MailEntityApiFactoryService.java | sylarsykes/coreapi-framework | 3891cb2ab3067041f7d7bf7bb47edba4200ff571 | [
"Apache-2.0"
] | 3 | 2021-12-10T01:24:00.000Z | 2022-01-04T16:35:35.000Z | coreapi-framework.mail/src/main/java/org/sylrsykssoft/coreapi/framework/mail/service/MailEntityApiFactoryService.java | sylarsykes/coreapi-framework | 3891cb2ab3067041f7d7bf7bb47edba4200ff571 | [
"Apache-2.0"
] | 1 | 2019-08-15T21:41:11.000Z | 2019-08-15T21:41:11.000Z | 28.056338 | 117 | 0.787651 | 995,625 | package org.sylrsykssoft.coreapi.framework.mail.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Service;
import org.sylrsykssoft.coreapi.framework.api.resource.BaseEntityResource;
import org.sylrsykssoft.coreapi.framework.mail.exception.CoreApiFrameworkMailException;
/**
* Factory for instance mail service
*
* @author juan.gonzalez.fernandez.jgf
*
*/
@Service
public class MailEntityApiFactoryService<R extends BaseEntityResource>
extends AbstractFactoryBean<MailEntityApiService<R>> {
private MailAdminApiServiceConfiguration serviceConfiguration;
@Autowired
private ApplicationContext applicationContext;
/**
* {@inheritDoc}}
*/
@Override
public void afterPropertiesSet() throws Exception {
setSingleton(false);
super.afterPropertiesSet();
}
/**
* {@inheritDoc}}
*/
@SuppressWarnings("unchecked")
@Override
protected MailEntityApiService<R> createInstance() throws Exception {
return (MailEntityApiService<R>) applicationContext.getBean(serviceConfiguration.getServiceName());
}
/**
* Create instance of service and send mail
*
* @param serviceConfiguration
* @param source
* @param html
*
* @throws CoreApiFrameworkMailException
* @throws Exception
*/
public void execute(final MailAdminApiServiceConfiguration serviceConfiguration, final R source, final boolean html)
throws CoreApiFrameworkMailException, Exception {
this.serviceConfiguration = serviceConfiguration;
createInstance().send(source, html);
}
/**
* {@inheritDoc}}
*/
@SuppressWarnings("unchecked")
@Override
public Class<MailEntityApiService<R>> getObjectType() {
return (Class<MailEntityApiService<R>>) GenericTypeResolver.resolveTypeArgument(getClass(),
MailEntityApiFactoryService.class);
}
}
|
9230d99c8d0499da562f491063b01978731973e8 | 3,068 | java | Java | sourcedata/xalan-j-xalan-j_2_5_0/src/org/apache/xpath/axes/PathComponent.java | DXYyang/SDP | 6ad0daf242d4062888ceca6d4a1bd4c41fd99b63 | [
"Apache-2.0"
] | 6 | 2020-10-27T06:11:59.000Z | 2021-09-09T13:52:42.000Z | sourcedata/xalan-j-xalan-j_2_5_0/src/org/apache/xpath/axes/PathComponent.java | DXYyang/SDP | 6ad0daf242d4062888ceca6d4a1bd4c41fd99b63 | [
"Apache-2.0"
] | 8 | 2020-11-16T20:41:38.000Z | 2022-02-01T01:05:45.000Z | sourcedata/xalan-j-xalan-j_2_5_0/src/org/apache/xpath/axes/PathComponent.java | DXYyang/SDP | 6ad0daf242d4062888ceca6d4a1bd4c41fd99b63 | [
"Apache-2.0"
] | null | null | null | 42.027397 | 84 | 0.726206 | 995,626 | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact lyhxr@example.com.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, Lotus
* Development Corporation., http://www.lotus.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xpath.axes;
/**
* Classes who implement this information provide information needed for
* static analysis of a path component.
*/
public interface PathComponent
{
/**
* Get the analysis bits for this path component, as defined in the WalkerFactory.
* @return One of WalkerFactory#BIT_DESCENDANT, etc.
*/
public int getAnalysisBits();
}
|
9230da335d42b2ca83c71d284dacf851d2e1907d | 839 | java | Java | 1_school/src/main/java/ru/bgbrakhi/stream/Profiles.java | brakhin/job4j | 2eea240e5f14353fb3272db1e71cb5ed0576a912 | [
"Apache-2.0"
] | null | null | null | 1_school/src/main/java/ru/bgbrakhi/stream/Profiles.java | brakhin/job4j | 2eea240e5f14353fb3272db1e71cb5ed0576a912 | [
"Apache-2.0"
] | 18 | 2019-11-14T13:36:14.000Z | 2022-02-16T01:00:23.000Z | 1_school/src/main/java/ru/bgbrakhi/stream/Profiles.java | brakhin/job4j | 2eea240e5f14353fb3272db1e71cb5ed0576a912 | [
"Apache-2.0"
] | null | null | null | 27.966667 | 91 | 0.598331 | 995,627 | package ru.bgbrakhi.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Profiles {
List<Profile> profiles = new ArrayList<>();
public Profiles() {
for (int i = 0; i < 10; i++) {
profiles.add(new Profile(new Address("city" + i, "street" + i, i + 1, i + 1)));
}
}
public List<Address> collect(List<Profile> profiles) {
return profiles.stream()
.map(Profile::getAddress)
.sorted(Comparator.comparing(Address::getCity))
.distinct()
.collect(Collectors.toList());
}
public static void main(String[] args) {
Profiles profiles = new Profiles();
List<Address> addresses = profiles.collect(profiles.profiles);
}
}
|
9230da79d0b7dc0cfd62ad80152c6e6a96a2505d | 2,705 | java | Java | java/com/google/flatbuffers/BaseVector.java | Skybox-Technologies/flatbuffers | 962eff15ce0c97f40c0b72ec2824e25d1c5a0ba5 | [
"Apache-2.0"
] | 16,870 | 2015-01-01T14:57:29.000Z | 2022-03-31T21:56:17.000Z | java/com/google/flatbuffers/BaseVector.java | Skybox-Technologies/flatbuffers | 962eff15ce0c97f40c0b72ec2824e25d1c5a0ba5 | [
"Apache-2.0"
] | 6,363 | 2015-01-01T04:41:50.000Z | 2022-03-31T23:36:52.000Z | java/com/google/flatbuffers/BaseVector.java | Skybox-Technologies/flatbuffers | 962eff15ce0c97f40c0b72ec2824e25d1c5a0ba5 | [
"Apache-2.0"
] | 3,324 | 2015-01-02T12:42:10.000Z | 2022-03-31T10:57:27.000Z | 27.886598 | 98 | 0.675416 | 995,628 | /*
* Copyright 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.flatbuffers;
import java.nio.ByteBuffer;
/// @cond FLATBUFFERS_INTERNAL
/**
* All vector access objects derive from this class, and add their own accessors.
*/
public class BaseVector {
/** Used to hold the vector data position. */
private int vector;
/** Used to hold the vector size. */
private int length;
/** Used to hold the vector element size in table. */
private int element_size;
/** The underlying ByteBuffer to hold the data of the vector. */
protected ByteBuffer bb;
/**
* Get the start data of a vector.
*
* @return Returns the start of the vector data.
*/
protected int __vector() {
return vector;
}
/**
* Gets the element position in vector's ByteBuffer.
*
* @param j An `int` index of element into a vector.
* @return Returns the position of the vector element in a ByteBuffer.
*/
protected int __element(int j) {
return vector + j * element_size;
}
/**
* Re-init the internal state with an external buffer {@code ByteBuffer}, an offset within and
* element size.
*
* This method exists primarily to allow recycling vector instances without risking memory leaks
* due to {@code ByteBuffer} references.
*/
protected void __reset(int _vector, int _element_size, ByteBuffer _bb) {
bb = _bb;
if (bb != null) {
vector = _vector;
length = bb.getInt(_vector - Constants.SIZEOF_INT);
element_size = _element_size;
} else {
vector = 0;
length = 0;
element_size = 0;
}
}
/**
* Resets the internal state with a null {@code ByteBuffer} and a zero position.
*
* This method exists primarily to allow recycling vector instances without risking memory leaks
* due to {@code ByteBuffer} references. The instance will be unusable until it is assigned
* again to a {@code ByteBuffer}.
*/
public void reset() {
__reset(0, 0, null);
}
/**
* Get the length of a vector.
*
* @return Returns the length of the vector.
*/
public int length() {
return length;
}
}
/// @endcond
|
9230dac1ec7d7be6f1dd2cfd425452ea46f6aec7 | 860 | java | Java | EvoSuiteTests/evosuite_2/evosuite-tests/org/mozilla/javascript/regexp/CompilerState_ESTest.java | LASER-UMASS/Swami | feaa5e091b7c2514db5106eba39f7ffbfa6ed408 | [
"MIT"
] | 9 | 2019-02-25T16:12:31.000Z | 2022-01-18T02:39:50.000Z | EvoSuiteTests/evosuite_2/evosuite-tests/org/mozilla/javascript/regexp/CompilerState_ESTest.java | sophiatong/Swami-Additional | feaa5e091b7c2514db5106eba39f7ffbfa6ed408 | [
"MIT"
] | null | null | null | EvoSuiteTests/evosuite_2/evosuite-tests/org/mozilla/javascript/regexp/CompilerState_ESTest.java | sophiatong/Swami-Additional | feaa5e091b7c2514db5106eba39f7ffbfa6ed408 | [
"MIT"
] | 5 | 2019-11-21T06:51:40.000Z | 2022-01-18T02:40:08.000Z | 34.4 | 176 | 0.772093 | 995,629 | /*
* This file was automatically generated by EvoSuite
* Tue Jul 31 20:07:33 GMT 2018
*/
package org.mozilla.javascript.regexp;
import org.junit.Test;
import static org.junit.Assert.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.regexp.CompilerState;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class CompilerState_ESTest extends CompilerState_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
char[] charArray0 = new char[4];
CompilerState compilerState0 = new CompilerState((Context) null, charArray0, 0, 0);
}
}
|
9230dc194250a2c1fc50bfe52cb4cd8f46c4d704 | 8,427 | java | Java | core/src/zemin/notification/NotificationRemote.java | lamydev/Android-InApp-Notification | 6d6571d2862cb6edbacf9a78125418f7d621c3f8 | [
"Apache-2.0"
] | 81 | 2015-06-30T06:17:05.000Z | 2022-02-04T13:51:16.000Z | core/src/zemin/notification/NotificationRemote.java | lamydev/Android-InApp-Notification | 6d6571d2862cb6edbacf9a78125418f7d621c3f8 | [
"Apache-2.0"
] | 7 | 2016-10-18T19:15:16.000Z | 2019-11-06T23:19:02.000Z | core/src/zemin/notification/NotificationRemote.java | lamydev/Android-InApp-Notification | 6d6571d2862cb6edbacf9a78125418f7d621c3f8 | [
"Apache-2.0"
] | 28 | 2015-07-27T13:18:32.000Z | 2021-08-16T05:57:45.000Z | 30.868132 | 100 | 0.643883 | 995,630 | /*
* Copyright (C) 2015 Zemin Liu
*
* 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 zemin.notification;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.support.v4.app.NotificationCompat;
/**
* Status-bar notification.
*/
public class NotificationRemote extends NotificationHandler {
public static final String SIMPLE_NAME = "Remote";
public static boolean DBG;
public static final String ACTION_CANCEL =
"notification.intent.action.notificationremote.cancel";
public static final String ACTION_CONTENT =
"notification.intent.action.notificationremote.content";
public static final String ACTION_ACTION =
"notification.intent.action.notificationremote.action";
public static final String KEY_ENTRY_ID = "key_entry_id";
public static final String KEY_ACTION_ID = "key_action_id";
private static int sID = 0;
private NotificationRemoteCallback mCallback;
private NotificationManager mManager;
private NotificationCompat.Builder mBuilder;
private Receiver mReceiver;
private IntentFilter mFilter;
private boolean mListening;
/* package */ NotificationRemote(Context context, Looper looper) {
super(context, NotificationDelegater.REMOTE, looper);
mManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
mReceiver = new Receiver();
}
/**
* Set callback.
*
* @param cb
*/
public void setCallback(NotificationRemoteCallback cb) {
if (mCallback != cb) {
stopListening();
mCallback = cb;
}
}
/**
* Add a new Intent action for BroadcastReceiver {@link #Receiver}.
*
* @param action
*/
public void addAction(String action) {
getFilter().addAction(action);
}
/**
* Whether the given action is included in the filter.
*
* @param action
*/
public boolean hasAction(String action) {
return getFilter().hasAction(action);
}
/**
* Generate Id for {@link android.app.PendingIntent}.
*
* @return int
*/
public int genIdForPendingIntent() {
return sID++;
}
/**
* Get builder for {@link android.app.Notification}.
*
* @return NotificationCompat#Builder
*/
public NotificationCompat.Builder getStatusBarNotificationBuilder() {
if (mBuilder == null) {
mBuilder = new NotificationCompat.Builder(mContext);
}
return mBuilder;
}
/**
* Create an PendingIntent to execute when the notification is explicitly dismissed by the user.
*
* @see android.app.Notification#setDeleteIntent(PendingIntent)
*
* @param entry
* @return PendingIntent
*/
public PendingIntent getDeleteIntent(NotificationEntry entry) {
Intent intent = new Intent(ACTION_CANCEL);
intent.putExtra(KEY_ENTRY_ID, entry.ID);
return PendingIntent.getBroadcast(mContext, genIdForPendingIntent(), intent, 0);
}
/**
* Create an PendingIntent to execute when the notification is clicked by the user.
*
* @see android.app.Notification#setContentIntent(PendingIntent)
*
* @param entry
* @return PedningIntent
*/
public PendingIntent getContentIntent(NotificationEntry entry) {
Intent intent = new Intent(ACTION_CONTENT);
intent.putExtra(KEY_ENTRY_ID, entry.ID);
return PendingIntent.getBroadcast(mContext, genIdForPendingIntent(), intent, 0);
}
/**
* Create an PendingIntent to be fired when the notification action is invoked.
*
* @see android.app.Notification#addAction(int, CharSequence, PendingIntent)
*
* @param entry
* @param act
* @return PendingIntent
*/
public PendingIntent getActionIntent(NotificationEntry entry, NotificationEntry.Action act) {
Intent intent = new Intent(ACTION_ACTION);
intent.putExtra(KEY_ENTRY_ID, entry.ID);
intent.putExtra(KEY_ACTION_ID, entry.mActions.indexOf(act));
return PendingIntent.getBroadcast(mContext, genIdForPendingIntent(), intent, 0);
}
@Override
protected void onCancel(NotificationEntry entry) {
mManager.cancel(entry.ID);
onCancelFinished(entry);
}
@Override
protected void onCancelAll() {
mManager.cancelAll();
onCancelAllFinished();
}
@Override
protected void onArrival(NotificationEntry entry) {
if (mCallback == null) {
if (DBG) Log.v(TAG, "set default NotificationRemoteCallback");
mCallback = new NotificationRemoteCallback();
}
if (!mListening) {
mCallback.onRemoteSetup(this);
startListening();
}
Notification n = mCallback.makeStatusBarNotification(this, entry, entry.layoutId);
if (n == null) {
Log.e(TAG, "failed to send remote notification. {null Notification}");
onSendIgnored(entry);
return;
}
mManager.notify(entry.tag, entry.ID, n);
if (entry.useSystemEffect) {
cancelEffect(entry);
}
onSendFinished(entry);
}
@Override
protected void onUpdate(NotificationEntry entry) {
onArrival(entry);
}
private void onCanceledRemotely(NotificationEntry entry) {
reportCanceled(entry);
}
private void startListening() {
if (!mListening) {
IntentFilter filter = getFilter();
filter.addAction(ACTION_CANCEL);
filter.addAction(ACTION_CONTENT);
filter.addAction(ACTION_ACTION);
mContext.registerReceiver(mReceiver, filter, null, this);
mListening = true;
}
}
private void stopListening() {
if (mListening) {
mListening = false;
mFilter = null;
mContext.unregisterReceiver(mReceiver);
}
}
private IntentFilter getFilter() {
if (mFilter == null) {
mFilter = new IntentFilter();
}
return mFilter;
}
private class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final int entryId = intent.getIntExtra(KEY_ENTRY_ID, -1);
final NotificationEntry entry = getNotification(entryId);
if (DBG) Log.d(TAG, "onReceive - " + entryId + ", " + action);
if (ACTION_CANCEL.equals(action)) {
onCanceledRemotely(entry);
mCallback.onCancelRemote(NotificationRemote.this, entry);
} else if (ACTION_CONTENT.equals(action)) {
entry.executeContentAction(mContext);
mCallback.onClickRemote(NotificationRemote.this, entry);
if (entry.autoCancel) {
onCanceledRemotely(entry);
}
} else if (ACTION_ACTION.equals(action)) {
final int actionId = intent.getIntExtra(KEY_ACTION_ID, -1);
final NotificationEntry.Action act = entry.mActions.get(actionId);
mCallback.onClickRemoteAction(NotificationRemote.this, entry, act);
act.execute(mContext);
} else {
mCallback.onReceive(NotificationRemote.this, entry, intent, action);
}
}
}
@Override public String toSimpleString() { return SIMPLE_NAME; }
@Override public String toString() { return SIMPLE_NAME; }
}
|
9230dc2a32ccaebb7c5de8df526ffa0e9011a479 | 617 | java | Java | src/main/java/net/cartola/emissorfiscal/documento/ProdutoOrigem.java | robsonhenriq/emissor-fiscal | d0a8d0da1ca91ad7b0016ef8bb19bcbe1dd30818 | [
"MIT"
] | 4 | 2021-08-25T00:39:24.000Z | 2022-02-28T19:46:24.000Z | src/main/java/net/cartola/emissorfiscal/documento/ProdutoOrigem.java | robsonhenriq/emissor-fiscal | d0a8d0da1ca91ad7b0016ef8bb19bcbe1dd30818 | [
"MIT"
] | null | null | null | src/main/java/net/cartola/emissorfiscal/documento/ProdutoOrigem.java | robsonhenriq/emissor-fiscal | d0a8d0da1ca91ad7b0016ef8bb19bcbe1dd30818 | [
"MIT"
] | 2 | 2022-02-22T01:00:36.000Z | 2022-02-25T13:49:48.000Z | 26.826087 | 64 | 0.730956 | 995,631 | package net.cartola.emissorfiscal.documento;
/**
* 09/10/2013 16:40:35
* @author murilo
*/
public enum ProdutoOrigem {
NACIONAL,
ESTRANGEIRA_IMPORTACAO_DIRETA,
ESTRANGEIRA_ADQUIRIDO_MERCADO_INTERNO,
NACIONAL_CONTEUDO_IMPORTADO_MAIOR_40,
NACIONAL_CONFORMIDADE_PROCESSOS,
NACIONAL_CONTEUDO_IMPORTADO_MENOR_40,
ESTRANGEIRA_IMPORTACAO_DIRETA_CAMEX,
ESTRANGEIRA_ADQUIRIDO_MERCADO_INTERNO_CAMEX,
NACIONAL_CONTEUDO_IMPORTADO_MAIOR_70;
public String getDescricaoComOrdinal() {
return String.valueOf(this.ordinal()) +" - "+ this.name();
}
} |
9230dd4374feeca5121d80545fb61925ecd423af | 2,741 | java | Java | aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/transform/DescribeVirtualRouterRequestMarshaller.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | 1 | 2022-01-04T04:11:16.000Z | 2022-01-04T04:11:16.000Z | aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/transform/DescribeVirtualRouterRequestMarshaller.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/transform/DescribeVirtualRouterRequestMarshaller.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | 44.209677 | 155 | 0.759577 | 995,632 | /*
* Copyright 2017-2022 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.services.appmesh.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.appmesh.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeVirtualRouterRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeVirtualRouterRequestMarshaller {
private static final MarshallingInfo<String> MESHNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("meshName").build();
private static final MarshallingInfo<String> MESHOWNER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("meshOwner").build();
private static final MarshallingInfo<String> VIRTUALROUTERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PATH).marshallLocationName("virtualRouterName").build();
private static final DescribeVirtualRouterRequestMarshaller instance = new DescribeVirtualRouterRequestMarshaller();
public static DescribeVirtualRouterRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DescribeVirtualRouterRequest describeVirtualRouterRequest, ProtocolMarshaller protocolMarshaller) {
if (describeVirtualRouterRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeVirtualRouterRequest.getMeshName(), MESHNAME_BINDING);
protocolMarshaller.marshall(describeVirtualRouterRequest.getMeshOwner(), MESHOWNER_BINDING);
protocolMarshaller.marshall(describeVirtualRouterRequest.getVirtualRouterName(), VIRTUALROUTERNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
9230dd85b7aca389109ee991bff1d2e4d879e335 | 1,316 | java | Java | src/main/java/grondag/canvas/mixinterface/AnimatedTextureExt.java | PepperCode1/canvas | 026ace4c427657a4ce39d408fb0653136927491b | [
"Apache-2.0"
] | 1 | 2021-11-29T11:52:39.000Z | 2021-11-29T11:52:39.000Z | src/main/java/grondag/canvas/mixinterface/AnimatedTextureExt.java | PepperCode1/canvas | 026ace4c427657a4ce39d408fb0653136927491b | [
"Apache-2.0"
] | null | null | null | src/main/java/grondag/canvas/mixinterface/AnimatedTextureExt.java | PepperCode1/canvas | 026ace4c427657a4ce39d408fb0653136927491b | [
"Apache-2.0"
] | null | null | null | 33.74359 | 82 | 0.779635 | 995,633 | /*
* Copyright © Contributing Authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional copyright and licensing notices may apply for content that was
* included from other projects. For more information, see ATTRIBUTION.md.
*/
package grondag.canvas.mixinterface;
import java.util.List;
import net.minecraft.client.renderer.texture.TextureAtlasSprite.FrameInfo;
import net.minecraft.client.renderer.texture.TextureAtlasSprite.InterpolationData;
public interface AnimatedTextureExt extends CombinedAnimationConsumer {
InterpolationData canvas_interpolation();
int canvas_frameCount();
int canvas_frameIndex();
int canvas_frameTicks();
List<FrameInfo> canvas_frames();
}
|
9230ddab825b50dd217fe7c569ec053a5e3266ed | 364 | java | Java | ygb/ygb-project/src/main/java/com/qingbo/ginkgo/ygb/project/repository/CommissionDetailRepository.java | hwxiasn/archetypes | 6fb990ad85a9d0dc47b8e84fad4cd3eb207f65c2 | [
"Apache-2.0"
] | null | null | null | ygb/ygb-project/src/main/java/com/qingbo/ginkgo/ygb/project/repository/CommissionDetailRepository.java | hwxiasn/archetypes | 6fb990ad85a9d0dc47b8e84fad4cd3eb207f65c2 | [
"Apache-2.0"
] | null | null | null | ygb/ygb-project/src/main/java/com/qingbo/ginkgo/ygb/project/repository/CommissionDetailRepository.java | hwxiasn/archetypes | 6fb990ad85a9d0dc47b8e84fad4cd3eb207f65c2 | [
"Apache-2.0"
] | null | null | null | 33.090909 | 87 | 0.824176 | 995,634 | package com.qingbo.ginkgo.ygb.project.repository;
import java.util.List;
import com.qingbo.ginkgo.ygb.base.repository.BaseRepository;
import com.qingbo.ginkgo.ygb.project.entity.CommissionDetail;
public interface CommissionDetailRepository extends BaseRepository<CommissionDetail> {
List<CommissionDetail> findByTemplateIdAndDeletedFalse(Long id);
}
|
9230e0bdc3318afd4b65ee04118f4e90cf6ab0c1 | 902 | java | Java | nosqlunit-dynamodb/src/main/java/com/lordofthejars/nosqlunit/dynamodb/DynamoDbConfiguration.java | AffanHasan/nosql-unit | 25c4b43a4698623080f03d0203da1070d77288cf | [
"Apache-2.0"
] | 228 | 2015-01-05T22:59:04.000Z | 2021-12-07T13:39:43.000Z | nosqlunit-dynamodb/src/main/java/com/lordofthejars/nosqlunit/dynamodb/DynamoDbConfiguration.java | AffanHasan/nosql-unit | 25c4b43a4698623080f03d0203da1070d77288cf | [
"Apache-2.0"
] | 91 | 2015-01-05T10:36:21.000Z | 2021-12-09T21:21:52.000Z | nosqlunit-dynamodb/src/main/java/com/lordofthejars/nosqlunit/dynamodb/DynamoDbConfiguration.java | AffanHasan/nosql-unit | 25c4b43a4698623080f03d0203da1070d77288cf | [
"Apache-2.0"
] | 99 | 2015-01-12T10:35:40.000Z | 2022-02-01T16:52:34.000Z | 22 | 78 | 0.698448 | 995,635 |
package com.lordofthejars.nosqlunit.dynamodb;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.lordofthejars.nosqlunit.core.AbstractJsr330Configuration;
public final class DynamoDbConfiguration extends AbstractJsr330Configuration {
private static final String DEFAULT_ENDPOINT = "http://localhost:8000";
private String endpoint = DEFAULT_ENDPOINT;
private AmazonDynamoDB dynamo;
public DynamoDbConfiguration() {
super();
}
public DynamoDbConfiguration(String endpoint) {
super();
this.endpoint = endpoint;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public void setDynamo(AmazonDynamoDB dynamo) {
this.dynamo = dynamo;
}
public AmazonDynamoDB getDynamo() {
return dynamo;
}
}
|
9230e1b51146d382df273ccc8678733ed981b416 | 974 | java | Java | governator-core/src/test/java/com/netflix/governator/lifecycle/mocks/ObjectWithConfigVariable.java | truthiswill/governator | db4a5ac9c1a70f0006d2b6ea025c595f61d99f3d | [
"Apache-2.0"
] | 704 | 2015-01-04T07:58:34.000Z | 2022-03-27T11:50:29.000Z | governator-core/src/test/java/com/netflix/governator/lifecycle/mocks/ObjectWithConfigVariable.java | truthiswill/governator | db4a5ac9c1a70f0006d2b6ea025c595f61d99f3d | [
"Apache-2.0"
] | 93 | 2015-01-15T01:29:03.000Z | 2021-04-10T00:14:43.000Z | governator-core/src/test/java/com/netflix/governator/lifecycle/mocks/ObjectWithConfigVariable.java | truthiswill/governator | db4a5ac9c1a70f0006d2b6ea025c595f61d99f3d | [
"Apache-2.0"
] | 148 | 2015-01-15T01:10:12.000Z | 2022-02-25T06:50:52.000Z | 24.974359 | 76 | 0.679671 | 995,636 | package com.netflix.governator.lifecycle.mocks;
import com.netflix.governator.annotations.Configuration;
import com.netflix.governator.annotations.ConfigurationVariable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class ObjectWithConfigVariable {
@ConfigurationVariable(name="name")
private final String name;
@Configuration(value = "${name}.b", documentation = "this is a boolean")
public boolean aBool = false;
@Configuration("${name}.i")
public int anInt = 1;
@Configuration("${name}.l")
public long aLong = 2;
@Configuration("${name}.d")
public double aDouble = 3.4;
@Configuration("${name}.s")
public String aString = "test";
@Configuration("${name}.dt")
public Date aDate = null;
@Configuration(value = "${name}.obj")
public List<Integer> ints = Arrays.asList(5, 6, 7);
public ObjectWithConfigVariable(String name) {
this.name = name;
}
}
|
9230e2584402c0abeeaba882d09fe4bed748bf14 | 124 | java | Java | src/main/java/com/hw/shared/idempotent/exception/CustomByteArraySerializationException.java | publicdevop2019/mt17-object-store | 064a841d4380aef5f391ae9f89cc2e142bb2f478 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hw/shared/idempotent/exception/CustomByteArraySerializationException.java | publicdevop2019/mt17-object-store | 064a841d4380aef5f391ae9f89cc2e142bb2f478 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hw/shared/idempotent/exception/CustomByteArraySerializationException.java | publicdevop2019/mt17-object-store | 064a841d4380aef5f391ae9f89cc2e142bb2f478 | [
"Apache-2.0"
] | null | null | null | 24.8 | 76 | 0.870968 | 995,637 | package com.hw.shared.idempotent.exception;
public class CustomByteArraySerializationException extends RuntimeException{
}
|
9230e3e4860d2e4c0d712b00446dd18b440705b2 | 2,171 | java | Java | src/test/java/net/openright/conferencer/domain/products/ProductRepositoryTest.java | jhannes/openright-conferencer | 618ee331711af7ac65864a724a986401857fae7c | [
"MIT"
] | null | null | null | src/test/java/net/openright/conferencer/domain/products/ProductRepositoryTest.java | jhannes/openright-conferencer | 618ee331711af7ac65864a724a986401857fae7c | [
"MIT"
] | null | null | null | src/test/java/net/openright/conferencer/domain/products/ProductRepositoryTest.java | jhannes/openright-conferencer | 618ee331711af7ac65864a724a986401857fae7c | [
"MIT"
] | null | null | null | 31.926471 | 73 | 0.707969 | 995,638 | package net.openright.conferencer.domain.products;
import net.openright.conferencer.application.ConferencerConfig;
import net.openright.conferencer.application.ConferencerTestConfig;
import net.openright.conferencer.domain.products.Product;
import net.openright.conferencer.domain.products.ProductRepository;
import net.openright.infrastructure.test.SampleData;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ProductRepositoryTest {
private ConferencerConfig config = ConferencerTestConfig.instance();
private ProductRepository repository = new ProductRepository(config);
@Test
public void shouldRetrieveSavedProduct() throws Exception {
Product product = sampleProduct();
repository.insert(product);
assertThat(repository.retrieve(product.getId()))
.isEqualToComparingFieldByField(product);
}
@Test
public void shouldUpdateProduct() throws Exception {
Product product = sampleProduct();
repository.insert(product);
product.setTitle("New title");
repository.update(product.getId(), product);
assertThat(repository.retrieve(product.getId()).getTitle())
.isEqualTo("New title");
}
@Test
public void shouldListActiveProducts() throws Exception {
Product product1 = sampleProduct("z");
Product product2 = sampleProduct("a");
Product inactiveProduct = sampleProduct();
inactiveProduct.setInactive();
repository.insert(product1);
repository.insert(product2);
repository.insert(inactiveProduct);
assertThat(repository.list())
.containsSubsequence(product2, product1)
.doesNotContain(inactiveProduct);
}
private static Product sampleProduct(String prefix) {
Product product = new Product();
product.setTitle(prefix + SampleData.sampleString(3));
product.setDescription(SampleData.sampleString(10));
product.setPrice(SampleData.randomAmount());
return product;
}
public static Product sampleProduct() {
return sampleProduct("");
}
}
|
9230e4391a1c57cff10cb4e198d1e2b184d2bf5b | 1,018 | java | Java | app/src/main/java/com/yetwish/customsearchdemo/activity/adapter/SearchAdapter.java | b300548/CustomerSearchView | 6b1e03b7e88e745e93b1b4b4f81d656d5a33a97b | [
"Apache-2.0"
] | 85 | 2015-06-19T07:55:40.000Z | 2022-03-12T15:07:02.000Z | app/src/main/java/com/yetwish/customsearchdemo/activity/adapter/SearchAdapter.java | b300548/CustomerSearchView | 6b1e03b7e88e745e93b1b4b4f81d656d5a33a97b | [
"Apache-2.0"
] | 1 | 2018-10-10T08:37:09.000Z | 2018-10-10T08:37:09.000Z | app/src/main/java/com/yetwish/customsearchdemo/activity/adapter/SearchAdapter.java | jiangf8686/MyFirstTest | 8bc2aa049563a8564302525865412fa4bd2511e6 | [
"Apache-2.0"
] | 83 | 2015-07-02T07:29:25.000Z | 2021-11-30T04:45:58.000Z | 32.83871 | 89 | 0.740668 | 995,639 | package com.yetwish.customsearchdemo.activity.adapter;
import android.content.Context;
import android.view.View;
import com.yetwish.customsearchdemo.R;
import com.yetwish.customsearchdemo.activity.model.Bean;
import com.yetwish.customsearchdemo.activity.util.CommonAdapter;
import com.yetwish.customsearchdemo.activity.util.ViewHolder;
import java.util.List;
/**
* Created by yetwish on 2015-05-11
*/
public class SearchAdapter extends CommonAdapter<Bean>{
public SearchAdapter(Context context, List<Bean> data, int layoutId) {
super(context, data, layoutId);
}
@Override
public void convert(ViewHolder holder, int position) {
holder.setImageResource(R.id.item_search_iv_icon,mData.get(position).getIconId())
.setText(R.id.item_search_tv_title,mData.get(position).getTitle())
.setText(R.id.item_search_tv_content,mData.get(position).getContent())
.setText(R.id.item_search_tv_comments,mData.get(position).getComments());
}
}
|
9230e528c07a696e34d0b72be52a6bbbf2eb6fc9 | 225 | java | Java | jpa/deferred/src/main/java/example/service/Customer1067Service.java | WeisonWei/spring-data-examples | 0bdca5b05cc4dd3e21271dbc9032efb2c2e75677 | [
"Apache-2.0"
] | 4,772 | 2015-01-06T12:36:15.000Z | 2022-03-30T13:37:02.000Z | jpa/deferred/src/main/java/example/service/Customer1067Service.java | divyajnu08/spring-data-examples | 735fe79e56ea22c06e1c66e4f34fcc2215bac5e2 | [
"Apache-2.0"
] | 519 | 2015-01-04T17:10:10.000Z | 2022-03-30T06:20:17.000Z | jpa/deferred/src/main/java/example/service/Customer1067Service.java | divyajnu08/spring-data-examples | 735fe79e56ea22c06e1c66e4f34fcc2215bac5e2 | [
"Apache-2.0"
] | 3,670 | 2015-01-06T03:47:23.000Z | 2022-03-31T12:16:18.000Z | 20.454545 | 59 | 0.84 | 995,640 | package example.service;
import example.repo.Customer1067Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer1067Service {
public Customer1067Service(Customer1067Repository repo) {}
}
|
9230e5b5cac95dc056fba38bc20fec49181dfa7f | 1,713 | java | Java | SIGECU/src/java/extras/ObtenerProgreso.java | RolandoCM/SIGECU | 11b4e4cc0c137f133f591736984fc8f5fc75cb11 | [
"Apache-2.0"
] | 3 | 2017-11-29T22:28:48.000Z | 2017-11-29T22:29:02.000Z | SIGECU/src/java/extras/ObtenerProgreso.java | RolandoCM/SIGECU | 11b4e4cc0c137f133f591736984fc8f5fc75cb11 | [
"Apache-2.0"
] | null | null | null | SIGECU/src/java/extras/ObtenerProgreso.java | RolandoCM/SIGECU | 11b4e4cc0c137f133f591736984fc8f5fc75cb11 | [
"Apache-2.0"
] | 1 | 2017-11-29T22:32:44.000Z | 2017-11-29T22:32:44.000Z | 30.052632 | 81 | 0.618797 | 995,641 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package extras;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
*
* @author rolando
*/
public class ObtenerProgreso {
public static int progreso(String fechaInicio, String fechaTermino)
{
double progreso;
int anioI=0;
int anioF=0;
int mesI=0;
int mesF=0;
int diaI=0;
int diaF=0;
final long MILISECS = 24*60*60*1000;
String [] ff = fechaTermino.split("-");
anioF= Integer.parseInt(ff[0]);
mesF= Integer.parseInt(ff[1]);
diaF=Integer.parseInt(ff[2]);
Date hoy = new Date();
String [] fi = fechaInicio.split("-");
anioI= Integer.parseInt(fi[0]);
mesI= Integer.parseInt(fi[1]);
diaI=Integer.parseInt(fi[2]);
//Termino
Calendar calendarF = new GregorianCalendar(anioF, mesF-1, diaF);
java.sql.Date fechaF = new java.sql.Date(calendarF.getTimeInMillis());
//Inicio
Calendar calendarI = new GregorianCalendar(anioI, mesI-1, diaI);
java.sql.Date fechaI = new java.sql.Date(calendarI.getTimeInMillis());
long diferenciaTotal = ( fechaF.getTime() - fechaI.getTime() )/MILISECS;
long diferenciaTrascurrida = (hoy.getTime() - fechaI.getTime())/MILISECS;
progreso= ((double)(diferenciaTrascurrida)/diferenciaTotal)*100;
if(progreso<0)
progreso=0;
return (int)progreso;
}
} |
9230e5be6826aab5f923c1560b14f644a518bb03 | 2,292 | java | Java | src/main/java/com/waylau/spring/boot/fileserver/domain/CollectionInfo.java | JumpJumpTiger/mongo_file_sever | 814636622b96d93b18d30bd3e5f0fd49cc8fb0ab | [
"MIT"
] | null | null | null | src/main/java/com/waylau/spring/boot/fileserver/domain/CollectionInfo.java | JumpJumpTiger/mongo_file_sever | 814636622b96d93b18d30bd3e5f0fd49cc8fb0ab | [
"MIT"
] | null | null | null | src/main/java/com/waylau/spring/boot/fileserver/domain/CollectionInfo.java | JumpJumpTiger/mongo_file_sever | 814636622b96d93b18d30bd3e5f0fd49cc8fb0ab | [
"MIT"
] | null | null | null | 25.186813 | 89 | 0.633072 | 995,642 | package com.waylau.spring.boot.fileserver.domain;
import com.waylau.spring.boot.fileserver.service.CollectionService;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
import java.util.Objects;
@Document(collection = "collectionInfoCol")
public class CollectionInfo {
@Id //主键
private String id;
@Indexed(unique=true)
private String collectionName;
private String collectionType;
private Date createDate;
private String comment;
public CollectionInfo(String collectionName, String collectionType, String comment) {
this.collectionName = collectionName;
this.collectionType = collectionType;
this.comment = comment;
this.createDate = new Date();
}
public String getCollectionType() {
return collectionType;
}
public void setCollectionType(String collectionType) {
this.collectionType = collectionType;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CollectionInfo that = (CollectionInfo) o;
return collectionName.equals(that.collectionName);
}
@Override
public int hashCode() {
return Objects.hash(collectionName);
}
@Override
public String toString() {
return "CollectionInfo{" +
"collectionName='" + collectionName + '\'' +
", collectionType=" + collectionType +
", createDate=" + createDate +
", comment='" + comment + '\'' +
'}';
}
}
|
9230e67b1aec9308deb9a899617ec4be67648e86 | 16,976 | java | Java | src/main/java/fr/univlorraine/mondossierweb/controllers/ConfigController.java | EsupPortail/esup-mdw | 6d5fefae243b11188855b7535c655def0391eeea | [
"Apache-2.0"
] | 2 | 2016-09-30T13:09:43.000Z | 2022-03-15T14:30:58.000Z | src/main/java/fr/univlorraine/mondossierweb/controllers/ConfigController.java | EsupPortail/esup-mdw | 6d5fefae243b11188855b7535c655def0391eeea | [
"Apache-2.0"
] | 42 | 2016-09-30T13:08:55.000Z | 2022-03-22T11:01:18.000Z | src/main/java/fr/univlorraine/mondossierweb/controllers/ConfigController.java | EsupPortail/esup-mdw | 6d5fefae243b11188855b7535c655def0391eeea | [
"Apache-2.0"
] | 5 | 2016-12-09T15:29:13.000Z | 2019-07-05T06:43:39.000Z | 29.574913 | 102 | 0.775566 | 995,643 | /**
*
* ESUP-Portail MONDOSSIERWEB - Copyright (c) 2016 ESUP-Portail consortium
*
*
* 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 fr.univlorraine.mondossierweb.controllers;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import fr.univlorraine.mondossierweb.MainUI;
import fr.univlorraine.mondossierweb.entities.mdw.PreferencesApplication;
import fr.univlorraine.mondossierweb.entities.mdw.PreferencesApplicationCategorie;
import fr.univlorraine.mondossierweb.entities.mdw.PreferencesApplicationValeurs;
import fr.univlorraine.mondossierweb.entities.mdw.UtilisateurSwap;
import fr.univlorraine.mondossierweb.repositories.mdw.PreferencesApplicationCategorieRepository;
import fr.univlorraine.mondossierweb.repositories.mdw.PreferencesApplicationRepository;
import fr.univlorraine.mondossierweb.repositories.mdw.PreferencesApplicationValeursRepository;
import fr.univlorraine.mondossierweb.repositories.mdw.UtilisateurSwapRepository;
/**
* Gestion de la config en base de données
*/
@Component
public class ConfigController {
private Logger LOG = LoggerFactory.getLogger(ConfigController.class);
@Resource
private PreferencesApplicationRepository preferencesApplicationRepository;
@Resource
private PreferencesApplicationValeursRepository preferencesApplicationValeursRepository;
@Resource
private PreferencesApplicationCategorieRepository preferencesApplicationCategorieRepository;
@Resource
private UtilisateurSwapRepository utilisateurSwapRepository;
public List<PreferencesApplicationCategorie> getCategories(){
return preferencesApplicationCategorieRepository.findAll();
}
public List<PreferencesApplicationCategorie> getCategoriesOrderByOrdre(){
return preferencesApplicationCategorieRepository.findAllByOrderByOrdreAsc();
}
public boolean isCertificatScolaritePDF() {
return getBooleanValueForParameter("certificatScolaritePDF");
}
public boolean isCertificatScolaritePdfMobile() {
return getBooleanValueForParameter("certificatScolaritePdfMobile");
}
public boolean isAttestationAffiliationSSO(){
return getBooleanValueForParameter("attestationAffiliationSSO");
}
public boolean isAttestSsoAutorisePersonnel(){
return getBooleanValueForParameter("attestSsoAutorisePersonnel");
}
public boolean isCertificatScolariteTouteAnnee() {
return getBooleanValueForParameter("certificatScolariteTouteAnnee");
}
public boolean isCertScolAutorisePersonnel() {
return getBooleanValueForParameter("certScolAutorisePersonnel");
}
public boolean isCertificatScolaritePiecesNonValidees() {
return getBooleanValueForParameter("certificatScolaritePJinvalide");
}
public boolean isCertificatScolariteDossierNonValide() {
return getBooleanValueForParameter("certificatScolariteDossierNonValide");
}
public boolean isApplicationActive() {
return getBooleanValueForParameter("applicationActive");
}
public boolean isApplicationMobileActive() {
return getBooleanValueForParameter("applicationMobileActive");
}
public boolean isPartieEnseignantActive() {
return getBooleanValueForParameter("partieEnseignantActive");
}
public boolean isPartieEtudiantActive() {
return getBooleanValueForParameter("partieEtudiantActive");
}
public List<String> getListeLoginsBloques() {
return getListValeurForParameter("listeLoginsBloques");
}
public List<String> getListeCertScolTypDiplomeDesactive() {
return getListValeurForParameter("certScolTypDiplomeDesactive");
}
public boolean isAffRangEtudiant() {
return getBooleanValueForParameter("afficherRangEtudiant");
}
public boolean isAffResultatsEpreuves(){
return getBooleanValueForParameter("affResultatsEpreuves");
}
public boolean isAffBtnCertifNouvelleLigne(){
return getBooleanValueForParameter("afficherBoutonCertifNouvelleLigne");
}
public boolean isAffBtnCertificatCouleur() {
return getBooleanValueForParameter("afficherBoutonCertifCouleur");
}
public boolean isAffBtnQuittanceCouleur() {
return getBooleanValueForParameter("afficherBoutonQuittanceCouleur");
}
public boolean isAffBtnAttestSsoNouvelleLigne(){
return getBooleanValueForParameter("afficherBoutonAttestSsoNouvelleLigne");
}
public boolean isQuittanceDossierNonValide() {
return getBooleanValueForParameter("quittanceDossierNonValide");
}
public boolean isQuittanceDroitsPayes(){
return getBooleanValueForParameter("quittanceDroitsPayes");
}
public boolean isQuittanceDroitsPayesAutorisePersonnel(){
return getBooleanValueForParameter("quittanceDroitsPayesAutorisePersonnel");
}
public boolean isAffBtnQuittanceDroitsPayesNouvelleLigne(){
return getBooleanValueForParameter("afficherBoutonQuittanceNouvelleLigne");
}
public boolean isLogoutCasPropose() {
return getBooleanValueForParameter("logoutCasPropose");
}
public boolean isAffECTSEtudiant() {
return getBooleanValueForParameter("affECTSEtudiant");
}
public boolean isAffECTSIPEtudiant() {
return getBooleanValueForParameter("affECTSIPEtudiant");
}
public boolean isMasqueSession2Vide() {
return getBooleanValueForParameter("masqueSession2Vide");
}
public boolean isRenommeSession1Unique() {
return getBooleanValueForParameter("renommeSession1Unique");
}
public boolean isMasqueECTSEtudiant() {
return getBooleanValueForParameter("masqueECTSEtudiant");
}
public boolean isMasqueECTSIPEtudiant() {
return getBooleanValueForParameter("masqueECTSIPEtudiant");
}
public boolean isModificationAdressesAutorisee() {
return getBooleanValueForParameter("modificationAdresses");
}
public boolean isAffNumerosAnonymat() {
return getBooleanValueForParameter("affNumerosAnonymat");
}
public boolean isModificationCoordonneesPersoAutorisee() {
return getBooleanValueForParameter("modificationCoordonneesContactPerso");
}
public boolean isAffMentionEtudiant() {
return getBooleanValueForParameter("affMentionEtudiant");
}
public boolean isAffMessageNotesInformatives() {
return getBooleanValueForParameter("affMessageNotesInformatives");
}
public boolean isTemNotesEtuSem() {
return getBooleanValueForParameter("temNotesEtuSem");
}
public boolean isToujoursAfficherBareme() {
return getBooleanValueForParameter("affBaremeEtudiant");
}
public boolean isCertScolUtiliseLogo() {
return getBooleanValueForParameter("certScolUtiliseLogo");
}
public boolean isCertScolRegimeIns(){
return getBooleanValueForParameter("certScolRegimeIns");
}
public boolean isAffiliationSsoUsageEtatCivil() {
return getBooleanValueForParameter("attestationAffiliationSSOUsageEtatCivil");
}
public boolean isQuittanceDroitsPayesUsageEtatCivil() {
return getBooleanValueForParameter("quittanceDroitsPayesUsageEtatCivil");
}
public boolean isNotesPDFUsageEtatCivil() {
return getBooleanValueForParameter("notesPDFUsageEtatCivil");
}
public boolean isCertScolUsageEtatCivil() {
return getBooleanValueForParameter("certScolUsageEtatCivil");
}
public boolean isPdfNotesActive() {
return getBooleanValueForParameter("notesPDF");
}
public boolean isInsertionFiligranePdfNotes() {
return getBooleanValueForParameter("insertionFiligranePdfNotes");
}
public boolean isAffNumPlaceExamen() {
return getBooleanValueForParameter("affNumPlaceExamen");
}
public boolean isAffDetailExamen() {
return getBooleanValueForParameter("affDetailExamen");
}
public boolean isAffAdresseEnseignants() {
return getBooleanValueForParameter("affAdressesEnseignants");
}
public boolean isAffInfosAnnuellesEnseignants() {
return getBooleanValueForParameter("affInfosAnnuellesEnseignants");
}
public boolean isAffInfosContactEnseignants() {
return getBooleanValueForParameter("affInfosContactEnseignants");
}
public boolean isAffCalendrierEpreuvesEnseignants() {
return getBooleanValueForParameter("affCalendrierEpreuvesEnseignants");
}
public boolean isAffCalendrierEpreuvesEtudiants() {
return getBooleanValueForParameter("affCalendrierEpreuvesEtudiants");
}
public boolean isCertificatScolariteCarteEditee() {
return getBooleanValueForParameter("certificatScolariteEditionCarte");
}
public boolean isAffResAdmissibilite() {
return getBooleanValueForParameter("affResultatsAdmissibilite");
}
public boolean isAffichageDateNaissancePdfNotesPaysage() {
return getBooleanValueForParameter("affDateNaissancePdfNotesPaysage");
}
public List<String> getListeCertScolProfilDesactive(){
return getListValeurForParameter("certScolProfilDesactive");
}
public List<String> getListeCertScolCGEDesactive() {
return getListValeurForParameter("certScolCGEDesactive");
}
public List<String> getListeCertScolCmpDesactive() {
return getListValeurForParameter("certScolCmpDesactive");
}
public List<String> getListeCertScolStatutDesactive(){
return getListValeurForParameter("certScolStatutDesactive");
}
public List<String> getListeCodesEtapeAffichageRang() {
return getListValeurForParameter("codesEtapeAffichageRang");
}
public List<String> getListeCodesBlocageAffichageNotes(){
return getListValeurForParameter("codesBlocageAffichageNotes");
}
public List<String> getListeCodesBlocageAccesApplication(){
return getListValeurForParameter("codesBlocageAccesApplication");
}
public List<String> getTypesEpreuveAffichageNote() {
return getListValeurForParameter("typesEpreuveAffichageNote");
}
public String getAssistanceDocUrl() {
return getValeurForParameter("assistanceDocUrl");
}
public String getAssistanceHelpdeskUrl() {
return getValeurForParameter("assistanceHelpdeskUrl");
}
public String getAssistanceContactMail() {
return getValeurForParameter("assistanceContactMail");
}
public String getTemoinEtatIaeNotesEnseignant() {
return getValeurForParameter("temoinEtatIaeNotesEnseignant");
}
public String getTemoinEtatIaeNotesEtudiant() {
return getValeurForParameter("temoinEtatIaeNotesEtudiant");
}
public float getQuittancePdfPositionSignatureX() {
return Float.parseFloat(getQuittancePdfPositionSignature().split("-")[0]);
}
public float getQuittancePdfPositionSignatureY() {
return Float.parseFloat(getQuittancePdfPositionSignature().split("-")[1]);
}
private String getQuittancePdfPositionSignature() {
return getValeurForParameter("quittancePdfPositionSignature");
}
private String getCertificatScolaritePdfPositionSignature() {
return getValeurForParameter("certificatScolaritePdfPositionSignature");
}
public float getCertificatScolaritePdfPositionSignatureX() {
return Float.parseFloat(getCertificatScolaritePdfPositionSignature().split("-")[0]);
}
public float getCertificatScolaritePdfPositionSignatureY() {
return Float.parseFloat(getCertificatScolaritePdfPositionSignature().split("-")[1]);
}
public String getTemoinNotesEtudiant() {
return getValeurForParameter("temoinNotesEtudiant");
}
public String getTemoinNotesEnseignant() {
return getValeurForParameter("temoinNotesEnseignant");
}
public String getTemoinCtlValCadEpr() {
return getValeurForParameter("temoinCtlValCadEpr");
}
public String getTemoinFictif() {
return getValeurForParameter("temoinFictif");
}
public boolean isQuittancePdfSignature() {
return getBooleanValueForParameter("quittancePdfSignature");
}
public String getQuittanceCodeSignataire() {
return getValeurForParameter("quittanceCodeSignataire");
}
public boolean isQuittanceSignatureTampon() {
return getBooleanValueForParameter("quittanceSignatureTampon");
}
public String getCertScolCodeSignataire() {
return getValeurForParameter("certScolCodeSignataire");
}
public String getQuittanceDescSignataire() {
return getValeurForParameter("quittanceDescSignataire");
}
public String getCertScolDescSignataire() {
return getValeurForParameter("certScolDescSignataire");
}
public String getLogoUniversitePdf() {
return getValeurForParameter("logoUniversitePdf");
}
public String getCertScolHeaderUniv() {
return getValeurForParameter("certScolHeaderUniv");
}
public String getCertScolFooter() {
return getValeurForParameter("certScolFooter");
}
public String getCertScolLieuEdition() {
return getValeurForParameter("certScolLieuEdition");
}
public String getCertScolTampon() {
return getValeurForParameter("certScolTampon");
}
public int getTrombiMobileNbEtuParPage(){
return Integer.parseInt(getValeurForParameter("trombiMobileNbEtuParPage"));
}
public String getExtensionMailEtudiant(){
return getValeurForParameter("extensionMailEtudiant");
}
public int getNotesNombreAnneesExtractionApogee() {
return Integer.parseInt(getValeurForParameter("notesNombreAnneesExtractionApogee"));
}
public String getNotesAnneePivotExtractionApogee() {
return getValeurForParameter("notesAnneePivotExtractionApogee");
}
public boolean isNotesAnneeOuverteResExtractionApogee() {
return getBooleanValueForParameter("notesAnneeOuverteResExtractionApogee");
}
public boolean isAffichagePdfNotesFormatPortrait() {
return getBooleanValueForParameter("notesPDFFormatPortrait");
}
public boolean isNotesPDFsignature() {
return getBooleanValueForParameter("notesPDFSignature");
}
public String getNotesPDFLieuEdition() {
return getValeurForParameter("notesPDFLieuEdition");
}
public String[] getHeaderColorPdf() {
String color = getValeurForParameter("headerColorPdf");
return color.split(",");
}
/**
*
* @param parameter
* @return la valeur d'un parametre de type liste de valeurs
*/
private List<String> getListValeurForParameter(String parameter){
LinkedList<String> values = new LinkedList<String>();
PreferencesApplication pa = preferencesApplicationRepository.findOne(parameter);
if(pa!=null && pa.getPrefId()!=null){
if(pa.getPreferencesApplicationValeurs()!=null && pa.getPreferencesApplicationValeurs().size()>0){
for(PreferencesApplicationValeurs valeur : pa.getPreferencesApplicationValeurs()){
values.add(valeur.getValeur());
}
}
}
return values;
}
/**
*
* @param parameter
* @return la valeur d'un parametre de type String
*/
private String getValeurForParameter(String parameter){
PreferencesApplication pa = preferencesApplicationRepository.findOne(parameter);
if(pa!=null && StringUtils.hasText(pa.getValeur())){
return pa.getValeur();
}
return null;
}
/**
*
* @return les parametres applicatifs en base
*/
public List<PreferencesApplication> getAppParameters(){
return preferencesApplicationRepository.findAll();
}
/**
*
* @return les parametres applicatifs en base pour une catégorie donnée
*/
public List<PreferencesApplication> getAppParametersForCatId(Integer catId){
return preferencesApplicationRepository.findPreferencesApplicationFromCatId(catId);
}
/**
*
* @return les parametres applicatifs en base
*/
public List<UtilisateurSwap> getSwapUtilisateurs(){
return utilisateurSwapRepository.findAll();
}
/**
*
* @return les parametres applicatifs en base
*/
public UtilisateurSwap getSwapUtilisateur(String login){
return utilisateurSwapRepository.findOne(login);
}
/**
*
* @param parameter
* @return la valeur d'un parametre de type booleen
*/
private boolean getBooleanValueForParameter(String parameter){
PreferencesApplication pa = preferencesApplicationRepository.findOne(parameter);
if(pa!=null && StringUtils.hasText(pa.getValeur())
&& pa.getValeur().equals("true")){
return true;
}
return false;
}
public void saveAppParameter(PreferencesApplication prefApp) {
preferencesApplicationRepository.saveAndFlush(prefApp);
}
public void saveSwap(UtilisateurSwap swap) {
utilisateurSwapRepository.saveAndFlush(swap);
}
}
|
9230e6c61c365bb23fa777bbea5b9f4becf8b5aa | 3,475 | java | Java | gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/ser/GraphSONMessageSerializerGremlinV2d0.java | divijvaidya/tinkerpop | 3707fcfe3b873fc9ffc1be0379189b4d41e20390 | [
"Apache-2.0"
] | 1,425 | 2016-06-13T06:08:39.000Z | 2022-03-28T09:02:43.000Z | gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/ser/GraphSONMessageSerializerGremlinV2d0.java | divijvaidya/tinkerpop | 3707fcfe3b873fc9ffc1be0379189b4d41e20390 | [
"Apache-2.0"
] | 1,049 | 2016-06-10T10:25:59.000Z | 2022-03-30T11:25:44.000Z | gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/ser/GraphSONMessageSerializerGremlinV2d0.java | divijvaidya/tinkerpop | 3707fcfe3b873fc9ffc1be0379189b4d41e20390 | [
"Apache-2.0"
] | 732 | 2016-06-13T20:53:51.000Z | 2022-03-30T06:49:29.000Z | 36.578947 | 103 | 0.729496 | 995,644 | /*
* 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.tinkerpop.gremlin.driver.ser;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONXModuleV2d0;
import org.apache.tinkerpop.gremlin.structure.io.graphson.TypeInfo;
import java.nio.ByteBuffer;
/**
* Serialize results to JSON with version 2.0.x schema and the extended module.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
* @deprecated As for release 3.4.0, replaced by {@link GraphSONMessageSerializerV2d0}.
*/
@Deprecated
public final class GraphSONMessageSerializerGremlinV2d0 extends AbstractGraphSONMessageSerializerV2d0 {
private static final String MIME_TYPE = SerTokens.MIME_GRAPHSON_V2D0;
private static byte[] header;
static {
final ByteBuffer buffer = ByteBuffer.allocate(MIME_TYPE.length() + 1);
buffer.put((byte) MIME_TYPE.length());
buffer.put(MIME_TYPE.getBytes());
header = buffer.array();
}
/**
* Creates a default GraphSONMessageSerializerGremlin.
* <p>
* By default this will internally instantiate a {@link GraphSONMapper} and register
* a {@link GremlinServerModule} and {@link GraphSONXModuleV2d0} to the mapper.
*
* @see #GraphSONMessageSerializerGremlinV2d0(GraphSONMapper.Builder)
*/
public GraphSONMessageSerializerGremlinV2d0() {
super();
}
/**
* Create a GraphSONMessageSerializer from a {@link GraphSONMapper}. Deprecated, use
* {@link #GraphSONMessageSerializerGremlinV2d0(GraphSONMapper.Builder)} instead.
*/
@Deprecated
public GraphSONMessageSerializerGremlinV2d0(final GraphSONMapper mapper) {
super(mapper);
}
/**
* Create a GraphSONMessageSerializerGremlin with a provided {@link GraphSONMapper.Builder}.
* <p>
* Note that to make this mapper usable in the context of request messages and responses,
* this method will automatically register a {@link GremlinServerModule} to the provided
* mapper.
*/
public GraphSONMessageSerializerGremlinV2d0(final GraphSONMapper.Builder mapperBuilder) {
super(mapperBuilder);
}
@Override
public String[] mimeTypesSupported() {
return new String[]{SerTokens.MIME_GRAPHSON_V2D0, SerTokens.MIME_JSON};
}
@Override
byte[] obtainHeader() {
return header;
}
@Override
GraphSONMapper.Builder configureBuilder(final GraphSONMapper.Builder builder) {
// already set to 2.0 in AbstractGraphSONMessageSerializerV2d0
return builder.typeInfo(TypeInfo.PARTIAL_TYPES).addCustomModule(new GremlinServerModule());
}
}
|
9230e7199ae8b8635aa4c271f7f3f4e7c9064dad | 404 | java | Java | S_CHAT/s_chat/build/app/generated/not_namespaced_r_class_sources/release/r/androidx/lifecycle/runtime/R.java | SARVASVA-BIT/IEEE-Megaproject | 423534c3c4147e6a6766fecdb10a2755b2fef486 | [
"MIT"
] | 8 | 2022-01-07T14:07:07.000Z | 2022-02-05T04:03:07.000Z | S_CHAT/s_chat/build/app/generated/not_namespaced_r_class_sources/release/r/androidx/lifecycle/runtime/R.java | SARVASVA-BIT/IEEE-Megaproject | 423534c3c4147e6a6766fecdb10a2755b2fef486 | [
"MIT"
] | 41 | 2022-01-08T08:42:08.000Z | 2022-02-28T01:49:15.000Z | S_CHAT/s_chat/build/app/generated/not_namespaced_r_class_sources/release/r/androidx/lifecycle/runtime/R.java | SARVASVA-BIT/IEEE-Megaproject | 423534c3c4147e6a6766fecdb10a2755b2fef486 | [
"MIT"
] | 50 | 2022-01-07T13:15:15.000Z | 2022-02-25T04:35:15.000Z | 22.444444 | 71 | 0.683168 | 995,645 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package androidx.lifecycle.runtime;
public final class R {
private R() {}
public static final class id {
private id() {}
public static final int view_tree_lifecycle_owner = 0x7f08015b;
}
}
|
9230e71ad26a524031a34e97a497f9057176b576 | 1,119 | java | Java | src/main/java/act/ws/DefaultSecureTicketCodec.java | kehao-study/act_compile | b9381a9a0a83297bad7aebe8898f6ef12852ce03 | [
"Apache-2.0"
] | 776 | 2015-06-17T01:08:11.000Z | 2022-03-18T10:58:56.000Z | src/main/java/act/ws/DefaultSecureTicketCodec.java | kehao-study/act_compile | b9381a9a0a83297bad7aebe8898f6ef12852ce03 | [
"Apache-2.0"
] | 1,390 | 2015-05-25T20:24:44.000Z | 2022-01-24T23:49:33.000Z | src/main/java/act/ws/DefaultSecureTicketCodec.java | benstonezhang/actframework | 2554aced980de115939bfad4d003c74ff8f04112 | [
"Apache-2.0"
] | 149 | 2015-05-29T08:38:34.000Z | 2022-02-12T16:01:29.000Z | 26.023256 | 75 | 0.718499 | 995,646 | package act.ws;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* 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.
* #L%
*/
import act.crypto.AppCrypto;
import javax.inject.Singleton;
/**
* Default implementation of {@link SecureTicketCodec}. This implementation
* encode everything from the session object into the secure ticket
*/
@Singleton
public class DefaultSecureTicketCodec extends StringSecureTicketCodec {
public DefaultSecureTicketCodec() {
super();
}
public DefaultSecureTicketCodec(AppCrypto crypto) {
super(crypto);
}
}
|
9230e76cee75361359ec1a2ba83b411d5a5bf9c6 | 4,122 | java | Java | java/org/l2jserver/gameserver/model/actor/instance/SiegeFlagInstance.java | Williams-BR/L2JStudio-V2 | f3d3b329657c0f031dab107e6d4ceb5ddad0bea6 | [
"MIT"
] | 6 | 2020-05-14T22:52:59.000Z | 2022-02-24T01:37:23.000Z | java/org/l2jserver/gameserver/model/actor/instance/SiegeFlagInstance.java | huttysa/L2JServer_C6_Interlude | f3d3b329657c0f031dab107e6d4ceb5ddad0bea6 | [
"MIT"
] | 2 | 2020-12-10T15:08:48.000Z | 2021-12-01T01:01:46.000Z | java/org/l2jserver/gameserver/model/actor/instance/SiegeFlagInstance.java | huttysa/L2JServer_C6_Interlude | f3d3b329657c0f031dab107e6d4ceb5ddad0bea6 | [
"MIT"
] | 15 | 2020-05-08T20:41:06.000Z | 2022-02-24T01:36:58.000Z | 31.465649 | 147 | 0.733139 | 995,647 | /*
* This file is part of the L2JServer project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jserver.gameserver.model.actor.instance;
import org.l2jserver.gameserver.ai.CtrlIntention;
import org.l2jserver.gameserver.instancemanager.SiegeManager;
import org.l2jserver.gameserver.model.SiegeClan;
import org.l2jserver.gameserver.model.actor.Creature;
import org.l2jserver.gameserver.model.actor.templates.NpcTemplate;
import org.l2jserver.gameserver.model.entity.siege.Siege;
import org.l2jserver.gameserver.network.serverpackets.ActionFailed;
import org.l2jserver.gameserver.network.serverpackets.MyTargetSelected;
import org.l2jserver.gameserver.network.serverpackets.StatusUpdate;
import org.l2jserver.gameserver.network.serverpackets.ValidateLocation;
public class SiegeFlagInstance extends NpcInstance
{
private final PlayerInstance _player;
private final Siege _siege;
public SiegeFlagInstance(PlayerInstance player, int objectId, NpcTemplate template)
{
super(objectId, template);
_player = player;
_siege = SiegeManager.getInstance().getSiege(_player.getX(), _player.getY(), _player.getZ());
if ((_player.getClan() == null) || (_siege == null))
{
deleteMe();
}
else
{
final SiegeClan sc = _siege.getAttackerClan(_player.getClan());
if (sc == null)
{
deleteMe();
}
else
{
sc.addFlag(this);
}
}
}
@Override
public boolean isAttackable()
{
// Attackable during siege by attacker only
return (getCastle() != null) && (getCastle().getCastleId() > 0) && getCastle().getSiege().isInProgress();
}
@Override
public boolean isAutoAttackable(Creature attacker)
{
// Attackable during siege by attacker only
return (attacker instanceof PlayerInstance) && (getCastle() != null) && (getCastle().getCastleId() > 0) && getCastle().getSiege().isInProgress();
}
@Override
public boolean doDie(Creature killer)
{
if (!super.doDie(killer))
{
return false;
}
final SiegeClan sc = _siege.getAttackerClan(_player.getClan());
if (sc != null)
{
sc.removeFlag(this);
}
return true;
}
@Override
public void onForcedAttack(PlayerInstance player)
{
onAction(player);
}
@Override
public void onAction(PlayerInstance player)
{
if ((player == null) || !canTarget(player))
{
return;
}
// Check if the PlayerInstance already target the NpcInstance
if (this != player.getTarget())
{
// Set the target of the PlayerInstance player
player.setTarget(this);
// Send a Server->Client packet MyTargetSelected to the PlayerInstance player
player.sendPacket(new MyTargetSelected(getObjectId(), player.getLevel() - getLevel()));
// Send a Server->Client packet StatusUpdate of the NpcInstance to the PlayerInstance to update its HP bar
final StatusUpdate su = new StatusUpdate(getObjectId());
su.addAttribute(StatusUpdate.CUR_HP, (int) getStatus().getCurrentHp());
su.addAttribute(StatusUpdate.MAX_HP, getMaxHp());
player.sendPacket(su);
// Send a Server->Client packet ValidateLocation to correct the NpcInstance position and heading on the client
player.sendPacket(new ValidateLocation(this));
}
else if (isAutoAttackable(player) && (Math.abs(player.getZ() - getZ()) < 100))
{
player.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, this);
}
else
{
// Send a Server->Client ActionFailed to the PlayerInstance in order to avoid that the client wait another packet
player.sendPacket(ActionFailed.STATIC_PACKET);
}
}
}
|
9230e7de133df37559296fe18c8dde9e92399918 | 763 | java | Java | Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/basic/BasicProperties.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/basic/BasicProperties.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Client/src/main/java/org/mage/plugins/card/dl/beans/properties/basic/BasicProperties.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 21.8 | 69 | 0.65924 | 995,648 | package org.mage.plugins.card.dl.beans.properties.basic;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mage.plugins.card.dl.beans.properties.AbstractProperties;
import org.mage.plugins.card.dl.beans.properties.Property;
/**
* The class BoundProperties.
*
* @version V0.0 24.08.2010
* @author Clemens Koza
*/
public class BasicProperties extends AbstractProperties {
public <T> Property<T> property(String name, Property<T> value) {
return value;
}
public <E> List<E> list(String name, List<E> list) {
return list;
}
public <E> Set<E> set(String name, Set<E> set) {
return set;
}
public <K, V> Map<K, V> map(String name, Map<K, V> map) {
return map;
}
}
|
9230e825736a38b1841c9cd1f6ce11e9cb6f387c | 638 | java | Java | sqlitefinal/src/main/java/cn/finalteam/sqlitefinal/utils/IOUtils.java | pengjianbo/SQLiteFinal | e331baa81880fa1f4cc6cc4a0106f46172b6b8fa | [
"Apache-2.0"
] | 13 | 2015-10-12T12:56:05.000Z | 2020-01-02T08:51:36.000Z | sqlitefinal/src/main/java/cn/finalteam/sqlitefinal/utils/IOUtils.java | PaoJiao/SQLiteFinal | e331baa81880fa1f4cc6cc4a0106f46172b6b8fa | [
"Apache-2.0"
] | null | null | null | sqlitefinal/src/main/java/cn/finalteam/sqlitefinal/utils/IOUtils.java | PaoJiao/SQLiteFinal | e331baa81880fa1f4cc6cc4a0106f46172b6b8fa | [
"Apache-2.0"
] | null | null | null | 18.764706 | 58 | 0.518809 | 995,649 | package cn.finalteam.sqlitefinal.utils;
import android.database.Cursor;
import java.io.Closeable;
/**
* Desction:IO工具类
* Author:pengjianbo
* Date:15/7/3 上午11:04
*/
public class IOUtils {
private IOUtils() {
}
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Throwable e) {
}
}
}
public static void closeQuietly(Cursor cursor) {
if (cursor != null) {
try {
cursor.close();
} catch (Throwable e) {
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.