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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e069bf4603d72fd2fd5378055ec84aeb1b945a8
| 3,079 |
java
|
Java
|
org.eclipse.gemini.jpa.test.weaved/src/org/eclipse/gemini/jpa/test/weaved/TestWeaving.java
|
rheydenr/gemini.jpa
|
3c9cef81b2364e2fe2c917d61c559ebe0e53d96d
|
[
"Apache-2.0"
] | null | null | null |
org.eclipse.gemini.jpa.test.weaved/src/org/eclipse/gemini/jpa/test/weaved/TestWeaving.java
|
rheydenr/gemini.jpa
|
3c9cef81b2364e2fe2c917d61c559ebe0e53d96d
|
[
"Apache-2.0"
] | null | null | null |
org.eclipse.gemini.jpa.test.weaved/src/org/eclipse/gemini/jpa/test/weaved/TestWeaving.java
|
rheydenr/gemini.jpa
|
3c9cef81b2364e2fe2c917d61c559ebe0e53d96d
|
[
"Apache-2.0"
] | null | null | null | 30.79 | 103 | 0.587528 | 2,817 |
/*******************************************************************************
* Copyright (c) 2010 Oracle.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
* mkeith - Gemini JPA tests
******************************************************************************/
package org.eclipse.gemini.jpa.test.weaved;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.junit.*;
import org.osgi.framework.BundleContext;
import model.weaved.WeavedEntity;
import org.eclipse.gemini.jpa.test.common.JpaTest;
/**
* Test class to test weaving of JPA provider
*
* @author mkeith
*/
public class TestWeaving extends JpaTest {
public static final String TEST_NAME = "TestWeaving";
public static final String PERSISTENCE_UNIT_UNDER_TEST = "Weaved";
public static EntityManagerFactory emf;
public static BundleContext ctx;
/* === Test Methods === */
@BeforeClass
public static void classSetUp() {
sdebug(TEST_NAME, "In setup");
emf = lookupEntityManagerFactory(TEST_NAME, PERSISTENCE_UNIT_UNDER_TEST, ctx);
sdebug(TEST_NAME, "Got EMF - " + emf);
}
@AfterClass
public static void classCleanUp() throws Exception {
if (emf != null) {
emf.close();
emf = null;
}
}
/* === Additional test methods === */
@Test
public void testWovenClass() {
debug("testWovenClass");
WeavedEntity entity = new WeavedEntity();
boolean weaved = false;
Class<?>[] clsArray = entity.getClass().getInterfaces();
for ( Class<?> cls : clsArray) {
if (cls.toString().equals("org.eclipse.persistence.internal.weaving.PersistenceWeaved")) {
weaved = true;
break;
}
}
assert(weaved) ;
}
/* === Subclassed methods === */
public boolean needsDsfService() { return false; }
public EntityManagerFactory getEmf() { return emf; }
public String getTestPersistenceUnitName() { return PERSISTENCE_UNIT_UNDER_TEST; }
public Object newObject() {
WeavedEntity a = new WeavedEntity();
a.setId(100);
return a;
}
public Object findObject() {
EntityManager em = getEmf().createEntityManager();
Object obj = em.find(WeavedEntity.class, 100);
em.close();
return obj;
}
public String queryString() {
return "SELECT a FROM WeavedEntity a";
}
}
|
3e069c2e7f12a90f9bb1a99bb391f9c042233fa9
| 3,442 |
java
|
Java
|
server/src/main/java/org/elasticsearch/common/network/CIDRUtils.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null |
server/src/main/java/org/elasticsearch/common/network/CIDRUtils.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null |
server/src/main/java/org/elasticsearch/common/network/CIDRUtils.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null | 37.824176 | 114 | 0.59355 | 2,818 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.network;
import org.elasticsearch.core.Tuple;
import java.net.InetAddress;
import java.util.Arrays;
public class CIDRUtils {
// Borrowed from Lucene, rfc4291 prefix
static final byte[] IPV4_PREFIX = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1 };
private CIDRUtils() {}
public static boolean isInRange(String address, String... cidrAddresses) {
// Check if address is parsable first
byte[] addr = InetAddresses.forString(address).getAddress();
if (cidrAddresses == null || cidrAddresses.length == 0) {
return false;
}
for (String cidrAddress : cidrAddresses) {
if (cidrAddress == null) continue;
byte[] lower, upper;
if (cidrAddress.contains("/")) {
final Tuple<byte[], byte[]> range = getLowerUpper(InetAddresses.parseCidr(cidrAddress));
lower = range.v1();
upper = range.v2();
} else {
lower = InetAddresses.forString(cidrAddress).getAddress();
upper = lower;
}
if (isBetween(addr, lower, upper)) return true;
}
return false;
}
private static Tuple<byte[], byte[]> getLowerUpper(Tuple<InetAddress, Integer> cidr) {
final InetAddress value = cidr.v1();
final Integer prefixLength = cidr.v2();
if (prefixLength < 0 || prefixLength > 8 * value.getAddress().length) {
throw new IllegalArgumentException(
"illegal prefixLength '" + prefixLength + "'. Must be 0-32 for IPv4 ranges, 0-128 for IPv6 ranges"
);
}
byte[] lower = value.getAddress();
byte[] upper = value.getAddress();
// Borrowed from Lucene
for (int i = prefixLength; i < 8 * lower.length; i++) {
int m = 1 << (7 - (i & 7));
lower[i >> 3] &= ~m;
upper[i >> 3] |= m;
}
return new Tuple<>(lower, upper);
}
private static boolean isBetween(byte[] addr, byte[] lower, byte[] upper) {
// Encode the addresses bytes if lengths do not match
if (addr.length != lower.length) {
addr = encode(addr);
lower = encode(lower);
upper = encode(upper);
}
return Arrays.compareUnsigned(lower, addr) <= 0 && Arrays.compareUnsigned(upper, addr) >= 0;
}
// Borrowed from Lucene to make this consistent IP fields matching for the mix of IPv4 and IPv6 values
// Modified signature to avoid extra conversions
private static byte[] encode(byte[] address) {
if (address.length == 4) {
byte[] mapped = new byte[16];
System.arraycopy(IPV4_PREFIX, 0, mapped, 0, IPV4_PREFIX.length);
System.arraycopy(address, 0, mapped, IPV4_PREFIX.length, address.length);
address = mapped;
} else if (address.length != 16) {
throw new UnsupportedOperationException("Only IPv4 and IPv6 addresses are supported");
}
return address;
}
}
|
3e069ce7eba2b20f602aaa6684dcc36aed8d8e00
| 1,549 |
java
|
Java
|
src/main/java/org/furcoder/zero_caterpillar/task/ImmediateTask.java
|
FurCoder/ZeroCaterpillar
|
286d320718e70d8ccfbd96ceed0a844f4198ce72
|
[
"Apache-2.0"
] | 2 |
2019-04-05T11:54:05.000Z
|
2019-05-01T15:17:04.000Z
|
src/main/java/org/furcoder/zero_caterpillar/task/ImmediateTask.java
|
FurCoder/ZeroCaterpillar
|
286d320718e70d8ccfbd96ceed0a844f4198ce72
|
[
"Apache-2.0"
] | 4 |
2020-03-04T22:34:15.000Z
|
2021-12-09T20:59:26.000Z
|
src/main/java/org/furcoder/zero_caterpillar/task/ImmediateTask.java
|
FurCoder/ZeroCaterpillar
|
286d320718e70d8ccfbd96ceed0a844f4198ce72
|
[
"Apache-2.0"
] | 3 |
2019-04-05T12:24:26.000Z
|
2022-02-02T01:49:03.000Z
| 27.660714 | 93 | 0.751453 | 2,819 |
/*
* 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.furcoder.zero_caterpillar.task;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import java.util.concurrent.atomic.AtomicLong;
@FieldDefaults(level = AccessLevel.PRIVATE)
public abstract class ImmediateTask extends TaskSequence implements Comparable<ImmediateTask>
{
static final AtomicLong counter = new AtomicLong();
public final long id = counter.getAndIncrement();
public final int priority;
protected ImmediateTask()
{
this(0);
}
protected ImmediateTask(int priority)
{
this.priority = priority;
}
@Override
public int compareTo(ImmediateTask t)
{
if (priority != t.priority) return priority - t.priority;
if (id > t.id) return -1;
if (id < t.id) return 1;
return 0;
}
}
|
3e069eab6267a4b7d7c245490ffc7c1435077cc2
| 2,850 |
java
|
Java
|
gosu-core-api/src/main/java/gw/xml/simple/SimpleXmlNodeHandler.java
|
moneytech/gosu-lang
|
053bd00caa740f44ae8195bbebe1ba1a12734037
|
[
"Apache-2.0"
] | 389 |
2015-01-14T14:13:17.000Z
|
2022-03-21T16:35:39.000Z
|
gosu-core-api/src/main/java/gw/xml/simple/SimpleXmlNodeHandler.java
|
moneytech/gosu-lang
|
053bd00caa740f44ae8195bbebe1ba1a12734037
|
[
"Apache-2.0"
] | 114 |
2015-02-20T01:06:56.000Z
|
2022-02-14T18:14:13.000Z
|
gosu-core-api/src/main/java/gw/xml/simple/SimpleXmlNodeHandler.java
|
moneytech/gosu-lang
|
053bd00caa740f44ae8195bbebe1ba1a12734037
|
[
"Apache-2.0"
] | 92 |
2015-01-08T20:13:01.000Z
|
2022-03-30T06:54:20.000Z
| 27.142857 | 127 | 0.664561 | 2,820 |
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.xml.simple;
import gw.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
class SimpleXmlNodeHandler extends DefaultHandler {
private Stack<SimpleXmlNode> _elementStack = new Stack<SimpleXmlNode>();
private Stack<StringBuilder> _textStack = new Stack<StringBuilder>();
private SimpleXmlNode _root = null;
private StringBuilder _currentText;
public SimpleXmlNodeHandler() {
}
public SimpleXmlNode getRoot() {
return _root;
}
@Override
public void startElement(String uri, String localName,
String qualifiedName, Attributes attributes)
throws SAXException {
SimpleXmlNode element = new SimpleXmlNode(removePrefix(qualifiedName));
for (int i = 0; i < attributes.getLength(); i++) {
String attributeLocalName = removePrefix(attributes.getQName(i));
if (element.getAttributes().containsKey(attributeLocalName)) {
throw new IllegalStateException("Duplicate attributes were found with identical local names of " + attributeLocalName);
}
element.getAttributes().put(attributeLocalName, attributes.getValue(i));
}
if (!_elementStack.isEmpty()) {
SimpleXmlNode parent = _elementStack.peek();
parent.getChildren().add(element);
} else {
_root = element;
}
_elementStack.push(element);
_textStack.push(_currentText);
_currentText = null;
}
/**
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (!_elementStack.isEmpty()) {
SimpleXmlNode ended = _elementStack.pop();
if (_currentText != null && !isBlank(_currentText)) {
ended.setText(_currentText.toString());
} else {
ended.setText(null);
}
_currentText = _textStack.pop();
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (_currentText == null) {
_currentText = new StringBuilder();
_currentText.append(ch, start, length);
if (isBlank(_currentText)) {
_currentText = null;
}
} else {
_currentText.append(ch, start, length);
}
}
private boolean isBlank(StringBuilder sb) {
for (int i = 0; i < sb.length(); i++) {
if (!Character.isWhitespace(sb.charAt(i))) {
return false;
}
}
return true;
}
@Override
public void error(SAXParseException e) throws SAXException {
// For now, do nothing
}
private String removePrefix(String localName) {
int lastIndex = localName.lastIndexOf(':');
if (lastIndex != -1) {
return localName.substring(lastIndex + 1);
} else {
return localName;
}
}
}
|
3e069f543fdd0e84dd7033b0208fe9a4cc04502f
| 14,802 |
java
|
Java
|
subsamplingscaleimagedrawview/src/main/java/com/github/crazyatom/subsamplingscaleimagedrawview/drawviews/BaseDrawView.java
|
CrazyAtom/SubsamplingScaleImageDrawView
|
ebe94a94b4eac21f350e6580dc794d21031dd264
|
[
"Apache-2.0"
] | null | null | null |
subsamplingscaleimagedrawview/src/main/java/com/github/crazyatom/subsamplingscaleimagedrawview/drawviews/BaseDrawView.java
|
CrazyAtom/SubsamplingScaleImageDrawView
|
ebe94a94b4eac21f350e6580dc794d21031dd264
|
[
"Apache-2.0"
] | null | null | null |
subsamplingscaleimagedrawview/src/main/java/com/github/crazyatom/subsamplingscaleimagedrawview/drawviews/BaseDrawView.java
|
CrazyAtom/SubsamplingScaleImageDrawView
|
ebe94a94b4eac21f350e6580dc794d21031dd264
|
[
"Apache-2.0"
] | null | null | null | 25.608997 | 127 | 0.586813 | 2,821 |
package com.github.crazyatom.subsamplingscaleimagedrawview.drawviews;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.inputmethod.InputMethodManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.github.crazyatom.subsamplingscaleimagedrawview.drawtools.BaseDrawTool;
import com.github.crazyatom.subsamplingscaleimagedrawview.Event.DrawToolControllViewListener;
import com.github.crazyatom.subsamplingscaleimagedrawview.drawtools.BaseEditPinView;
import com.github.crazyatom.subsamplingscaleimagedrawview.util.DrawViewFactory;
import com.github.crazyatom.subsamplingscaleimagedrawview.util.DrawViewSetting;
import com.github.crazyatom.subsamplingscaleimagedrawview.util.Utillity;
import com.github.crazyatom.subsamplingscaleimagedrawview.views.ImageDrawView;
/**
* Created by crazy on 2017-07-11.
*/
public abstract class BaseDrawView {
private DrawViewType type;
private String uniqId;
private String creater;
private long updateTime;
private ArrayList<PointF> pointList = new ArrayList<>();
protected ImageDrawView imageDrawView;
protected Paint paint = new Paint();
protected int thick;
protected String color;
private float phase = 0.0f;
protected boolean showBoundaryBox = false;
protected RectF sRegion = null;
private boolean visibility = true;
private boolean isPreview = false;
private boolean isEditable = false;
private boolean isDashEffect = false;
protected DrawToolControllViewListener drawToolControllViewListener;
public BaseDrawView(DrawViewType type, @NonNull ImageDrawView imageDrawView) {
this.type = type;
this.imageDrawView = imageDrawView;
this.type = type;
this.imageDrawView = imageDrawView;
if (DrawViewFactory.getInstance().getNewDrawViewCallback() != null) {
setUniqId(DrawViewFactory.getInstance().getNewDrawViewCallback().newUUID());
setCreater(DrawViewFactory.getInstance().getNewDrawViewCallback().creater());
} else {
setUniqId(Utillity.getUUID());
setCreater("홍길동");
}
this.updateTime = System.currentTimeMillis();
this.thick = 4;
color = Utillity.getColorString(Color.BLACK);
}
protected void initPosition() {
this.pointList.clear();
}
public DrawViewType getType() {
return this.type;
}
public void setType(DrawViewType type) {
this.type = type;
}
public String getUniqId() {
return this.uniqId;
}
public void setUniqId(String uniqId) {
this.uniqId = uniqId;
}
public PointF getPosition(int index) {
try {
return this.pointList.get(index);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
public void setPoints(ArrayList<PointF> points) {
this.pointList = points;
setSourceRegion();
preCalc();
}
public void setPosition(int index, PointF position) {
try {
this.pointList.set(index, position);
setSourceRegion();
preCalc();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public void addPosition(PointF position) {
this.pointList.add(new PointF(position.x, position.y));
setSourceRegion();
preCalc();
}
public int getPositionSize() {
return this.pointList.size();
}
public int getThick() {
return this.thick;
}
public void setThick(int thick) {
this.thick = thick;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isShowBoundaryBox() {
return this.showBoundaryBox;
}
public void setShowBoundaryBox(boolean show) {
this.showBoundaryBox = show;
}
public RectF getSourceRegion() {
return this.sRegion;
}
protected void setSourceRegion() {
this.sRegion = getRect(false);
}
public String getCreater() {
return creater;
}
public void setCreater(String creater) {
this.creater = creater;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
public void setDrawToolControllViewListener(DrawToolControllViewListener drawToolControllViewListener) {
this.drawToolControllViewListener = drawToolControllViewListener;
}
public boolean isVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
/**
* 좌표 리스트 중 가장 큰 x값
*
* @return
*/
protected float getMaxX() {
return Collections.max(this.pointList, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.x, o2.x);
}
}).x;
}
/**
* 좌표 리스트 중 가장 큰 y값
*
* @return
*/
protected float getMaxY() {
return Collections.max(this.pointList, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.y, o2.y);
}
}).y;
}
/**
* 좌표 리스트 중 가장 작은 x값
*
* @return
*/
protected float getMinX() {
return Collections.min(this.pointList, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.x, o2.x);
}
}).x;
}
/**
* 좌표 리스트 중 가장 작은 y값
*
* @return
*/
protected float getMinY() {
return Collections.min(this.pointList, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.y, o2.y);
}
}).y;
}
/**
* 좌표 리스트 중 가장 큰 x값
*
* @return
*/
protected float getMaxX(ArrayList<PointF> points) {
return Collections.max(points, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.x, o2.x);
}
}).x;
}
/**
* 좌표 리스트 중 가장 큰 y값
*
* @return
*/
protected float getMaxY(ArrayList<PointF> points) {
return Collections.max(points, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.y, o2.y);
}
}).y;
}
/**
* 좌표 리스트 중 가장 작은 x값
*
* @return
*/
protected float getMinX(ArrayList<PointF> points) {
return Collections.min(points, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.x, o2.x);
}
}).x;
}
/**
* 좌표 리스트 중 가장 작은 y값
*
* @return
*/
protected float getMinY(ArrayList<PointF> points) {
return Collections.min(points, new Comparator<PointF>() {
@Override
public int compare(PointF o1, PointF o2) {
return Float.compare(o1.y, o2.y);
}
}).y;
}
public void onDraw(Canvas canvas) {
if (this.showBoundaryBox == true) {
drawBBox(canvas);
}
}
/**
* 외곽 사각 영역 그리기
*
* @param canvas
*/
protected void drawBBox(Canvas canvas) {
if (this.sRegion != null) {
Paint paint = new Paint();
paint.setStrokeWidth(8.0f);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.DKGRAY);
DashPathEffect dashPathEffect = new DashPathEffect(new float[] {10.0f, 5.0f}, phase);
paint.setPathEffect(dashPathEffect);
RectF vRect = new RectF();
this.imageDrawView.sourceToViewRect(this.sRegion, vRect);
canvas.drawRect(vRect, paint);
phase = (phase < 10.0f) ? phase + 1.0f : 0.0f;
// this.postInvalidateOnAnimation();
}
}
/**
* 외곽 사각형
*
* @param toView true이면 화면 좌표, false이면 소스 좌표
* @return 화면 또는 소스 좌표 rect
*/
protected RectF getRect(boolean toView) {
final float left = getMinX(this.pointList);
final float right = getMaxX(this.pointList);
final float top = getMinY(this.pointList);
final float bottom = getMaxY(this.pointList);
final RectF sRect = new RectF(left, top, right, bottom);
if (toView) {
final RectF vRect = new RectF();
return this.imageDrawView.sourceToViewRect(sRect, vRect);
} else {
return sRect;
}
}
/**
* 미리보기 인지 여부
*
* @return true이면 미리보기, false이면 미리보기 아님
*/
public boolean isPreview() {
return this.isPreview;
}
/**
* 미리보기 상태 설정
*
* @param preview
*/
public void setPreview(boolean preview) {
this.isPreview = preview;
}
/**
* 편집 상태 설정
* @return
*/
public boolean isEditable() {
return this.isEditable;
}
public void setEditable(boolean editable) {
this.isEditable = editable;
}
/**
* dash로 표현할지 여부 설정
* @return
*/
public boolean isDashEffect() {
return isDashEffect;
}
public void setDashEffect(boolean dashEffect) {
isDashEffect = dashEffect;
}
/**
* 점선 효과
* @return 점선 효과 적용 여부에 따라 이펙트 반환
*/
@Nullable
protected DashPathEffect getDashPathEffect() {
return isDashEffect ? new DashPathEffect(new float[] {40, 20}, 0.0f) : null;
}
/**
* 좌표정보 재설정
*
* @param points
*/
public void update(ArrayList<PointF> points) {
setPoints(points);
invalidate();
}
/**
* 화면 좌표를 소스 좌표로 변환
* @param vx
* @param vy
* @return
*/
protected final PointF viewToSourceCoord(float vx, float vy) {
if (this.imageDrawView == null) {
return null;
}
return this.imageDrawView.viewToSourceCoord(vx, vy);
}
/**
* 소스 좌표를 화면 좌표로 변환
* @param sx
* @param sy
* @return
*/
protected final PointF sourceToViewCoord(float sx, float sy) {
if (this.imageDrawView == null) {
return null;
}
return this.imageDrawView.sourceToViewCoord(sx, sy);
}
/**
* bondary box 정보를 이용하여 drawView 갱신
*
* @param newBbox
*/
public void update(RectF newBbox) {
final RectF originalBbox = getSourceRegion();
if (newBbox != null && originalBbox != null) {
final float scaleX = newBbox.width() / originalBbox.width();
final float scaleY = newBbox.height() / originalBbox.height();
ArrayList<PointF> points = new ArrayList<>();
for (int updateIdx = 0; updateIdx < getPositionSize(); ++updateIdx) {
PointF currPoint = getPosition(updateIdx);
PointF newPoint = new PointF();
newPoint.x = (currPoint.x - originalBbox.left) * scaleX + newBbox.left;
newPoint.y = (currPoint.y - originalBbox.top) * scaleY + newBbox.top;
points.add(newPoint);
}
update(points);
}
}
/**
* drawView 정보 팝업
* @param context
*/
public abstract void showContentsBox(Context context);
/**
* drawView 이름
*
* @return
*/
public abstract String getName(boolean isSimple);
/**
* 필요한 정보 미리 계산
*/
protected abstract void preCalc();
/**
* 편집 view
* @return
*/
public abstract BaseEditPinView getEditPinView();
/**
* 편집 flag 설정이 유효한지 여부
* @return
*/
public abstract boolean isValidEditedFlag();
/**
* 좌표 x, y가 annotation내에 존재 하는지 체크
* @param x
* @param y
* @return true 이면 drawView 내에 존재, false 이면 drawView 내에 존재 하지 않음
*/
public boolean isContains(float x, float y) {
if(this.sRegion == null) {
return false;
} else {
return sRegion.contains(x, y);
}
}
/**
* 소프트키보드 show/hide
* @param show boolean
*/
protected void toggleSoftInput(final boolean show) {
InputMethodManager manager = (InputMethodManager) getContext().getSystemService(getContext().INPUT_METHOD_SERVICE);
if (show == true) {
manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
} else {
manager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
/**
* tool을 연속으로 수행할지 여부 확인하여 연속 수행이 아니면 tool 해제
*/
public void checkContinueTool() {
if (DrawViewSetting.getInstance().isContinuous() == false) {
imageDrawView.changeTool(BaseDrawTool.DrawToolType.NONE);
if (drawToolControllViewListener != null) {
drawToolControllViewListener.changeDefaultDrawTool();
}
}
}
/**
* paint 기본 설정
*/
protected void loadPaint() {
paint.setColor(Color.parseColor(color));
paint.setStrokeWidth(thick);
paint.setAntiAlias(true);
paint.setPathEffect(getDashPathEffect());
}
protected Resources getResources() {
return imageDrawView.getResources();
}
protected Context getContext() {
return imageDrawView.getContext();
}
/**
* view 갱신
*/
public void invalidate() {
RectF invalidArea = new RectF();
imageDrawView.sourceToViewRect(getSourceRegion(), invalidArea);
imageDrawView.invalidate((int)invalidArea.left, (int)invalidArea.top, (int)invalidArea.right, (int)invalidArea.bottom);
}
/**
* drawView type 정의
*/
public static enum DrawViewType {
PHOTO,
TEXT,
DIMENSION,
DIMENSION_REF,
CLOUD,
INK,
LINE,
RECTANGLE,
ELLIPSE;
private DrawViewType() {
}
}
}
|
3e069fe4b276a1b71b21563e7065465a316aff51
| 3,173 |
java
|
Java
|
MEC012/mec012-server/src/main/java/io/swagger/model/RabEstNotificationErabQosParameters.java
|
nextworks-it/MEC-applications
|
33be0cf7027b8778fcb18fec3a93f71687679dd7
|
[
"Apache-2.0"
] | 1 |
2021-05-11T13:05:51.000Z
|
2021-05-11T13:05:51.000Z
|
MEC012/mec012-server/src/main/java/io/swagger/model/RabEstNotificationErabQosParameters.java
|
nextworks-it/MEC-applications
|
33be0cf7027b8778fcb18fec3a93f71687679dd7
|
[
"Apache-2.0"
] | null | null | null |
MEC012/mec012-server/src/main/java/io/swagger/model/RabEstNotificationErabQosParameters.java
|
nextworks-it/MEC-applications
|
33be0cf7027b8778fcb18fec3a93f71687679dd7
|
[
"Apache-2.0"
] | null | null | null | 29.110092 | 134 | 0.722345 | 2,822 |
package io.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.model.RabEstNotificationErabQosParametersQosInformation;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* QoS parameters for the E-RAB as defined below.
*/
@ApiModel(description = "QoS parameters for the E-RAB as defined below.")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-12-17T10:14:37.794Z[Etc/UTC]")
public class RabEstNotificationErabQosParameters {
@JsonProperty("qci")
private Integer qci = null;
@JsonProperty("qosInformation")
private RabEstNotificationErabQosParametersQosInformation qosInformation = null;
public RabEstNotificationErabQosParameters qci(Integer qci) {
this.qci = qci;
return this;
}
/**
* QoS Class Identifier as defined in ETSI TS 123 401 [i.4].
* @return qci
**/
@ApiModelProperty(required = true, value = "QoS Class Identifier as defined in ETSI TS 123 401 [i.4].")
@NotNull
public Integer getQci() {
return qci;
}
public void setQci(Integer qci) {
this.qci = qci;
}
public RabEstNotificationErabQosParameters qosInformation(RabEstNotificationErabQosParametersQosInformation qosInformation) {
this.qosInformation = qosInformation;
return this;
}
/**
* Get qosInformation
* @return qosInformation
**/
@ApiModelProperty(value = "")
@Valid
public RabEstNotificationErabQosParametersQosInformation getQosInformation() {
return qosInformation;
}
public void setQosInformation(RabEstNotificationErabQosParametersQosInformation qosInformation) {
this.qosInformation = qosInformation;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RabEstNotificationErabQosParameters rabEstNotificationErabQosParameters = (RabEstNotificationErabQosParameters) o;
return Objects.equals(this.qci, rabEstNotificationErabQosParameters.qci) &&
Objects.equals(this.qosInformation, rabEstNotificationErabQosParameters.qosInformation);
}
@Override
public int hashCode() {
return Objects.hash(qci, qosInformation);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class RabEstNotificationErabQosParameters {\n");
sb.append(" qci: ").append(toIndentedString(qci)).append("\n");
sb.append(" qosInformation: ").append(toIndentedString(qosInformation)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e06a00b9f53026c3acd881c4d4c78d099075ed8
| 1,008 |
java
|
Java
|
app/src/test/java/com/example/crowdtest/UserProfileTest.java
|
Parhamglst/cmput301-project
|
bf66b3f58646ff8aabe23d2a928e9738aab67020
|
[
"Apache-2.0"
] | 1 |
2021-12-09T19:08:14.000Z
|
2021-12-09T19:08:14.000Z
|
app/src/test/java/com/example/crowdtest/UserProfileTest.java
|
Parhamglst/cmput301-project
|
bf66b3f58646ff8aabe23d2a928e9738aab67020
|
[
"Apache-2.0"
] | 59 |
2021-03-03T01:55:18.000Z
|
2021-04-13T03:48:04.000Z
|
app/src/test/java/com/example/crowdtest/UserProfileTest.java
|
CMPUT301W21T26/cmput301-project
|
bf66b3f58646ff8aabe23d2a928e9738aab67020
|
[
"Apache-2.0"
] | null | null | null | 30.484848 | 84 | 0.703777 | 2,823 |
package com.example.crowdtest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* UserProfileTest class for unit testing UserProfile class
*/
public class UserProfileTest {
private MockClassCreator mockClassCreator = new MockClassCreator();
/**
* Function to test getter and setter methods for common user profile attributes
*/
@Test
void testAttributes() {
// Create a mock user profile
UserProfile userProfile = mockClassCreator.mockUserProfile();
// Set user profile attributes
userProfile.setUsername("sample_user");
userProfile.setEmail("[email protected]");
userProfile.setPhoneNumber("sample_number");
// Check that defined attributes have been successfully set
assertEquals("sample_user", userProfile.getUsername());
assertEquals("[email protected]", userProfile.getEmail());
assertEquals("sample_number", userProfile.getPhoneNumber());
}
}
|
3e06a10b143b0823c5c92f16917af7d2fc96d5cb
| 2,065 |
java
|
Java
|
CapellaTimeEffort/src/com/calsoft/report/model/EventConst.java
|
calsoftcapella/CapellaTimeEffort
|
f25e086e4b523ade4b11fcee700dba92ef342bb4
|
[
"Apache-2.0"
] | null | null | null |
CapellaTimeEffort/src/com/calsoft/report/model/EventConst.java
|
calsoftcapella/CapellaTimeEffort
|
f25e086e4b523ade4b11fcee700dba92ef342bb4
|
[
"Apache-2.0"
] | null | null | null |
CapellaTimeEffort/src/com/calsoft/report/model/EventConst.java
|
calsoftcapella/CapellaTimeEffort
|
f25e086e4b523ade4b11fcee700dba92ef342bb4
|
[
"Apache-2.0"
] | null | null | null | 22.445652 | 51 | 0.759322 | 2,824 |
package com.calsoft.report.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.calsoft.user.model.User;
@Entity
@Table(name="evnt_const")
public class EventConst {
@Id
@GeneratedValue()
@Column(name="const_id")
private int const_id;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="event_id")
private UserEvent userEvent;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="user_id")
private User user;
@Column(name="ondate_const")
private String ondate_const;
@Column(name="detail_const")
private String detail_const;
@Column(name="owner_const")
private String owner_const;
@Column(name="remark_const")
private String remark_const;
@Column(name="eta_const")
private String eta_const;
public int getConst_id() {
return const_id;
}
public void setConst_id(int const_id) {
this.const_id = const_id;
}
public UserEvent getUserEvent() {
return userEvent;
}
public void setUserEvent(UserEvent userEvent) {
this.userEvent = userEvent;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getOndate_const() {
return ondate_const;
}
public void setOndate_const(String ondate_const) {
this.ondate_const = ondate_const;
}
public String getDetail_const() {
return detail_const;
}
public void setDetail_const(String detail_const) {
this.detail_const = detail_const;
}
public String getOwner_const() {
return owner_const;
}
public void setOwner_const(String owner_const) {
this.owner_const = owner_const;
}
public String getRemark_const() {
return remark_const;
}
public void setRemark_const(String remark_const) {
this.remark_const = remark_const;
}
public String getEta_const() {
return eta_const;
}
public void setEta_const(String eta_const) {
this.eta_const = eta_const;
}
}
|
3e06a13d1a98f3776fac2038fccf66d79b764a99
| 1,629 |
java
|
Java
|
Facebook_Database/src/facebook/database/model/Post.java
|
widowmaker110/CSC480_Facebook_Database
|
4472d814c9e8b66dd6c274d79300eae470b18c6e
|
[
"Unlicense",
"MIT"
] | null | null | null |
Facebook_Database/src/facebook/database/model/Post.java
|
widowmaker110/CSC480_Facebook_Database
|
4472d814c9e8b66dd6c274d79300eae470b18c6e
|
[
"Unlicense",
"MIT"
] | null | null | null |
Facebook_Database/src/facebook/database/model/Post.java
|
widowmaker110/CSC480_Facebook_Database
|
4472d814c9e8b66dd6c274d79300eae470b18c6e
|
[
"Unlicense",
"MIT"
] | null | null | null | 18.303371 | 122 | 0.656231 | 2,825 |
package facebook.database.model;
import java.util.Date;
import facebook.database.dao.PostDAO;;;
public class Post
{
@SuppressWarnings("unused")
private PostDAO dao;
private int postId;
private int userId;
private Date postDate;
private String postText;
private String postImage; // an url to the image
private String postVideo; // an url to the video
/**
*
* @param dao
* @param postId
* @param postDate
* @param postText
* @param postImage
* @param postVideo
*/
public Post(/*PostDAO dao,*/ int postId, int userId, Date postDate, String postText, String postImage, String postVideo)
{
//this.dao = dao;
this.setUserId(userId);
this.postId = postId;
this.postDate = postDate;
this.postText = postText;
this.postImage = postImage;
this.postVideo = postVideo;
}
public int getPostId()
{
return postId;
}
public Date getPostDate()
{
return postDate;
}
public String getPostText()
{
return postText;
}
public void changePostText(String newPostText)
{
postText = newPostText;
//dao.changePostText(...);
}
public String getPostImage()
{
return postImage;
}
public void changePostImage(String newPostImage)
{
postImage = newPostImage;
//dao.changePostImage(...);
}
public String getPostVideo()
{
return postVideo;
}
public void changePostVideo(String newPostVideo)
{
postImage = newPostVideo;
//dao.changePostVideo(...);
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
|
3e06a1cb799c06dc7691bf8badb390fd97d7f4c9
| 12,174 |
java
|
Java
|
src/main/java/org/unitedinternet/cosmo/dav/impl/DavCollectionBase.java
|
ksokol/carldav
|
6bb288daf60fac815a0196768dcb4eecd7ffc671
|
[
"Apache-2.0"
] | 30 |
2017-01-13T10:59:08.000Z
|
2021-12-22T21:28:20.000Z
|
src/main/java/org/unitedinternet/cosmo/dav/impl/DavCollectionBase.java
|
ksokol/carldav
|
6bb288daf60fac815a0196768dcb4eecd7ffc671
|
[
"Apache-2.0"
] | 5 |
2015-12-13T10:23:53.000Z
|
2021-04-26T20:55:28.000Z
|
src/main/java/org/unitedinternet/cosmo/dav/impl/DavCollectionBase.java
|
ksokol/carldav
|
6bb288daf60fac815a0196768dcb4eecd7ffc671
|
[
"Apache-2.0"
] | 9 |
2017-03-09T12:42:51.000Z
|
2021-07-14T14:30:49.000Z
| 36.890909 | 138 | 0.644406 | 2,826 |
package org.unitedinternet.cosmo.dav.impl;
import carldav.entity.CollectionItem;
import carldav.entity.Item;
import carldav.jackrabbit.webdav.io.DavInputContext;
import carldav.jackrabbit.webdav.property.DavPropertySet;
import carldav.jackrabbit.webdav.version.report.ReportType;
import org.apache.commons.lang.StringEscapeUtils;
import org.unitedinternet.cosmo.calendar.query.CalendarQueryProcessor;
import org.unitedinternet.cosmo.dav.CosmoDavException;
import org.unitedinternet.cosmo.dav.DavCollection;
import org.unitedinternet.cosmo.dav.DavResourceFactory;
import org.unitedinternet.cosmo.dav.DavResourceLocator;
import org.unitedinternet.cosmo.dav.ETagUtil;
import org.unitedinternet.cosmo.dav.ForbiddenException;
import org.unitedinternet.cosmo.dav.WebDavResource;
import org.unitedinternet.cosmo.dav.property.DisplayName;
import org.unitedinternet.cosmo.dav.property.Etag;
import org.unitedinternet.cosmo.dav.property.IsCollection;
import org.unitedinternet.cosmo.dav.property.LastModified;
import org.unitedinternet.cosmo.dav.property.ResourceType;
import org.unitedinternet.cosmo.dav.property.WebDavProperty;
import org.unitedinternet.cosmo.service.ContentService;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static carldav.CarldavConstants.TEXT_HTML_VALUE;
import static carldav.CarldavConstants.caldav;
import static org.springframework.http.HttpHeaders.ETAG;
import static org.springframework.http.HttpHeaders.LAST_MODIFIED;
public class DavCollectionBase extends DavResourceBase implements WebDavResource, DavCollection {
protected final Set<ReportType> reportTypes = new HashSet<>();
private List<WebDavResource> members;
private CollectionItem item;
private DavCollection parent;
public DavCollectionBase(CollectionItem collection, DavResourceLocator locator, DavResourceFactory factory) throws CosmoDavException {
super(locator, factory);
this.item = collection;
members = new ArrayList<>();
}
public DavCollectionBase(DavResourceLocator locator, DavResourceFactory factory) throws CosmoDavException {
this(new CollectionItem(), locator, factory);
}
public CollectionItem getItem() {
return item;
}
@Override
public boolean exists() {
return item.getId() != null;
}
public boolean isCollection() {
return true;
}
@Override
public String getDisplayName() {
return item.getDisplayName();
}
public long getModificationTime() {
return item.getModifiedDate() == null ? 0 : item.getModifiedDate().getTime();
}
@Override
public List<WebDavResource> getMembers() {
final List<CollectionItem> collections = getResourceFactory().getCollectionRepository().findByParentId(item.getId());
final List<Item> items = getResourceFactory().getItemRepository().findByCollectionId(item.getId());
members.addAll(collections.stream().map(this::collectionToResource).collect(Collectors.toList()));
members.addAll(items.stream().map(this::memberToResource).collect(Collectors.toList()));
return Collections.unmodifiableList(members);
}
@Override
public String getName() {
return item.getName();
}
public List<WebDavResource> getCollectionMembers() {
for (CollectionItem memberItem : item.getCollections()) {
WebDavResource resource = collectionToResource(memberItem);
members.add(resource);
}
return Collections.unmodifiableList(members);
}
public void removeItem(WebDavResource member) {
Item item = ((DavItemResourceBase) member).getItem();
getContentService().removeItemFromCollection(item, this.item);
members.remove(member);
}
public void removeCollection(DavCollectionBase member) {
CollectionItem hibItem = member.getItem();
getContentService().removeCollection(hibItem);
members.remove(member);
}
@Override
public DavCollection getParent() throws CosmoDavException {
if (parent == null) {
DavResourceLocator parentLocator = getResourceLocator()
.getParentLocator();
try {
parent = (DavCollection) getResourceFactory().resolve(
parentLocator);
} catch (ClassCastException e) {
throw new ForbiddenException("Resource "
+ parentLocator.getPath() + " is not a collection");
}
if (parent == null)
parent = new DavCollectionBase(parentLocator, getResourceFactory());
}
return parent;
}
@Override
public String getETag() {
return ETagUtil.createETagEscaped(getItem().getId(), getItem().getModifiedDate());
}
public void addContent(WebDavResource content, DavInputContext context) throws CosmoDavException {
DavItemResourceBase base = (DavItemResourceBase) content;
base.populateItem(context);
saveContent(base);
members.add(base);
}
public WebDavResource findMember(String href) throws CosmoDavException {
return memberToResource(href);
}
public boolean isHomeCollection() {
return false;
}
// our methods
protected Set<QName> getResourceTypes() {
Set<QName> rt = new LinkedHashSet<>();
rt.add(caldav(XML_COLLECTION));
return rt;
}
public Set<ReportType> getReportTypes() {
return reportTypes;
}
protected void loadLiveProperties(DavPropertySet properties) {
properties.add(new LastModified(item.getModifiedDate()));
properties.add(new Etag(getETag()));
properties.add(new DisplayName(getDisplayName()));
properties.add(new ResourceType(getResourceTypes()));
properties.add(new IsCollection(isCollection()));
}
/**
* Saves the given content resource to storage.
*/
protected void saveContent(DavItemResourceBase member) throws CosmoDavException {
CollectionItem collection = item;
Item content = member.getItem();
if (content.getId() != null) {
content = getContentService().updateContent(content);
} else {
content = getContentService().createContent(collection, content);
}
member.setItem(content);
}
protected WebDavResource memberToResource(Item item) throws CosmoDavException {
String path;
try {
path = getResourcePath() + "/" + URLEncoder.encode(item.getName(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new CosmoDavException(e);
}
DavResourceLocator locator = getResourceLocator().getFactory()
.createResourceLocatorByPath(getResourceLocator().getContext(),
path);
return getResourceFactory().createResource(locator, item);
}
protected WebDavResource collectionToResource(CollectionItem hibItem) {
String path;
try {
path = getResourcePath() + "/" + URLEncoder.encode(hibItem.getName(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new CosmoDavException(e);
}
DavResourceLocator locator = getResourceLocator().getFactory()
.createResourceLocatorByPath(getResourceLocator().getContext(),
path);
return getResourceFactory().createCollectionResource(locator, hibItem);
}
protected WebDavResource memberToResource(String uri) throws CosmoDavException {
DavResourceLocator locator = getResourceLocator().getFactory()
.createResourceLocatorByUri(getResourceLocator().getContext(),
uri);
return getResourceFactory().resolve(locator);
}
public void writeHead(final HttpServletResponse response) throws IOException {
response.setContentType(TEXT_HTML_VALUE);
if (getModificationTime() >= 0) {
response.addDateHeader(LAST_MODIFIED, getModificationTime());
}
if (getETag() != null) {
response.setHeader(ETAG, getETag());
}
}
public void writeBody(final HttpServletResponse response) throws IOException {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
try {
writer.write("<html>\n<head><title>");
String colName = StringEscapeUtils.escapeHtml(getDisplayName());
writer.write(colName);
writer.write("</title></head>\n");
writer.write("<body>\n");
writer.write("<h1>");
writer.write(colName);
writer.write("</h1>\n");
WebDavResource parent = getParent();
writer.write("Parent: <a href=\"");
writer.write(parent.getResourceLocator().getHref(true));
writer.write("\">");
writer.write(StringEscapeUtils.escapeHtml(parent.getDisplayName()));
writer.write("</a></li>\n");
writer.write("<h2>Members</h2>\n");
writer.write("<ul>\n");
for (final WebDavResource child : getMembers()) {
writer.write("<li><a href=\"");
writer.write(child.getResourceLocator().getHref(child.isCollection()));
writer.write("\">");
writer.write(StringEscapeUtils.escapeHtml(child.getDisplayName()));
writer.write("</a></li>\n");
}
writer.write("</ul>\n");
writer.write("<h2>Properties</h2>\n");
writer.write("<dl>\n");
for (final Map.Entry<String, WebDavProperty> i : getWebDavProperties().entrySet()) {
WebDavProperty prop = i.getValue();
String text = prop.getValueText();
if (text == null) {
text = "-- no value --";
}
writer.write("<dt>");
writer.write(StringEscapeUtils.escapeHtml(prop.getName().toString()));
writer.write("</dt><dd>");
writer.write(StringEscapeUtils.escapeHtml(text));
writer.write("</dd>\n");
}
writer.write("</dl>\n");
writer.write("<p>\n");
DavResourceLocator principalLocator = getResourceLocator()
.getFactory().createPrincipalLocator(
getResourceLocator().getContext(), getUsername());
writer.write("<a href=\"");
writer.write(principalLocator.getHref(false));
writer.write("\">");
writer.write("Principal resource");
writer.write("</a><br>\n");
writer.write("<p>\n");
if (!isHomeCollection()) {
DavResourceLocator homeLocator = getResourceLocator()
.getFactory().createHomeLocator(
getResourceLocator().getContext(), getUsername());
writer.write("<a href=\"");
writer.write(homeLocator.getHref(true));
writer.write("\">");
writer.write("Home collection");
writer.write("</a><br>\n");
}
writer.write("</body>");
writer.write("</html>\n");
}finally{
writer.close();
}
}
protected ContentService getContentService() {
return getResourceFactory().getContentService();
}
protected CalendarQueryProcessor getCalendarQueryProcesor() {
return getResourceFactory().getCalendarQueryProcessor();
}
}
|
3e06a2458910b9d74a89f70a76a50ddc7d33ffcb
| 2,867 |
java
|
Java
|
src/main/java/edu/indiana/d2i/htrc/access/policy/PolicyCheckerRegistryImpl.java
|
htrc/HTRC-DataAPI-old
|
682b88100347943d8f6dd50b5ac9aadd09aa7f0d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/edu/indiana/d2i/htrc/access/policy/PolicyCheckerRegistryImpl.java
|
htrc/HTRC-DataAPI-old
|
682b88100347943d8f6dd50b5ac9aadd09aa7f0d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/edu/indiana/d2i/htrc/access/policy/PolicyCheckerRegistryImpl.java
|
htrc/HTRC-DataAPI-old
|
682b88100347943d8f6dd50b5ac9aadd09aa7f0d
|
[
"Apache-2.0"
] | null | null | null | 30.5 | 97 | 0.653994 | 2,827 |
/*
#
# Copyright 2013 The Trustees of Indiana University
#
# 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 expressed or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# -----------------------------------------------------------------
#
# Project: data-api
# File: PolicyCheckerRegistryImpl.java
# Description: This singleton class is an implementation of the PolicyCheckerRegistry interface
#
# -----------------------------------------------------------------
#
*/
/**
*
*/
package edu.indiana.d2i.htrc.access.policy;
import java.util.HashMap;
import java.util.Map;
import edu.indiana.d2i.htrc.access.PolicyChecker;
import edu.indiana.d2i.htrc.access.PolicyCheckerRegistry;
/**
* This singleton class is an implementation of the PolicyCheckerRegistry interface
*
* @author Yiming Sun
*
*/
public class PolicyCheckerRegistryImpl implements PolicyCheckerRegistry {
protected final Map<String, PolicyChecker> checkerMap;
protected static final NullPolicyChecker NULL_POLICY_CHECKER = new NullPolicyChecker();
protected static PolicyCheckerRegistryImpl instance = null;
/**
* Constructor. Used internally for singleton
*/
protected PolicyCheckerRegistryImpl() {
this.checkerMap = new HashMap<String, PolicyChecker>();
}
/**
* Method to get the singleton instance of the PolicyCheckerRegistryImpl object
* @return
*/
public static synchronized PolicyCheckerRegistryImpl getInstance() {
if (instance == null) {
instance = new PolicyCheckerRegistryImpl();
}
return instance;
}
/**
* @see edu.indiana.d2i.htrc.access.PolicyCheckerRegistry#getPolicyChecker(java.lang.String)
*/
@Override
public PolicyChecker getPolicyChecker(String key) {
PolicyChecker policyChecker = checkerMap.get(key);
if (policyChecker == null) {
policyChecker = NULL_POLICY_CHECKER;
}
return policyChecker;
}
/**
* Method to register PolicyChecker objects with this registry
* @param key a unique key to identify each PolicyChecker object
* @param policyChecker a PolicyChecker object
*/
public void registerPolicyChecker(String key, PolicyChecker policyChecker) {
this.checkerMap.put(key, policyChecker);
}
}
|
3e06a26e07e07a7454efa4b675a0724c60aeac71
| 346 |
java
|
Java
|
app/src/main/java/com/coolweather/yc/gson/Now.java
|
JonSnow6/coolweather
|
863fe3b04d12c2ba7d306263d3943a373235bb6f
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/coolweather/yc/gson/Now.java
|
JonSnow6/coolweather
|
863fe3b04d12c2ba7d306263d3943a373235bb6f
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/coolweather/yc/gson/Now.java
|
JonSnow6/coolweather
|
863fe3b04d12c2ba7d306263d3943a373235bb6f
|
[
"Apache-2.0"
] | null | null | null | 15.727273 | 50 | 0.650289 | 2,828 |
package com.coolweather.yc.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by LZC on 2018/2/1.
*/
public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More{
@SerializedName("txt")
public String info;
}
}
|
3e06a2716fdd62342c5058be76601cfd87bfe099
| 22,163 |
java
|
Java
|
trunk/src/java/org/quartz/core/QuartzSchedulerThread.java
|
eric-hsu/opensymphony-quartz-backup
|
cf83b3f762260cfa7dd95f269c17b8ea50684c87
|
[
"Apache-2.0"
] | null | null | null |
trunk/src/java/org/quartz/core/QuartzSchedulerThread.java
|
eric-hsu/opensymphony-quartz-backup
|
cf83b3f762260cfa7dd95f269c17b8ea50684c87
|
[
"Apache-2.0"
] | null | null | null |
trunk/src/java/org/quartz/core/QuartzSchedulerThread.java
|
eric-hsu/opensymphony-quartz-backup
|
cf83b3f762260cfa7dd95f269c17b8ea50684c87
|
[
"Apache-2.0"
] | 1 |
2020-10-26T11:35:09.000Z
|
2020-10-26T11:35:09.000Z
| 39.576786 | 120 | 0.483012 | 2,829 |
/*
* Copyright 2001-2009 James House
*
* 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.
*
*/
/*
* Previously Copyright (c) 2001-2004 James House
*/
package org.quartz.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobPersistenceException;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.spi.TriggerFiredBundle;
import java.util.Random;
/**
* <p>
* The thread responsible for performing the work of firing <code>{@link Trigger}</code>
* s that are registered with the <code>{@link QuartzScheduler}</code>.
* </p>
*
* @see QuartzScheduler
* @see org.quartz.Job
* @see Trigger
*
* @author James House
*/
public class QuartzSchedulerThread extends Thread {
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Data members.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
private QuartzScheduler qs;
private QuartzSchedulerResources qsRsrcs;
private Object sigLock = new Object();
private boolean signaled;
private long signaledNextFireTime;
private boolean paused;
private boolean halted;
private SchedulingContext ctxt = null;
private Random random = new Random(System.currentTimeMillis());
// When the scheduler finds there is no current trigger to fire, how long
// it should wait until checking again...
private static long DEFAULT_IDLE_WAIT_TIME = 30L * 1000L;
private long idleWaitTime = DEFAULT_IDLE_WAIT_TIME;
private int idleWaitVariablness = 7 * 1000;
private long dbFailureRetryInterval = 15L * 1000L;
private final Log log = LogFactory.getLog(getClass());
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Constructors.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* <p>
* Construct a new <code>QuartzSchedulerThread</code> for the given
* <code>QuartzScheduler</code> as a non-daemon <code>Thread</code>
* with normal priority.
* </p>
*/
QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs,
SchedulingContext ctxt) {
this(qs, qsRsrcs, ctxt, qsRsrcs.getMakeSchedulerThreadDaemon(), Thread.NORM_PRIORITY);
}
/**
* <p>
* Construct a new <code>QuartzSchedulerThread</code> for the given
* <code>QuartzScheduler</code> as a <code>Thread</code> with the given
* attributes.
* </p>
*/
QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs,
SchedulingContext ctxt, boolean setDaemon, int threadPrio) {
super(qs.getSchedulerThreadGroup(), qsRsrcs.getThreadName());
this.qs = qs;
this.qsRsrcs = qsRsrcs;
this.ctxt = ctxt;
this.setDaemon(setDaemon);
if(qsRsrcs.isThreadsInheritInitializersClassLoadContext()) {
log.info("QuartzSchedulerThread Inheriting ContextClassLoader of thread: " + Thread.currentThread().getName());
this.setContextClassLoader(Thread.currentThread().getContextClassLoader());
}
this.setPriority(threadPrio);
// start the underlying thread, but put this object into the 'paused'
// state
// so processing doesn't start yet...
paused = true;
halted = false;
this.start();
}
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Interface.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
void setIdleWaitTime(long waitTime) {
idleWaitTime = waitTime;
idleWaitVariablness = (int) (waitTime * 0.2);
}
private long getDbFailureRetryInterval() {
return dbFailureRetryInterval;
}
public void setDbFailureRetryInterval(long dbFailureRetryInterval) {
this.dbFailureRetryInterval = dbFailureRetryInterval;
}
private long getRandomizedIdleWaitTime() {
return idleWaitTime - random.nextInt(idleWaitVariablness);
}
/**
* <p>
* Signals the main processing loop to pause at the next possible point.
* </p>
*/
void togglePause(boolean pause) {
synchronized (sigLock) {
paused = pause;
if (paused) {
signalSchedulingChange(0);
} else {
sigLock.notifyAll();
}
}
}
/**
* <p>
* Signals the main processing loop to pause at the next possible point.
* </p>
*/
void halt() {
synchronized (sigLock) {
halted = true;
if (paused) {
sigLock.notifyAll();
} else {
signalSchedulingChange(0);
}
}
}
boolean isPaused() {
return paused;
}
/**
* <p>
* Signals the main processing loop that a change in scheduling has been
* made - in order to interrupt any sleeping that may be occuring while
* waiting for the fire time to arrive.
* </p>
*
* @param newNextTime the time (in millis) when the newly scheduled trigger
* will fire. If this method is being called do to some other even (rather
* than scheduling a trigger), the caller should pass zero (0).
*/
public void signalSchedulingChange(long candidateNewNextFireTime) {
synchronized(sigLock) {
signaled = true;
signaledNextFireTime = candidateNewNextFireTime;
sigLock.notifyAll();
}
}
public void clearSignaledSchedulingChange() {
synchronized(sigLock) {
signaled = false;
signaledNextFireTime = 0;
}
}
public boolean isScheduleChanged() {
synchronized(sigLock) {
return signaled;
}
}
public long getSignaledNextFireTime() {
synchronized(sigLock) {
return signaledNextFireTime;
}
}
/**
* <p>
* The main processing loop of the <code>QuartzSchedulerThread</code>.
* </p>
*/
public void run() {
boolean lastAcquireFailed = false;
while (!halted) {
try {
// check if we're supposed to pause...
synchronized (sigLock) {
while (paused && !halted) {
try {
// wait until togglePause(false) is called...
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
if (halted) {
break;
}
}
int availTreadCount = qsRsrcs.getThreadPool().blockForAvailableThreads();
if(availTreadCount > 0) { // will always be true, due to semantics of blockForAvailableThreads...
Trigger trigger = null;
long now = System.currentTimeMillis();
clearSignaledSchedulingChange();
try {
trigger = qsRsrcs.getJobStore().acquireNextTrigger(
ctxt, now + idleWaitTime);
lastAcquireFailed = false;
} catch (JobPersistenceException jpe) {
if(!lastAcquireFailed) {
qs.notifySchedulerListenersError(
"An error occured while scanning for the next trigger to fire.",
jpe);
}
lastAcquireFailed = true;
} catch (RuntimeException e) {
if(!lastAcquireFailed) {
getLog().error("quartzSchedulerThreadLoop: RuntimeException "
+e.getMessage(), e);
}
lastAcquireFailed = true;
}
if (trigger != null) {
now = System.currentTimeMillis();
long triggerTime = trigger.getNextFireTime().getTime();
long timeUntilTrigger = triggerTime - now;
while(timeUntilTrigger > 0) {
synchronized(sigLock) {
try {
// we chould have blocked a long while
// on 'synchronize', so we must recompute
now = System.currentTimeMillis();
timeUntilTrigger = triggerTime - now;
sigLock.wait(timeUntilTrigger);
} catch (InterruptedException ignore) {
}
}
if (isScheduleChanged()) {
if(isCandidateNewTimeEarlierWithinReason(triggerTime)) {
// above call does a clearSignaledSchedulingChange()
try {
qsRsrcs.getJobStore().releaseAcquiredTrigger(
ctxt, trigger);
} catch (JobPersistenceException jpe) {
qs.notifySchedulerListenersError(
"An error occured while releasing trigger '"
+ trigger.getFullName() + "'",
jpe);
// db connection must have failed... keep
// retrying until it's up...
releaseTriggerRetryLoop(trigger);
} catch (RuntimeException e) {
getLog().error(
"releaseTriggerRetryLoop: RuntimeException "
+e.getMessage(), e);
// db connection must have failed... keep
// retrying until it's up...
releaseTriggerRetryLoop(trigger);
}
trigger = null;
break;
}
}
now = System.currentTimeMillis();
timeUntilTrigger = triggerTime - now;
}
if(trigger == null)
continue;
// set trigger to 'executing'
TriggerFiredBundle bndle = null;
boolean goAhead = true;
synchronized(sigLock) {
goAhead = !halted;
}
if(goAhead) {
try {
bndle = qsRsrcs.getJobStore().triggerFired(ctxt,
trigger);
} catch (SchedulerException se) {
qs.notifySchedulerListenersError(
"An error occured while firing trigger '"
+ trigger.getFullName() + "'", se);
} catch (RuntimeException e) {
getLog().error(
"RuntimeException while firing trigger " +
trigger.getFullName(), e);
// db connection must have failed... keep
// retrying until it's up...
releaseTriggerRetryLoop(trigger);
}
}
// it's possible to get 'null' if the trigger was paused,
// blocked, or other similar occurrences that prevent it being
// fired at this time... or if the scheduler was shutdown (halted)
if (bndle == null) {
try {
qsRsrcs.getJobStore().releaseAcquiredTrigger(ctxt,
trigger);
} catch (SchedulerException se) {
qs.notifySchedulerListenersError(
"An error occured while releasing trigger '"
+ trigger.getFullName() + "'", se);
// db connection must have failed... keep retrying
// until it's up...
releaseTriggerRetryLoop(trigger);
}
continue;
}
// TODO: improvements:
//
// 2- make sure we can get a job runshell before firing trigger, or
// don't let that throw an exception (right now it never does,
// but the signature says it can).
// 3- acquire more triggers at a time (based on num threads available?)
JobRunShell shell = null;
try {
shell = qsRsrcs.getJobRunShellFactory().borrowJobRunShell();
shell.initialize(qs, bndle);
} catch (SchedulerException se) {
try {
qsRsrcs.getJobStore().triggeredJobComplete(ctxt,
trigger, bndle.getJobDetail(), Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR);
} catch (SchedulerException se2) {
qs.notifySchedulerListenersError(
"An error occured while placing job's triggers in error state '"
+ trigger.getFullName() + "'", se2);
// db connection must have failed... keep retrying
// until it's up...
errorTriggerRetryLoop(bndle);
}
continue;
}
if (qsRsrcs.getThreadPool().runInThread(shell) == false) {
try {
// this case should never happen, as it is indicative of the
// scheduler being shutdown or a bug in the thread pool or
// a thread pool being used concurrently - which the docs
// say not to do...
getLog().error("ThreadPool.runInThread() return false!");
qsRsrcs.getJobStore().triggeredJobComplete(ctxt,
trigger, bndle.getJobDetail(), Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR);
} catch (SchedulerException se2) {
qs.notifySchedulerListenersError(
"An error occured while placing job's triggers in error state '"
+ trigger.getFullName() + "'", se2);
// db connection must have failed... keep retrying
// until it's up...
releaseTriggerRetryLoop(trigger);
}
}
continue;
}
} else { // if(availTreadCount > 0)
continue; // should never happen, if threadPool.blockForAvailableThreads() follows contract
}
long now = System.currentTimeMillis();
long waitTime = now + getRandomizedIdleWaitTime();
long timeUntilContinue = waitTime - now;
synchronized(sigLock) {
try {
sigLock.wait(timeUntilContinue);
} catch (InterruptedException ignore) {
}
}
} catch(RuntimeException re) {
getLog().error("Runtime error occured in main trigger firing loop.", re);
}
} // loop...
// drop references to scheduler stuff to aid garbage collection...
qs = null;
qsRsrcs = null;
}
private boolean isCandidateNewTimeEarlierWithinReason(long oldTime) {
// So here's the deal: We know due to being signaled that 'the schedule'
// has changed. We may know (if getSignaledNextFireTime() != 0) the
// new earliest fire time. We may not (in which case we will assume
// that the new time is earlier than the trigger we have acquired).
// In either case, we only want to abandon our acquired trigger and
// go looking for a new one if "it's worth it". It's only worth it if
// the time cost incurred to abandon the trigger and acquire a new one
// is less than the time until the currently acquired trigger will fire,
// otherwise we're just "thrashing" the job store (e.g. database).
//
// So the question becomes when is it "worth it"? This will depend on
// the job store implementation (and of course the particular database
// or whatever behind it). Ideally we would depend on the job store
// implementation to tell us the amount of time in which it "thinks"
// it can abandon the acquired trigger and acquire a new one. However
// we have no current facility for having it tell us that, so we make
// a somewhat educated but arbitrary guess ;-).
synchronized(sigLock) {
boolean earlier = false;
if(getSignaledNextFireTime() == 0)
earlier = true;
else if(getSignaledNextFireTime() < oldTime )
earlier = true;
if(earlier) {
// so the new time is considered earlier, but is it enough earlier?
// le
long diff = oldTime - System.currentTimeMillis();
if(diff < (qsRsrcs.getJobStore().supportsPersistence() ? 80L : 7L))
earlier = false;
}
clearSignaledSchedulingChange();
return earlier;
}
}
public void errorTriggerRetryLoop(TriggerFiredBundle bndle) {
int retryCount = 0;
try {
while (!halted) {
try {
Thread.sleep(getDbFailureRetryInterval()); // retry every N
// seconds (the db
// connection must
// be failed)
retryCount++;
qsRsrcs.getJobStore().triggeredJobComplete(ctxt,
bndle.getTrigger(), bndle.getJobDetail(), Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR);
retryCount = 0;
break;
} catch (JobPersistenceException jpe) {
if(retryCount % 4 == 0) {
qs.notifySchedulerListenersError(
"An error occured while releasing trigger '"
+ bndle.getTrigger().getFullName() + "'", jpe);
}
} catch (RuntimeException e) {
getLog().error("releaseTriggerRetryLoop: RuntimeException "+e.getMessage(), e);
} catch (InterruptedException e) {
getLog().error("releaseTriggerRetryLoop: InterruptedException "+e.getMessage(), e);
}
}
} finally {
if(retryCount == 0) {
getLog().info("releaseTriggerRetryLoop: connection restored.");
}
}
}
public void releaseTriggerRetryLoop(Trigger trigger) {
int retryCount = 0;
try {
while (!halted) {
try {
Thread.sleep(getDbFailureRetryInterval()); // retry every N
// seconds (the db
// connection must
// be failed)
retryCount++;
qsRsrcs.getJobStore().releaseAcquiredTrigger(ctxt, trigger);
retryCount = 0;
break;
} catch (JobPersistenceException jpe) {
if(retryCount % 4 == 0) {
qs.notifySchedulerListenersError(
"An error occured while releasing trigger '"
+ trigger.getFullName() + "'", jpe);
}
} catch (RuntimeException e) {
getLog().error("releaseTriggerRetryLoop: RuntimeException "+e.getMessage(), e);
} catch (InterruptedException e) {
getLog().error("releaseTriggerRetryLoop: InterruptedException "+e.getMessage(), e);
}
}
} finally {
if(retryCount == 0) {
getLog().info("releaseTriggerRetryLoop: connection restored.");
}
}
}
public Log getLog() {
return log;
}
} // end of QuartzSchedulerThread
|
3e06a282147b3c712910549270169573c143aea8
| 8,885 |
java
|
Java
|
org/spongepowered/asm/lib/FieldWriter.java
|
christallinqq/ninehack
|
d40415b9ff5d1e8d4c325d98e1213bbcff0cf218
|
[
"Apache-2.0"
] | 6 |
2021-09-18T03:18:42.000Z
|
2021-09-18T21:13:26.000Z
|
org/spongepowered/asm/lib/FieldWriter.java
|
christallinqq/ninehack
|
d40415b9ff5d1e8d4c325d98e1213bbcff0cf218
|
[
"Apache-2.0"
] | 2 |
2021-09-18T18:43:04.000Z
|
2021-09-21T02:51:31.000Z
|
org/spongepowered/asm/lib/FieldWriter.java
|
christallinqq/ninehack
|
d40415b9ff5d1e8d4c325d98e1213bbcff0cf218
|
[
"Apache-2.0"
] | 1 |
2021-09-18T12:33:42.000Z
|
2021-09-18T12:33:42.000Z
| 26.601796 | 122 | 0.3991 | 2,830 |
/* */ package org.spongepowered.asm.lib;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ final class FieldWriter
/* */ extends FieldVisitor
/* */ {
/* */ private final ClassWriter cw;
/* */ private final int access;
/* */ private final int name;
/* */ private final int desc;
/* */ private int signature;
/* */ private int value;
/* */ private AnnotationWriter anns;
/* */ private AnnotationWriter ianns;
/* */ private AnnotationWriter tanns;
/* */ private AnnotationWriter itanns;
/* */ private Attribute attrs;
/* */
/* */ FieldWriter(ClassWriter cw, int access, String name, String desc, String signature, Object value) {
/* 121 */ super(327680);
/* 122 */ if (cw.firstField == null) {
/* 123 */ cw.firstField = this;
/* */ } else {
/* 125 */ cw.lastField.fv = this;
/* */ }
/* 127 */ cw.lastField = this;
/* 128 */ this.cw = cw;
/* 129 */ this.access = access;
/* 130 */ this.name = cw.newUTF8(name);
/* 131 */ this.desc = cw.newUTF8(desc);
/* 132 */ if (signature != null) {
/* 133 */ this.signature = cw.newUTF8(signature);
/* */ }
/* 135 */ if (value != null) {
/* 136 */ this.value = (cw.newConstItem(value)).index;
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
/* 150 */ ByteVector bv = new ByteVector();
/* */
/* 152 */ bv.putShort(this.cw.newUTF8(desc)).putShort(0);
/* 153 */ AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, 2);
/* 154 */ if (visible) {
/* 155 */ aw.next = this.anns;
/* 156 */ this.anns = aw;
/* */ } else {
/* 158 */ aw.next = this.ianns;
/* 159 */ this.ianns = aw;
/* */ }
/* 161 */ return aw;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
/* 170 */ ByteVector bv = new ByteVector();
/* */
/* 172 */ AnnotationWriter.putTarget(typeRef, typePath, bv);
/* */
/* 174 */ bv.putShort(this.cw.newUTF8(desc)).putShort(0);
/* 175 */ AnnotationWriter aw = new AnnotationWriter(this.cw, true, bv, bv, bv.length - 2);
/* */
/* 177 */ if (visible) {
/* 178 */ aw.next = this.tanns;
/* 179 */ this.tanns = aw;
/* */ } else {
/* 181 */ aw.next = this.itanns;
/* 182 */ this.itanns = aw;
/* */ }
/* 184 */ return aw;
/* */ }
/* */
/* */
/* */ public void visitAttribute(Attribute attr) {
/* 189 */ attr.next = this.attrs;
/* 190 */ this.attrs = attr;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void visitEnd() {}
/* */
/* */
/* */
/* */
/* */
/* */
/* */ int getSize() {
/* 207 */ int size = 8;
/* 208 */ if (this.value != 0) {
/* 209 */ this.cw.newUTF8("ConstantValue");
/* 210 */ size += 8;
/* */ }
/* 212 */ if ((this.access & 0x1000) != 0 && ((
/* 213 */ this.cw.version & 0xFFFF) < 49 || (this.access & 0x40000) != 0)) {
/* */
/* 215 */ this.cw.newUTF8("Synthetic");
/* 216 */ size += 6;
/* */ }
/* */
/* 219 */ if ((this.access & 0x20000) != 0) {
/* 220 */ this.cw.newUTF8("Deprecated");
/* 221 */ size += 6;
/* */ }
/* 223 */ if (this.signature != 0) {
/* 224 */ this.cw.newUTF8("Signature");
/* 225 */ size += 8;
/* */ }
/* 227 */ if (this.anns != null) {
/* 228 */ this.cw.newUTF8("RuntimeVisibleAnnotations");
/* 229 */ size += 8 + this.anns.getSize();
/* */ }
/* 231 */ if (this.ianns != null) {
/* 232 */ this.cw.newUTF8("RuntimeInvisibleAnnotations");
/* 233 */ size += 8 + this.ianns.getSize();
/* */ }
/* 235 */ if (this.tanns != null) {
/* 236 */ this.cw.newUTF8("RuntimeVisibleTypeAnnotations");
/* 237 */ size += 8 + this.tanns.getSize();
/* */ }
/* 239 */ if (this.itanns != null) {
/* 240 */ this.cw.newUTF8("RuntimeInvisibleTypeAnnotations");
/* 241 */ size += 8 + this.itanns.getSize();
/* */ }
/* 243 */ if (this.attrs != null) {
/* 244 */ size += this.attrs.getSize(this.cw, null, 0, -1, -1);
/* */ }
/* 246 */ return size;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ void put(ByteVector out) {
/* 256 */ int FACTOR = 64;
/* 257 */ int mask = 0x60000 | (this.access & 0x40000) / 64;
/* */
/* 259 */ out.putShort(this.access & (mask ^ 0xFFFFFFFF)).putShort(this.name).putShort(this.desc);
/* 260 */ int attributeCount = 0;
/* 261 */ if (this.value != 0) {
/* 262 */ attributeCount++;
/* */ }
/* 264 */ if ((this.access & 0x1000) != 0 && ((
/* 265 */ this.cw.version & 0xFFFF) < 49 || (this.access & 0x40000) != 0))
/* */ {
/* 267 */ attributeCount++;
/* */ }
/* */
/* 270 */ if ((this.access & 0x20000) != 0) {
/* 271 */ attributeCount++;
/* */ }
/* 273 */ if (this.signature != 0) {
/* 274 */ attributeCount++;
/* */ }
/* 276 */ if (this.anns != null) {
/* 277 */ attributeCount++;
/* */ }
/* 279 */ if (this.ianns != null) {
/* 280 */ attributeCount++;
/* */ }
/* 282 */ if (this.tanns != null) {
/* 283 */ attributeCount++;
/* */ }
/* 285 */ if (this.itanns != null) {
/* 286 */ attributeCount++;
/* */ }
/* 288 */ if (this.attrs != null) {
/* 289 */ attributeCount += this.attrs.getCount();
/* */ }
/* 291 */ out.putShort(attributeCount);
/* 292 */ if (this.value != 0) {
/* 293 */ out.putShort(this.cw.newUTF8("ConstantValue"));
/* 294 */ out.putInt(2).putShort(this.value);
/* */ }
/* 296 */ if ((this.access & 0x1000) != 0 && ((
/* 297 */ this.cw.version & 0xFFFF) < 49 || (this.access & 0x40000) != 0))
/* */ {
/* 299 */ out.putShort(this.cw.newUTF8("Synthetic")).putInt(0);
/* */ }
/* */
/* 302 */ if ((this.access & 0x20000) != 0) {
/* 303 */ out.putShort(this.cw.newUTF8("Deprecated")).putInt(0);
/* */ }
/* 305 */ if (this.signature != 0) {
/* 306 */ out.putShort(this.cw.newUTF8("Signature"));
/* 307 */ out.putInt(2).putShort(this.signature);
/* */ }
/* 309 */ if (this.anns != null) {
/* 310 */ out.putShort(this.cw.newUTF8("RuntimeVisibleAnnotations"));
/* 311 */ this.anns.put(out);
/* */ }
/* 313 */ if (this.ianns != null) {
/* 314 */ out.putShort(this.cw.newUTF8("RuntimeInvisibleAnnotations"));
/* 315 */ this.ianns.put(out);
/* */ }
/* 317 */ if (this.tanns != null) {
/* 318 */ out.putShort(this.cw.newUTF8("RuntimeVisibleTypeAnnotations"));
/* 319 */ this.tanns.put(out);
/* */ }
/* 321 */ if (this.itanns != null) {
/* 322 */ out.putShort(this.cw.newUTF8("RuntimeInvisibleTypeAnnotations"));
/* 323 */ this.itanns.put(out);
/* */ }
/* 325 */ if (this.attrs != null)
/* 326 */ this.attrs.put(this.cw, null, 0, -1, -1, out);
/* */ }
/* */ }
/* Location: C:\Users\tarka\Downloads\ninehack-1.0.1-release.jar!\org\spongepowered\asm\lib\FieldWriter.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 1.1.3
*/
|
3e06a2a5ce77923a2a3aa3cc60b74658f99cb7c6
| 1,888 |
java
|
Java
|
rts/src/main/java/eta/runtime/storage/HeapStats.java
|
baajur/eta
|
97ee2251bbc52294efbf60fa4342ce6f52c0d25c
|
[
"BSD-3-Clause"
] | 2,497 |
2016-10-25T06:11:23.000Z
|
2022-03-20T14:27:58.000Z
|
rts/src/main/java/eta/runtime/storage/HeapStats.java
|
baajur/eta
|
97ee2251bbc52294efbf60fa4342ce6f52c0d25c
|
[
"BSD-3-Clause"
] | 845 |
2016-10-25T11:18:38.000Z
|
2021-09-22T10:05:37.000Z
|
rts/src/main/java/eta/runtime/storage/HeapStats.java
|
baajur/eta
|
97ee2251bbc52294efbf60fa4342ce6f52c0d25c
|
[
"BSD-3-Clause"
] | 190 |
2016-10-28T15:02:57.000Z
|
2022-01-10T05:21:34.000Z
| 25.173333 | 106 | 0.590572 | 2,831 |
package eta.runtime.storage;
import java.util.List;
import static eta.runtime.util.Report.*;
public class HeapStats {
int nurserySize;
int blockSize;
int miniBlockSize;
List<NurseryStats> nurseryStats;
public HeapStats(int nurserySize, int blockSize, int miniBlockSize, List<NurseryStats> nurseryStats) {
this.nurserySize = nurserySize;
this.blockSize = blockSize;
this.miniBlockSize = miniBlockSize;
this.nurseryStats = nurseryStats;
}
public long getTotalBytesAllocated() {
/* TODO: Implement */
return 0;
}
public long getTotalBytesFree() {
/* TODO: Implement */
return 0;
}
public int getNurserySize() {
return nurserySize;
}
public int getBlockSize() {
return blockSize;
}
public int getMiniBlockSize() {
return miniBlockSize;
}
public List<NurseryStats> getNurseryStats() {
return nurseryStats;
}
public String generateReport() {
StringBuilder sb = new StringBuilder();
generateReport(sb);
return sb.toString();
}
public void generateReport(StringBuilder sb) {
header(sb, "Eta Memory Manager");
blankLine(sb);
header(sb, "Native Heap Statistics");
blankLine(sb);
format(sb, " Nursery Size: %d bytes", nurserySize);
format(sb, " Block Size: %d bytes", blockSize);
format(sb, "MiniBlock Size: %d bytes", miniBlockSize);
format(sb, "Total Nurseries: %d", nurseryStats.size());
blankLine(sb);
header(sb, "Nurseries");
blankLine(sb);
int i = 0;
for (NurseryStats stats: nurseryStats) {
format(sb, "Nursery %d:", i);
blankLine(sb);
stats.generateReport(sb);
blankLine(sb);
i++;
}
}
}
|
3e06a3316768ed2e9ac855b7e337fca401b9ecfe
| 953 |
java
|
Java
|
src/main/java/com/udacity/jwdnd/course1/cloudstorage/mapper/FileMapper.java
|
sunil-babu/cloudStorageUdacity
|
186e63715601e87819ff6f979b9f9d640fa1c283
|
[
"MIT"
] | null | null | null |
src/main/java/com/udacity/jwdnd/course1/cloudstorage/mapper/FileMapper.java
|
sunil-babu/cloudStorageUdacity
|
186e63715601e87819ff6f979b9f9d640fa1c283
|
[
"MIT"
] | null | null | null |
src/main/java/com/udacity/jwdnd/course1/cloudstorage/mapper/FileMapper.java
|
sunil-babu/cloudStorageUdacity
|
186e63715601e87819ff6f979b9f9d640fa1c283
|
[
"MIT"
] | null | null | null | 31.766667 | 88 | 0.710388 | 2,832 |
package com.udacity.jwdnd.course1.cloudstorage.mapper;
import com.udacity.jwdnd.course1.cloudstorage.model.File;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface FileMapper {
@Select("SELECT * FROM FILES WHERE fileId = #{fileId}")
File findFileById(Integer fileId);
@Select("SELECT * FROM FILES WHERE fileName = #{fileName}")
File findFileByName(String fileName);
@Select("SELECT * FROM FILES WHERE userId = #{userId}")
List<File> findAllFiles(int userId);
@Insert("INSERT INTO FILES (fileName, contentType, fileSize, userId, fileData) "
+"VALUES(#{fileName}, #{contentType}, #{fileSize}, #{userId}, #{fileData})")
@Options(useGeneratedKeys = true, keyProperty = "fileId")
Integer insert(File file);
@Delete("DELETE FROM FILES WHERE fileId = #{fileId}")
Integer delete(Integer fileId);
}
|
3e06a47893d2a4806ed880788f60a63652bf016b
| 342 |
java
|
Java
|
src/main/java/at/ac/ait/lablink/core/connection/rpc/package-info.java
|
AIT-Lablink/lablink-core-java
|
6d18cb405e6b05ebb3c2fdecd4910c82eee0e17b
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/at/ac/ait/lablink/core/connection/rpc/package-info.java
|
AIT-Lablink/lablink-core-java
|
6d18cb405e6b05ebb3c2fdecd4910c82eee0e17b
|
[
"BSD-3-Clause"
] | 1 |
2021-03-30T11:30:36.000Z
|
2021-04-07T16:28:23.000Z
|
src/main/java/at/ac/ait/lablink/core/connection/rpc/package-info.java
|
AIT-Lablink/lablink-core-java
|
6d18cb405e6b05ebb3c2fdecd4910c82eee0e17b
|
[
"BSD-3-Clause"
] | null | null | null | 28.5 | 61 | 0.745614 | 2,833 |
//
// Copyright (c) AIT Austrian Institute of Technology GmbH.
// Distributed under the terms of the Modified BSD License.
//
/**
* Module for remote procedure calls.
*
* <p>This package contains the specification for sending
* requests and waiting for replies using the Lablink system.
*/
package at.ac.ait.lablink.core.connection.rpc;
|
3e06a532fd9a6d31fe13c2b635ddc55a4269135b
| 3,354 |
java
|
Java
|
data/groundtruth/all/methodAbstractAddedToClass/rest-service-4.0-b72-sources/org/glassfish/admin/rest/provider/MethodMetaData.java
|
crossminer/maracas
|
662a44542065a896195e0ae719624550ae4dd39d
|
[
"MIT"
] | 6 |
2020-06-13T19:46:29.000Z
|
2021-12-13T13:17:13.000Z
|
data/groundtruth/all/methodAbstractAddedToClass/rest-service-4.0-b72-sources/org/glassfish/admin/rest/provider/MethodMetaData.java
|
crossminer/maracas
|
662a44542065a896195e0ae719624550ae4dd39d
|
[
"MIT"
] | 29 |
2019-08-19T13:50:19.000Z
|
2021-01-26T16:01:44.000Z
|
data/groundtruth/all/methodAbstractAddedToClass/rest-service-4.0-b72-sources/org/glassfish/admin/rest/provider/MethodMetaData.java
|
crossminer/maracas
|
662a44542065a896195e0ae719624550ae4dd39d
|
[
"MIT"
] | null | null | null | 33.878788 | 78 | 0.738521 | 2,834 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2009-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.admin.rest.provider;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Meta-data store for resource method. Holds meta-data for message
* and query paramters of the method.
*
* @author Rajeshwar Patil
*/
public class MethodMetaData {
public MethodMetaData() {
__parameterMetaData = new TreeMap<String, ParameterMetaData>();
}
public ParameterMetaData getParameterMetaData(String parameter) {
return __parameterMetaData.get(parameter);
}
public ParameterMetaData putParameterMetaData(String parameter,
ParameterMetaData parameterMetaData) {
return __parameterMetaData.put(parameter, parameterMetaData);
}
public ParameterMetaData removeParamMetaData(String param) {
return __parameterMetaData.remove(param);
}
public int sizeParameterMetaData() {
return __parameterMetaData.size();
}
public Set<String> parameters() {
return __parameterMetaData.keySet();
}
public boolean isFileUploadOperation() {
return __isFileUploadOperation;
}
public void setIsFileUploadOperation(boolean isFileUploadOperation) {
__isFileUploadOperation = isFileUploadOperation;
}
Map<String, ParameterMetaData> __parameterMetaData;
boolean __isFileUploadOperation = false;
}
|
3e06a5b09b20e85ca8cf88f5e8037b1aafa2b819
| 1,215 |
java
|
Java
|
stack/rest/src/main/java/org/apache/usergrid/rest/exceptions/UncaughtException.java
|
bernhardriegler/usergrid
|
79e37c9df0ee7debfb080b080cf4f6a5a03ebc46
|
[
"Apache-2.0"
] | 788 |
2015-08-21T16:46:57.000Z
|
2022-03-16T01:57:44.000Z
|
stack/rest/src/main/java/org/apache/usergrid/rest/exceptions/UncaughtException.java
|
bernhardriegler/usergrid
|
79e37c9df0ee7debfb080b080cf4f6a5a03ebc46
|
[
"Apache-2.0"
] | 101 |
2015-08-23T04:58:13.000Z
|
2019-11-13T07:02:57.000Z
|
stack/rest/src/main/java/org/apache/usergrid/rest/exceptions/UncaughtException.java
|
bernhardriegler/usergrid
|
79e37c9df0ee7debfb080b080cf4f6a5a03ebc46
|
[
"Apache-2.0"
] | 342 |
2015-08-22T06:14:20.000Z
|
2022-03-15T01:20:39.000Z
| 32.837838 | 75 | 0.740741 | 2,835 |
/*
* 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.usergrid.rest.exceptions;
import org.apache.usergrid.persistence.model.util.UUIDGenerator;
import java.util.UUID;
public class UncaughtException extends Throwable {
private UUID timeUUID;
public UncaughtException(Throwable cause) {
super(cause);
this.timeUUID = UUIDGenerator.newTimeUUID();
}
public UUID getTimeUUID() {
return timeUUID;
}
}
|
3e06a5b8db4e8761543bd69f95283d918656a0e4
| 4,193 |
java
|
Java
|
ir_service/src/edu/ur/ir/repository/service/DefaultChecksumCheckerJob.java
|
rochester-rcl/irplus
|
6695110887ab3ac3f1db7cf7262dd1a7241c0e04
|
[
"Apache-2.0"
] | 2 |
2020-04-01T08:51:58.000Z
|
2020-12-04T18:45:54.000Z
|
ir_service/src/edu/ur/ir/repository/service/DefaultChecksumCheckerJob.java
|
rochester-rcl/irplus
|
6695110887ab3ac3f1db7cf7262dd1a7241c0e04
|
[
"Apache-2.0"
] | null | null | null |
ir_service/src/edu/ur/ir/repository/service/DefaultChecksumCheckerJob.java
|
rochester-rcl/irplus
|
6695110887ab3ac3f1db7cf7262dd1a7241c0e04
|
[
"Apache-2.0"
] | 1 |
2021-12-28T16:05:41.000Z
|
2021-12-28T16:05:41.000Z
| 30.384058 | 128 | 0.709039 | 2,836 |
package edu.ur.ir.repository.service;
import java.util.GregorianCalendar;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.quartz.StatefulJob;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import edu.ur.file.db.ChecksumCheckerService;
import edu.ur.file.db.FileInfoChecksum;
import edu.ur.file.db.FileInfoChecksumService;
import edu.ur.ir.ErrorEmailService;
/**
* Job set up to run and check checksums of files.
*
* @author Nathan Sarr
*
*/
public class DefaultChecksumCheckerJob implements StatefulJob{
/** Application context from spring */
public static final String APPLICATION_CONTEXT_KEY = "applicationContext";
/** Get the logger for this class */
private static final Logger log = LogManager.getLogger(DefaultChecksumCheckerJob.class);
/**
* Exceuction of the job
* @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
*/
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDetail jobDetail = context.getJobDetail();
String beanName = jobDetail.getName();
if (log.isDebugEnabled())
{
log.info ("Running SpringBeanDelegatingJob - Job Name ["+jobDetail.getName()+"], Group Name ["+jobDetail.getGroup()+"]");
log.info ("Delegating to bean ["+beanName+"]");
}
ApplicationContext applicationContext = null;
try
{
applicationContext = (ApplicationContext) context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);
}
catch (SchedulerException e2)
{
throw new JobExecutionException("problem with the Scheduler", e2);
}
ChecksumCheckerService checksumCheckerService = null;
FileInfoChecksumService fileInfoChecksumService = null;
ErrorEmailService errorEmailService;
PlatformTransactionManager tm = null;
TransactionDefinition td = null;
try
{
checksumCheckerService = (ChecksumCheckerService) applicationContext.getBean("checksumCheckerService");
fileInfoChecksumService = (FileInfoChecksumService) applicationContext.getBean("fileInfoChecksumService");
errorEmailService = (ErrorEmailService)applicationContext.getBean("errorEmailService");
tm = (PlatformTransactionManager) applicationContext.getBean("transactionManager");
td = new DefaultTransactionDefinition(
TransactionDefinition.PROPAGATION_REQUIRED);
}
catch(BeansException e1)
{
throw new JobExecutionException("Unable to retrieve target bean that is to be used as a job source", e1);
}
// start a new transaction
TransactionStatus ts = null;
try
{
ts = tm.getTransaction(td);
GregorianCalendar calendar = new GregorianCalendar();
calendar.add(GregorianCalendar.DAY_OF_YEAR, -5);
if (log.isDebugEnabled())
{
log.debug("getting checksums for before date " + calendar.getTime());
}
List<FileInfoChecksum> checksums = fileInfoChecksumService.getOldestChecksumsForChecker(0, 1, calendar.getTime());
if (log.isDebugEnabled())
{
log.debug("found " + checksums.size() + " checksums");
}
for(FileInfoChecksum checksum : checksums)
{
if (log.isDebugEnabled())
{
log.debug("processing checksum for " + checksum);
}
checksumCheckerService.checkChecksum(checksum);
if(!checksum.getReCalculatedPassed()){
}
}
tm.commit(ts);
}
catch(Exception e)
{
errorEmailService.sendError(e);
}
finally
{
if( ts != null && !ts.isCompleted() )
{
if( tm != null )
{
tm.commit(ts);
}
}
}
}
}
|
3e06a7c87410c428cd8987bc000180c80a11c665
| 325 |
java
|
Java
|
src/main/java/com/seshut/example/jwtauth/UserNotesApplication.java
|
SeshuTechie/spring-jwt-sample
|
5827843f2c772f9062bc1c8ee3e3cf3612d24476
|
[
"MIT"
] | null | null | null |
src/main/java/com/seshut/example/jwtauth/UserNotesApplication.java
|
SeshuTechie/spring-jwt-sample
|
5827843f2c772f9062bc1c8ee3e3cf3612d24476
|
[
"MIT"
] | null | null | null |
src/main/java/com/seshut/example/jwtauth/UserNotesApplication.java
|
SeshuTechie/spring-jwt-sample
|
5827843f2c772f9062bc1c8ee3e3cf3612d24476
|
[
"MIT"
] | null | null | null | 23.214286 | 68 | 0.824615 | 2,837 |
package com.seshut.example.jwtauth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserNotesApplication {
public static void main(String[] args) {
SpringApplication.run(UserNotesApplication.class, args);
}
}
|
3e06a86512fefc8dd17a6308cb34e1195016fe91
| 2,178 |
java
|
Java
|
izpack-compiler/src/main/java/com/izforge/izpack/compiler/container/provider/CompressedOutputStreamProvider.java
|
lgrill-pentaho/izpack
|
f74abef01c45bc3f4e8fe9251cbd8293888774b3
|
[
"Apache-2.0"
] | null | null | null |
izpack-compiler/src/main/java/com/izforge/izpack/compiler/container/provider/CompressedOutputStreamProvider.java
|
lgrill-pentaho/izpack
|
f74abef01c45bc3f4e8fe9251cbd8293888774b3
|
[
"Apache-2.0"
] | 1 |
2021-08-02T17:26:26.000Z
|
2021-08-02T17:26:26.000Z
|
izpack-compiler/src/main/java/com/izforge/izpack/compiler/container/provider/CompressedOutputStreamProvider.java
|
lgrill-pentaho/izpack
|
f74abef01c45bc3f4e8fe9251cbd8293888774b3
|
[
"Apache-2.0"
] | 1 |
2021-01-12T11:39:34.000Z
|
2021-01-12T11:39:34.000Z
| 35.704918 | 131 | 0.724977 | 2,838 |
/*
* IzPack - Copyright 2001-2012 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* 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.izforge.izpack.compiler.container.provider;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.tools.zip.ZipEntry;
import org.picocontainer.injectors.Provider;
import com.izforge.izpack.compiler.data.CompilerData;
import com.izforge.izpack.compiler.stream.JarOutputStream;
/**
* Created by IntelliJ IDEA.
*
* @author Anthonin Bonnefoy
*/
public class CompressedOutputStreamProvider implements Provider
{
public OutputStream provide(CompilerData compilerData, JarOutputStream jarOutputStream) throws CompressorException, IOException
{
OutputStream outputStream = jarOutputStream;
String comprFormat = compilerData.getComprFormat();
if (comprFormat.equals("bzip2"))
{
ZipEntry entry = new ZipEntry("bzip2");
entry.setMethod(ZipEntry.STORED);
entry.setComment("bzip2");
// We must set the entry before we get the compressed stream
// because some writes initialize data (e.g. bzip2).
jarOutputStream.putNextEntry(entry);
jarOutputStream.flush(); // flush before we start counting
outputStream = new CompressorStreamFactory().createCompressorOutputStream("bzip2", jarOutputStream);
jarOutputStream.closeEntry();
}
return outputStream;
}
}
|
3e06a86e28754dff0447b61fb4f591268a08d224
| 211 |
java
|
Java
|
src/main/java/ommina/biomediversity/IProxy.java
|
Ommina/BiomeDiversity
|
3200e3976f34ac50e3ab2d4381c780a92b651f83
|
[
"MIT"
] | null | null | null |
src/main/java/ommina/biomediversity/IProxy.java
|
Ommina/BiomeDiversity
|
3200e3976f34ac50e3ab2d4381c780a92b651f83
|
[
"MIT"
] | 1 |
2019-12-28T08:51:44.000Z
|
2019-12-28T10:21:45.000Z
|
src/main/java/ommina/biomediversity/IProxy.java
|
Ommina/BiomeDiversity
|
3200e3976f34ac50e3ab2d4381c780a92b651f83
|
[
"MIT"
] | 1 |
2019-12-28T04:47:02.000Z
|
2019-12-28T04:47:02.000Z
| 16.230769 | 48 | 0.777251 | 2,839 |
package ommina.biomediversity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.world.World;
public interface IProxy {
World getClientWorld();
PlayerEntity getClientPlayer();
}
|
3e06a8784d1ae700bf942e47725d539160492925
| 5,739 |
java
|
Java
|
src/main/java/com/xero/models/payrolluk/Account.java
|
ledgerscope/Xero-Java
|
0e7f3aaefbed0eb5575b5a3a4dc2899cf71093fe
|
[
"MIT"
] | 70 |
2016-09-22T23:19:14.000Z
|
2022-01-13T07:09:44.000Z
|
src/main/java/com/xero/models/payrolluk/Account.java
|
ledgerscope/Xero-Java
|
0e7f3aaefbed0eb5575b5a3a4dc2899cf71093fe
|
[
"MIT"
] | 213 |
2016-11-08T11:27:01.000Z
|
2022-03-10T23:01:03.000Z
|
src/main/java/com/xero/models/payrolluk/Account.java
|
ledgerscope/Xero-Java
|
0e7f3aaefbed0eb5575b5a3a4dc2899cf71093fe
|
[
"MIT"
] | 106 |
2016-08-15T03:12:16.000Z
|
2022-03-17T12:18:55.000Z
| 20.261484 | 100 | 0.608825 | 2,840 |
/*
* Xero Payroll UK
* This is the Xero Payroll API for orgs in the UK region.
*
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.xero.models.payrolluk;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.xero.api.StringUtil;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
import java.util.UUID;
/** Account */
public class Account {
StringUtil util = new StringUtil();
@JsonProperty("accountID")
private UUID accountID;
/** The assigned AccountType */
public enum TypeEnum {
/** BANK */
BANK("BANK"),
/** EMPLOYERSNIC */
EMPLOYERSNIC("EMPLOYERSNIC"),
/** NICLIABILITY */
NICLIABILITY("NICLIABILITY"),
/** PAYEECONTRIBUTION */
PAYEECONTRIBUTION("PAYEECONTRIBUTION"),
/** PAYELIABILITY */
PAYELIABILITY("PAYELIABILITY"),
/** WAGESPAYABLE */
WAGESPAYABLE("WAGESPAYABLE"),
/** WAGESEXPENSE */
WAGESEXPENSE("WAGESEXPENSE");
private String value;
TypeEnum(String value) {
this.value = value;
}
/**
* getValue
*
* @return String value
*/
@JsonValue
public String getValue() {
return value;
}
/**
* toString
*
* @return String value
*/
@Override
public String toString() {
return String.valueOf(value);
}
/**
* fromValue
*
* @param value String
*/
@JsonCreator
public static TypeEnum fromValue(String value) {
for (TypeEnum b : TypeEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
}
@JsonProperty("type")
private TypeEnum type;
@JsonProperty("code")
private String code;
@JsonProperty("name")
private String name;
/**
* The Xero identifier for Settings.
*
* @param accountID UUID
* @return Account
*/
public Account accountID(UUID accountID) {
this.accountID = accountID;
return this;
}
/**
* The Xero identifier for Settings.
*
* @return accountID
*/
@ApiModelProperty(value = "The Xero identifier for Settings.")
/**
* The Xero identifier for Settings.
*
* @return accountID UUID
*/
public UUID getAccountID() {
return accountID;
}
/**
* The Xero identifier for Settings.
*
* @param accountID UUID
*/
public void setAccountID(UUID accountID) {
this.accountID = accountID;
}
/**
* The assigned AccountType
*
* @param type TypeEnum
* @return Account
*/
public Account type(TypeEnum type) {
this.type = type;
return this;
}
/**
* The assigned AccountType
*
* @return type
*/
@ApiModelProperty(value = "The assigned AccountType")
/**
* The assigned AccountType
*
* @return type TypeEnum
*/
public TypeEnum getType() {
return type;
}
/**
* The assigned AccountType
*
* @param type TypeEnum
*/
public void setType(TypeEnum type) {
this.type = type;
}
/**
* A unique 3 digit number for each Account
*
* @param code String
* @return Account
*/
public Account code(String code) {
this.code = code;
return this;
}
/**
* A unique 3 digit number for each Account
*
* @return code
*/
@ApiModelProperty(value = "A unique 3 digit number for each Account")
/**
* A unique 3 digit number for each Account
*
* @return code String
*/
public String getCode() {
return code;
}
/**
* A unique 3 digit number for each Account
*
* @param code String
*/
public void setCode(String code) {
this.code = code;
}
/**
* Name of the Account.
*
* @param name String
* @return Account
*/
public Account name(String name) {
this.name = name;
return this;
}
/**
* Name of the Account.
*
* @return name
*/
@ApiModelProperty(value = "Name of the Account.")
/**
* Name of the Account.
*
* @return name String
*/
public String getName() {
return name;
}
/**
* Name of the Account.
*
* @param name String
*/
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Account account = (Account) o;
return Objects.equals(this.accountID, account.accountID)
&& Objects.equals(this.type, account.type)
&& Objects.equals(this.code, account.code)
&& Objects.equals(this.name, account.name);
}
@Override
public int hashCode() {
return Objects.hash(accountID, type, code, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Account {\n");
sb.append(" accountID: ").append(toIndentedString(accountID)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e06aa1bbe429f6cd7ec0cc8a2410214d69d912d
| 1,221 |
java
|
Java
|
src/main/java/com/roycer/cam/myTaskListener.java
|
roycer/cam
|
5dc2a44e48619a8af9fd4d16d7c1b793f3582a64
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/roycer/cam/myTaskListener.java
|
roycer/cam
|
5dc2a44e48619a8af9fd4d16d7c1b793f3582a64
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/roycer/cam/myTaskListener.java
|
roycer/cam
|
5dc2a44e48619a8af9fd4d16d7c1b793f3582a64
|
[
"Apache-2.0"
] | null | null | null | 31.307692 | 83 | 0.662572 | 2,841 |
package com.roycer.cam;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.UserTask;
public class myTaskListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
UserTask userTask = delegateTask.getBpmnModelElementInstance();
String eventName = delegateTask.getEventName();
System.out.println("["+eventName+"] -> "+userTask.getName());
System.out.println("\t id_Task: "+delegateTask.getId());
switch (eventName) {
case "create":
System.out.println("\t assignment: "+delegateTask.getAssignee());
System.out.println("\t priority: "+delegateTask.getPriority());
try {
System.out.println("\t var: "+delegateTask.getVariable("var"));
System.out.println("\t varLocal: "+delegateTask.getVariableLocal("var"));
} catch (Exception e) {
System.out.println("\t var: error");
}
break;
case "assignment":
System.out.println("\t assignment: "+delegateTask.getAssignee());
break;
case "complete": break;
case "delete": break;
default: break;
}
}
}
|
3e06acd15fb995a2141492dec47b5739bd322bff
| 1,729 |
java
|
Java
|
src/main/java/com/example/csvspringprocessing/interfaces/CsvProcessorController.java
|
maketheworldwise/csv-spring-processing
|
fde0e16f1a91f452c2ad7b8e8f02b9dfa81aae65
|
[
"MIT"
] | null | null | null |
src/main/java/com/example/csvspringprocessing/interfaces/CsvProcessorController.java
|
maketheworldwise/csv-spring-processing
|
fde0e16f1a91f452c2ad7b8e8f02b9dfa81aae65
|
[
"MIT"
] | null | null | null |
src/main/java/com/example/csvspringprocessing/interfaces/CsvProcessorController.java
|
maketheworldwise/csv-spring-processing
|
fde0e16f1a91f452c2ad7b8e8f02b9dfa81aae65
|
[
"MIT"
] | null | null | null | 33.901961 | 104 | 0.714864 | 2,842 |
package com.example.csvspringprocessing.interfaces;
import com.example.csvspringprocessing.application.CsvProcessorService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RequiredArgsConstructor
@RestController
public class CsvProcessorController {
private final CsvProcessorService csvProcessorService;
@GetMapping("/test")
public String test() {
return "test";
}
// 직접 구현
@PostMapping("/custom-csv/processing")
public ResponseEntity<?> csvCustomProcessing(@RequestParam(value = "file") MultipartFile file) {
csvProcessorService.customProcessor(file);
return new ResponseEntity<>(
"성공적으로 변환에 성공하였습니다.",
HttpStatus.OK);
}
// OpenCsv 라이브러리 테스트
@PostMapping("/open-csv/processing/test")
public ResponseEntity<?> openCsvCustomProcessingTest() {
csvProcessorService.openCsvProcessorTest();
return new ResponseEntity<>(
"성공적으로 테스트하였습니다.",
HttpStatus.OK);
}
// OpenCsv 라이브러리
@PostMapping("/open-csv/processing")
public ResponseEntity<?> openCsvCustomProcessing(@RequestParam(value = "file") MultipartFile file) {
csvProcessorService.openCsvProcessor(file);
return new ResponseEntity<>(
"성공적으로 변환에 성공하였습니다.",
HttpStatus.OK);
}
}
|
3e06ad1bd153f63f52724efee6c2711133254e7d
| 2,692 |
java
|
Java
|
src/main/java/lambdasinaction/chap6/Partitioning.java
|
kimi-sxh/Java8InAction
|
633e43058a5ef1ab7a517e8a6da58100ee2f4859
|
[
"MIT"
] | null | null | null |
src/main/java/lambdasinaction/chap6/Partitioning.java
|
kimi-sxh/Java8InAction
|
633e43058a5ef1ab7a517e8a6da58100ee2f4859
|
[
"MIT"
] | null | null | null |
src/main/java/lambdasinaction/chap6/Partitioning.java
|
kimi-sxh/Java8InAction
|
633e43058a5ef1ab7a517e8a6da58100ee2f4859
|
[
"MIT"
] | null | null | null | 38.457143 | 136 | 0.66679 | 2,843 |
package lambdasinaction.chap6;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.ToIntFunction;
import java.util.stream.Collector;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.*;
import static lambdasinaction.chap6.Dish.menu;
public class Partitioning {
public static void main(String ... args) {
//6.4.1节 分区
System.out.println("Dishes partitioned by vegetarian: " + partitionByVegeterian());
System.out.println("Vegetarian Dishes by type: " + vegetarianDishesByType());
System.out.println("Most caloric dishes by vegetarian: " + mostCaloricPartitionedByVegetarian());
}
/**
* <b>概要:</b>:
* 根据是否为素菜分区
* <b>作者:</b>SUXH</br>
* <b>日期:</b>2020/3/15 10:40 </br>
* @return true-对应素菜列表,false-对应非素菜列表
*/
private static Map<Boolean, List<Dish>> partitionByVegeterian() {
return menu.stream().collect(partitioningBy(Dish::isVegetarian));
}
/**
* <b>概要:</b>:
* 根据是否为素菜分区,才形成二级map
* <b>作者:</b>SUXH</br>
* <b>日期:</b>2020/3/15 10:45 </br>
* @param:
* @return:
*/
private static Map<Boolean, Map<Dish.Type, List<Dish>>> vegetarianDishesByType() {
Function<Dish, Dish.Type> getType = Dish::getType;
Collector<Dish, ?, Map<Dish.Type, List<Dish>>> dishMapCollector = groupingBy(getType);//按照类型分组
Predicate<Dish> isVegetarian = Dish::isVegetarian;//是否为素菜
Collector<Dish, ?, Map<Boolean, Map<Dish.Type, List<Dish>>>> dishMapCollector1 = partitioningBy(isVegetarian, dishMapCollector);
return menu.stream().collect(dishMapCollector1);
}
/**
* <b>概要:</b>:
* 找出素菜和非素菜中热量最高的菜
* <b>作者:</b>SUXH</br>
* <b>日期:</b>2020/3/15 11:01 </br>
* @return true-热量最高的菜 false-非素菜中热量最高的菜
*/
private static Map<Boolean, String> mostCaloricPartitionedByVegetarian() {
Predicate<Dish> isVegetarian = Dish::isVegetarian;
ToIntFunction<Dish> getCalories = Dish::getCalories;
Collector<Dish, ?, Optional<Dish>> dishOptionalCollector = maxBy(comparingInt(getCalories));
//将结果容器应用最终转换
Function<Optional<Dish>,String> finisher = (dishOptional)->dishOptional.get().getName()+":"+dishOptional.get().getCalories();
Collector<Dish, ?, String> dishDishCollector = collectingAndThen(dishOptionalCollector, finisher);
Collector<Dish, ?, Map<Boolean, String>> dishMapCollector = partitioningBy(isVegetarian, dishDishCollector);
return menu.stream().collect(dishMapCollector);
}
}
|
3e06ae038dba14633dffa5601133974444d9a3db
| 409 |
java
|
Java
|
urule-core/src/main/java/com/bstek/urule/model/crosstab/TopColumn.java
|
zsy1988cool/urule
|
1b7edeef8bb6e9b365b249cb9900fe82cf23ad5d
|
[
"Apache-2.0"
] | 1 |
2020-06-03T00:24:36.000Z
|
2020-06-03T00:24:36.000Z
|
urule-core/src/main/java/com/bstek/urule/model/crosstab/TopColumn.java
|
wuranjia/myRule
|
6fd0cd6c13ac23ad7f678dda9def8b553d72901e
|
[
"Apache-2.0"
] | 1 |
2021-05-10T15:16:10.000Z
|
2021-05-10T15:16:10.000Z
|
urule-core/src/main/java/com/bstek/urule/model/crosstab/TopColumn.java
|
wuranjia/myRule
|
6fd0cd6c13ac23ad7f678dda9def8b553d72901e
|
[
"Apache-2.0"
] | null | null | null | 19.47619 | 52 | 0.618582 | 2,844 |
package com.bstek.urule.model.crosstab;
public class TopColumn implements CrossColumn {
private int columnNumber;
public TopColumn() {
}
public int getColumnNumber() {
return this.columnNumber;
}
public void setColumnNumber(int columnNumber) {
this.columnNumber = columnNumber;
}
public String getType() {
return "top";
}
}
|
3e06ae44204a68e11d29e86bca5a6ce127cba750
| 1,675 |
java
|
Java
|
src/java/master/logica/entidades/Usuario.java
|
ayepezv/WebAppCatastro
|
0ff68975a8d7dd259bcf9aa3e1a21f3121b969a3
|
[
"MIT"
] | null | null | null |
src/java/master/logica/entidades/Usuario.java
|
ayepezv/WebAppCatastro
|
0ff68975a8d7dd259bcf9aa3e1a21f3121b969a3
|
[
"MIT"
] | null | null | null |
src/java/master/logica/entidades/Usuario.java
|
ayepezv/WebAppCatastro
|
0ff68975a8d7dd259bcf9aa3e1a21f3121b969a3
|
[
"MIT"
] | null | null | null | 18.611111 | 63 | 0.528955 | 2,845 |
package master.logica.entidades;
import java.io.Serializable;
import java.util.Date;
public class Usuario extends Persona implements Serializable {
private String nick;
private String mail;
private String password;
private Date ultimoAcceso;
private String ultimaIp;
public Usuario() {
}
/**
* @return the nick
*/
public String getNick() {
return nick;
}
/**
* @param nick the nick to set
*/
public void setNick(String nick) {
this.nick = nick;
}
/**
* @return the mail
*/
public String getMail() {
return mail;
}
/**
* @param mail the mail to set
*/
public void setMail(String mail) {
this.mail = mail;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the ultimoAcceso
*/
public Date getUltimoAcceso() {
return ultimoAcceso;
}
/**
* @param ultimoAcceso the ultimoAcceso to set
*/
public void setUltimoAcceso(Date ultimoAcceso) {
this.ultimoAcceso = ultimoAcceso;
}
/**
* @return the ultimaIp
*/
public String getUltimaIp() {
return ultimaIp;
}
/**
* @param ultimaIp the ultimaIp to set
*/
public void setUltimaIp(String ultimaIp) {
this.ultimaIp = ultimaIp;
}
}
|
3e06af66d26a95b09a51e59cc0c552b7d13d34ae
| 1,871 |
java
|
Java
|
model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MigrationModelAdapter.java
|
matzew/keycloak
|
0095968a739e51aea1b298e79fbf9805642be197
|
[
"Apache-2.0"
] | null | null | null |
model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MigrationModelAdapter.java
|
matzew/keycloak
|
0095968a739e51aea1b298e79fbf9805642be197
|
[
"Apache-2.0"
] | null | null | null |
model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MigrationModelAdapter.java
|
matzew/keycloak
|
0095968a739e51aea1b298e79fbf9805642be197
|
[
"Apache-2.0"
] | null | null | null | 32.293103 | 134 | 0.766684 | 2,846 |
package org.keycloak.models.mongo.keycloak.adapters;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import org.keycloak.connections.mongo.api.context.MongoStoreInvocationContext;
import org.keycloak.migration.MigrationModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.entities.ProtocolMapperEntity;
import org.keycloak.models.mongo.keycloak.entities.MongoClientEntity;
import org.keycloak.models.mongo.keycloak.entities.MongoMigrationModelEntity;
import org.keycloak.models.mongo.keycloak.entities.MongoRoleEntity;
import org.keycloak.models.mongo.utils.MongoModelUtils;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Marek Posolda</a>
*/
public class MigrationModelAdapter extends AbstractMongoAdapter<MongoMigrationModelEntity> implements MigrationModel {
protected final MongoMigrationModelEntity entity;
public MigrationModelAdapter(KeycloakSession session, MongoMigrationModelEntity entity, MongoStoreInvocationContext invContext) {
super(invContext);
this.entity = entity;
}
@Override
public MongoMigrationModelEntity getMongoEntity() {
return entity;
}
@Override
public String getStoredVersion() {
return getMongoEntity().getVersion();
}
@Override
public void setStoredVersion(String version) {
getMongoEntity().setVersion(version);
updateMongoEntity();
}
}
|
3e06afc9dd41eeb7c5afbc42a680b53115bf800f
| 11,510 |
java
|
Java
|
webkit/webkit/src/androidTest/java/androidx/webkit/WebSettingsCompatForceDarkTest.java
|
gharrma/androidx
|
e4783158a707fbf82f5893ceb5efec08838056ae
|
[
"Apache-2.0"
] | 2 |
2021-01-20T07:27:37.000Z
|
2021-05-28T14:32:42.000Z
|
webkit/webkit/src/androidTest/java/androidx/webkit/WebSettingsCompatForceDarkTest.java
|
gharrma/androidx
|
e4783158a707fbf82f5893ceb5efec08838056ae
|
[
"Apache-2.0"
] | null | null | null |
webkit/webkit/src/androidTest/java/androidx/webkit/WebSettingsCompatForceDarkTest.java
|
gharrma/androidx
|
e4783158a707fbf82f5893ceb5efec08838056ae
|
[
"Apache-2.0"
] | 1 |
2020-07-28T01:42:42.000Z
|
2020-07-28T01:42:42.000Z
| 41.702899 | 98 | 0.681234 | 2,847 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.webkit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Base64;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.core.graphics.ColorUtils;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.MediumTest;
import androidx.test.rule.ActivityTestRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.HashMap;
import java.util.Map;
@MediumTest
@RunWith(AndroidJUnit4.class)
public class WebSettingsCompatForceDarkTest {
private final String mDarkThemeSupport = Base64.encodeToString((
"<html>"
+ " <head>"
+ " <meta name=\"color-scheme\" content=\"light dark\">"
+ " <style>"
+ " @media (prefers-color-scheme: dark) {"
+ " body {background-color: rgba(0, 255, 0, 1); }"
+ " </style>"
+ " </head>"
+ " <body>"
+ " </body>"
+ "</html>"
).getBytes(), Base64.NO_PADDING);
// LayoutParams are null until WebView has a parent Activity.
// Test testForceDark_rendersDark requires LayoutParams to define
// width and height of WebView to capture its bitmap representation.
@Rule
public final ActivityTestRule<WebViewTestActivity> mActivityRule =
new ActivityTestRule<>(WebViewTestActivity.class);
private WebViewOnUiThread mWebViewOnUiThread;
@Before
public void setUp() {
mWebViewOnUiThread = new WebViewOnUiThread(mActivityRule.getActivity().getWebView());
mWebViewOnUiThread.getSettings().setJavaScriptEnabled(true);
}
@After
public void tearDown() {
if (mWebViewOnUiThread != null) {
mWebViewOnUiThread.cleanUp();
}
}
/**
* This should remain functionally equivalent to
* android.webkit.cts.WebSettingsTest#testForceDark_default. Modifications to this test should
* be reflected in that test as necessary. See http://go/modifying-webview-cts.
*/
@Test
public void testForceDark_default() throws Throwable {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
assertEquals("The default force dark state should be AUTO",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_AUTO);
}
/**
* This should remain functionally equivalent to
* android.webkit.cts.WebSettingsTest#testForceDark_rendersDark. Modifications to this test
* should be reflected in that test as necessary. See http://go/modifying-webview-cts.
*/
@Test
public void testForceDark_rendersDark() throws Throwable {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.OFF_SCREEN_PRERASTER);
setWebViewSize(64, 64);
// Loading about:blank into a force-dark-on webview should result in a dark background
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
assertEquals("Force dark should have been set to ON",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_ON);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be dark",
ColorUtils.calculateLuminance(getWebPageColor()) < 0.5f);
// Loading about:blank into a force-dark-off webview should result in a light background
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
assertEquals("Force dark should have been set to OFF",
WebSettingsCompat.getForceDark(mWebViewOnUiThread.getSettings()),
WebSettingsCompat.FORCE_DARK_OFF);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be light",
ColorUtils.calculateLuminance(getWebPageColor()) > 0.5f);
}
/**
* Test to exercise USER_AGENT_DARKENING_ONLY option,
* i.e. web contents are always darkened by a user agent.
*/
@Test
public void testForceDark_userAgentDarkeningOnly() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
WebkitUtils.checkFeature(WebViewFeature.OFF_SCREEN_PRERASTER);
setWebViewSize(64, 64);
// Loading empty page with or without dark theme support into a force-dark-on webview with
// force dark only algorithm should result in a dark background.
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.DARK_STRATEGY_USER_AGENT_DARKENING_ONLY);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be dark",
ColorUtils.calculateLuminance(getWebPageColor()) < 0.5f);
assertFalse(prefersDarkTheme());
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be dark",
ColorUtils.calculateLuminance(getWebPageColor()) < 0.5f);
assertFalse(prefersDarkTheme());
}
/**
* Test to exercise WEB_THEME_DARKENING_ONLY option,
* i.e. web contents are darkened only by web theme.
*/
@Test
public void testForceDark_webThemeDarkeningOnly() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
WebkitUtils.checkFeature(WebViewFeature.OFF_SCREEN_PRERASTER);
setWebViewSize(64, 64);
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.DARK_STRATEGY_WEB_THEME_DARKENING_ONLY);
// Loading a page without dark-theme support should result in a light background as web
// page is not darken by a user agent
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
assertTrue("Bitmap colour should be light",
ColorUtils.calculateLuminance(getWebPageColor()) > 0.5f);
assertTrue(prefersDarkTheme());
// Loading a page with dark-theme support should result in a green background (as
// specified in media-query)
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be green", isGreen(getWebPageColor()));
assertTrue(prefersDarkTheme());
}
/**
* Test to exercise PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING option,
* i.e. web contents are darkened by a user agent if there is no dark web theme.
*/
@Test
public void testForceDark_preferWebThemeOverUADarkening() {
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK);
WebkitUtils.checkFeature(WebViewFeature.FORCE_DARK_STRATEGY);
WebkitUtils.checkFeature(WebViewFeature.OFF_SCREEN_PRERASTER);
setWebViewSize(64, 64);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
WebSettingsCompat.setForceDark(
mWebViewOnUiThread.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
WebSettingsCompat.setForceDarkStrategy(mWebViewOnUiThread.getSettings(),
WebSettingsCompat.DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING);
mWebViewOnUiThread.loadUrlAndWaitForCompletion("about:blank");
// Loading a page without dark-theme support should result in a dark background as
// web page is darken by a user agent
assertTrue("Bitmap colour should be dark",
ColorUtils.calculateLuminance(getWebPageColor()) < 0.5f);
assertFalse(prefersDarkTheme());
// Loading a page with dark-theme support should result in a green background (as
// specified in media-query)
mWebViewOnUiThread.loadDataAndWaitForCompletion(mDarkThemeSupport, "text/html", "base64");
assertTrue("Bitmap colour should be green",
isGreen(getWebPageColor()));
assertTrue(prefersDarkTheme());
}
private void setWebViewSize(final int width, final int height) {
WebkitUtils.onMainThreadSync(() -> {
WebView webView = mWebViewOnUiThread.getWebViewOnCurrentThread();
ViewGroup.LayoutParams params = webView.getLayoutParams();
params.height = height;
params.width = width;
webView.setLayoutParams(params);
});
}
// Requires {@link WebViewFeature.OFF_SCREEN_PRERASTER} for {@link
// WebViewOnUiThread#captureBitmap}.
private int getWebPageColor() {
Map<Integer, Integer> histogram;
Integer[] colourValues;
histogram = getBitmapHistogram(mWebViewOnUiThread.captureBitmap(), 0, 0, 64, 64);
assertEquals("Bitmap should have a single colour", histogram.size(), 1);
colourValues = histogram.keySet().toArray(new Integer[0]);
return colourValues[0];
}
private Map<Integer, Integer> getBitmapHistogram(
Bitmap bitmap, int x, int y, int width, int height) {
Map<Integer, Integer> histogram = new HashMap<>();
for (int pixel : getBitmapPixels(bitmap, x, y, width, height)) {
Integer count = histogram.get(pixel);
histogram.put(pixel, count == null ? 1 : count + 1);
}
return histogram;
}
private int[] getBitmapPixels(Bitmap bitmap, int x, int y, int width, int height) {
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, x, y, width, height);
return pixels;
}
private boolean prefersDarkTheme() {
final String colorSchemeSelector =
"window.matchMedia('(prefers-color-scheme: dark)').matches";
String result = mWebViewOnUiThread.evaluateJavascriptSync(colorSchemeSelector);
return "true".equals(result);
}
private boolean isGreen(int color) {
return Color.green(color) > 200
&& Color.red(color) < 50
&& Color.blue(color) < 50;
}
}
|
3e06afeccb30524cd693106d03737d0cbe0be15e
| 3,818 |
java
|
Java
|
src/libs/stun/com/cablelabs/stun/attributes/RequestedProps.java
|
tinours/PCSim2
|
e828bf714c94d64e9277522bc316311375297649
|
[
"MIT"
] | 2 |
2019-01-08T00:58:22.000Z
|
2021-04-30T18:47:15.000Z
|
src/libs/stun/com/cablelabs/stun/attributes/RequestedProps.java
|
tinours/PCSim2
|
e828bf714c94d64e9277522bc316311375297649
|
[
"MIT"
] | null | null | null |
src/libs/stun/com/cablelabs/stun/attributes/RequestedProps.java
|
tinours/PCSim2
|
e828bf714c94d64e9277522bc316311375297649
|
[
"MIT"
] | 1 |
2019-03-13T06:32:21.000Z
|
2019-03-13T06:32:21.000Z
| 33.491228 | 87 | 0.564432 | 2,848 |
/*
######################################################################################
## ##
## (c) 2006-2012 Cable Television Laboratories, Inc. All rights reserved. Any use ##
## of this documentation/package is subject to the terms and conditions of the ##
## CableLabs License provided to you on download of the documentation/package. ##
## ##
######################################################################################
*/
package com.cablelabs.stun.attributes;
import com.cablelabs.stun.StunConstants;
import com.cablelabs.common.*;
/**
* This attribute allows the client to request certain properties for
* the relayed transport address that is allocated by the server. The
* attribute is 32 bits long. Its format is:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prop-type | Reserved = 0 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* The field labeled "Prop-type" is an 8-bit field specifying the
* desired property. The rest of the attribute is RFFU (Reserved For
* Future Use) and MUST be set to 0 on transmission and ignored on
* reception. The values of the "Prop-type" field are:
*
* 0x00 (Reserved)
* 0x01 Even port number
* 0x02 Pair of ports
*
*
* If the value of the "Prop-type" field is 0x01, then the client is
* requesting the server allocate an even-numbered port for the relayed
* transport address.
*
* If the value of the "Prop-type" field is 0x02, then client is
* requesting the server allocate an even-numbered port for the relayed
* transport address, and in addition reserve the next-highest port for
* a subsequent allocation.
*
* All other values of the "Prop-type" field are reserved.
*
*
* @author ghassler
*
*/
public class RequestedProps extends StunAttribute {
public static int DEFAULT_VALUE_SIZE = 4;
public static byte RESERVED = 0x00;
public static byte EVEN_PORT_NUMBER = 0x01;
public static byte PAIR_OF_PORTS = 0x02;
public RequestedProps(char type, byte [] val ) throws IllegalArgumentException {
super(type,val);
}
public RequestedProps(byte [] val) throws IllegalArgumentException {
super(StunConstants.REQUESTED_PROPS_TYPE, val);
}
public RequestedProps(byte val) throws IllegalArgumentException {
super(StunConstants.REQUESTED_PROPS_TYPE, null);
setValue(val);
}
public void setValue(byte [] val) {
length = DEFAULT_VALUE_SIZE;
value = new byte [val.length];
System.arraycopy(val,0, value,0, val.length);
}
public void setValue(byte prop) {
byte [] rffu = new byte [3];
length = DEFAULT_VALUE_SIZE;
value = new byte [DEFAULT_VALUE_SIZE];
value[0] = prop;
System.arraycopy(rffu,0, value,1, rffu.length);
}
public boolean isValidProp() {
if (value != null &&
(value[0] == EVEN_PORT_NUMBER ||
value[0] == PAIR_OF_PORTS)) {
return true;
}
return false;
}
public Byte getProp() {
if (value != null)
return (Byte)value[0];
return null;
}
/**
* This method converts the attribute into a string representation of the
* data.
*/
public String toString() {
String result = " " + StunConstants.getAttributeName(type)
+ "=[" + Conversion.hexString(type)
+ "] valueLen=[" + length
+ "] value=[" + Conversion.hexString(value) + "] padding=[" + padding + "]";
return result;
}
}
|
3e06b17a1354f0dc872a4f8819a7312c7dbe6b48
| 1,296 |
java
|
Java
|
src/main/java/com/sphenon/basics/aspects/AspectsPackageInitialiser.java
|
616c/java-com.sphenon.components.basics.aspects
|
2cd7f9f00019bcb5f860fb34fac2ba1c26f459c6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/sphenon/basics/aspects/AspectsPackageInitialiser.java
|
616c/java-com.sphenon.components.basics.aspects
|
2cd7f9f00019bcb5f860fb34fac2ba1c26f459c6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/sphenon/basics/aspects/AspectsPackageInitialiser.java
|
616c/java-com.sphenon.components.basics.aspects
|
2cd7f9f00019bcb5f860fb34fac2ba1c26f459c6
|
[
"Apache-2.0"
] | null | null | null | 34.105263 | 78 | 0.645833 | 2,849 |
package com.sphenon.basics.aspects;
/****************************************************************************
Copyright 2001-2018 Sphenon GmbH
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.
*****************************************************************************/
import com.sphenon.basics.context.*;
import com.sphenon.basics.context.classes.*;
import com.sphenon.basics.message.*;
import com.sphenon.basics.notification.*;
import com.sphenon.basics.customary.*;
public class AspectsPackageInitialiser {
static protected boolean initialised = false;
static {
initialise(RootContext.getRootContext());
}
static public synchronized void initialise (CallContext context) {
if (initialised == false) {
initialised = true;
}
}
}
|
3e06b32365e5810f03ff57ce52c3855e8da6d45d
| 856 |
java
|
Java
|
src/main/java/co/uk/bigredlobster/password/Password.java
|
bgrdlbstr/password
|
17ad988a01518921113b62065b58bd21e288ec17
|
[
"MIT"
] | null | null | null |
src/main/java/co/uk/bigredlobster/password/Password.java
|
bgrdlbstr/password
|
17ad988a01518921113b62065b58bd21e288ec17
|
[
"MIT"
] | null | null | null |
src/main/java/co/uk/bigredlobster/password/Password.java
|
bgrdlbstr/password
|
17ad988a01518921113b62065b58bd21e288ec17
|
[
"MIT"
] | null | null | null | 27.612903 | 65 | 0.57243 | 2,850 |
package co.uk.bigredlobster.password;
import java.util.ArrayList;
import java.util.List;
public class Password {
public static void main(String[] args) {
Parser parser = new Parser();
List<String> params = parser.doIt(args);
Password p = new Password();
List<String> items = p.doIt(
params.get(0),
Integer.parseInt(params.get(1)) - 1,
Integer.parseInt(params.get(2)) - 1,
Integer.parseInt(params.get(3)) - 1
);
items.forEach(System.out::println);
}
private List<String> doIt(String s, int s1, int s2, int s3) {
List<String> out = new ArrayList<>();
out.add(String.valueOf(s.charAt(s1)));
out.add(String.valueOf(s.charAt(s2)));
out.add(String.valueOf(s.charAt(s3)));
return out;
}
}
|
3e06b60064700d60c245e4819ee3ad098dd4d36c
| 1,920 |
java
|
Java
|
jdbc/src/main/java/com/sonicbase/client/ExecuteStatementHandler.java
|
lowrydale/sonicbase
|
9cf11c46443570a87bc13752c088f497cd6e8923
|
[
"Apache-2.0"
] | 1 |
2018-11-11T14:04:19.000Z
|
2018-11-11T14:04:19.000Z
|
jdbc/src/main/java/com/sonicbase/client/ExecuteStatementHandler.java
|
lowrydale/sonicbase
|
9cf11c46443570a87bc13752c088f497cd6e8923
|
[
"Apache-2.0"
] | 31 |
2020-03-04T22:06:40.000Z
|
2021-12-09T20:27:23.000Z
|
jdbc/src/main/java/com/sonicbase/client/ExecuteStatementHandler.java
|
lowrydale/sonicbase
|
9cf11c46443570a87bc13752c088f497cd6e8923
|
[
"Apache-2.0"
] | 1 |
2018-12-06T01:37:28.000Z
|
2018-12-06T01:37:28.000Z
| 40 | 109 | 0.748438 | 2,851 |
package com.sonicbase.client;
import com.sonicbase.common.ComArray;
import com.sonicbase.common.ComObject;
import com.sonicbase.jdbcdriver.ParameterHandler;
import com.sonicbase.procedure.StoredProcedureContextImpl;
import com.sonicbase.query.DatabaseException;
import com.sonicbase.query.impl.ResultSetImpl;
import com.sonicbase.query.impl.SelectStatementImpl;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.execute.Execute;
import java.util.concurrent.ThreadLocalRandom;
@SuppressWarnings({"squid:S1168", "squid:S00107"})
// I prefer to return null instead of an empty array
// I don't know a good way to reduce the parameter count
public class ExecuteStatementHandler implements StatementHandler {
private final DatabaseClient client;
public ExecuteStatementHandler(DatabaseClient client) {
this.client = client;
}
@Override
public Object execute(String dbName, ParameterHandler parms, String sqlToUse, Statement statement,
SelectStatementImpl.Explain explain, Long sequence0, Long sequence1, Short sequence2,
boolean restrictToThisServer, StoredProcedureContextImpl procedureContext,
int schemaRetryCount) {
Execute execute = (Execute) statement;
if (!"procedure".equalsIgnoreCase((execute.getName()))) {
throw new DatabaseException("invalid execute parameter: parm=" + execute.getName());
}
ComObject cobj = new ComObject(2);
cobj.put(ComObject.Tag.SQL, sqlToUse);
cobj.put(ComObject.Tag.DB_NAME, dbName);
ComObject ret = client.send("DatabaseServer:executeProcedurePrimary",
ThreadLocalRandom.current().nextInt(0, client.getShardCount()), 0, cobj, DatabaseClient.Replica.DEF);
if (ret != null) {
return new ResultSetImpl(client, ret.getArray(ComObject.Tag.RECORDS));
}
return new ResultSetImpl(client, (ComArray) null);
}
}
|
3e06b619ca6cfabea074916d7887443b9527a4e4
| 1,519 |
java
|
Java
|
frule-core/src/main/java/com/bstek/urule/runtime/service/KnowledgeService.java
|
FredGoo/frule
|
9f2073cb36f87ac90ae423fdd538bb8a10ab736d
|
[
"Apache-2.0"
] | 1 |
2018-12-13T09:15:03.000Z
|
2018-12-13T09:15:03.000Z
|
frule-core/src/main/java/com/bstek/urule/runtime/service/KnowledgeService.java
|
FredGoo/frule
|
9f2073cb36f87ac90ae423fdd538bb8a10ab736d
|
[
"Apache-2.0"
] | null | null | null |
frule-core/src/main/java/com/bstek/urule/runtime/service/KnowledgeService.java
|
FredGoo/frule
|
9f2073cb36f87ac90ae423fdd538bb8a10ab736d
|
[
"Apache-2.0"
] | null | null | null | 32.319149 | 80 | 0.653061 | 2,852 |
/*******************************************************************************
* Copyright 2017 Bstek
*
* 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.bstek.urule.runtime.service;
import java.io.IOException;
import com.bstek.urule.runtime.KnowledgePackage;
/**
* @author Jacky.gao
* 2015年1月28日
*/
public interface KnowledgeService {
String BEAN_ID = "urule.knowledgeService";
/**
* 根据给定的资源包ID获取对应的KnowledgePackage对象
*
* @param packageId 资源包ID
* @return 返回与给定的资源包ID获取对应的KnowledgePackage对象
* @throws IOException 抛出IO异常
*/
KnowledgePackage getKnowledge(String packageId) throws IOException;
/**
* 根据给定的一个或多个资源包ID获取对应的KnowledgePackage对象的集合
*
* @param packageIds 资源包ID数组
* @return 返回与给定的一个或多个资源包ID获取对应的KnowledgePackage对象集合
* @throws IOException 抛出IO异常
*/
KnowledgePackage[] getKnowledges(String[] packageIds) throws IOException;
}
|
3e06b635e801d5cc564b9a88c46670e481f8284d
| 4,439 |
java
|
Java
|
view/src/main/java/org/xcolab/view/auth/handlers/AuthenticationSuccessHandler.java
|
paser4se/XCoLab
|
4c777a90369028b0d9a946f83a03db368fa4fc55
|
[
"MIT"
] | 15 |
2015-02-11T04:42:00.000Z
|
2021-05-26T16:24:54.000Z
|
view/src/main/java/org/xcolab/view/auth/handlers/AuthenticationSuccessHandler.java
|
paser4se/XCoLab
|
4c777a90369028b0d9a946f83a03db368fa4fc55
|
[
"MIT"
] | 101 |
2016-03-10T12:25:31.000Z
|
2021-05-25T14:51:47.000Z
|
view/src/main/java/org/xcolab/view/auth/handlers/AuthenticationSuccessHandler.java
|
paser4se/XCoLab
|
4c777a90369028b0d9a946f83a03db368fa4fc55
|
[
"MIT"
] | 10 |
2016-03-09T21:01:07.000Z
|
2020-07-07T01:44:46.000Z
| 44.838384 | 117 | 0.722235 | 2,853 |
package org.xcolab.view.auth.handlers;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.xcolab.client.user.StaticUserContext;
import org.xcolab.client.user.pojo.wrapper.UserWrapper;
import org.xcolab.commons.exceptions.InternalException;
import org.xcolab.entity.utils.LinkUtils;
import org.xcolab.view.auth.AuthenticationService;
import org.xcolab.view.pages.redballoon.utils.BalloonService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import static org.xcolab.view.config.spring.beans.SsoClientConfig.SsoFilter.SSO_SAVED_REFERER_SESSION_ATTRIBUTE;
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private static final Logger log = LoggerFactory.getLogger(AuthenticationSuccessHandler.class);
private final AuthenticationService authenticationService;
private final BalloonService balloonService;
private final boolean allowLogin;
public AuthenticationSuccessHandler(AuthenticationService authenticationService,
BalloonService balloonService, boolean allowLogin) {
this.authenticationService = authenticationService;
this.balloonService = balloonService;
this.allowLogin = allowLogin;
setDefaultTargetUrl("/");
//TODO COLAB-2362: Rethink circular dependency
authenticationService.setAuthenticationSuccessHandler(this);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
onAuthenticationSuccess(request, response, authentication, true);
}
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication, boolean redirectOnSuccess) throws IOException {
final UserWrapper member = authenticationService.getRealMemberOrNull();
if (member == null) {
// This can currently happen when there's an error during SSO
// In that case, the CustomPrincipalExtractor returns null
// An error message will already be saved in an AlertMessage
log.warn("Member was null after authentication: {}", authentication.toString());
getRedirectStrategy().sendRedirect(request, response, "/");
return;
}
if (!allowLogin && !StaticUserContext.getPermissionClient().canAdminAll(member)) {
authenticationService.logout(request, response);
getRedirectStrategy().sendRedirect(request, response, "/loginDisabled");
return;
}
balloonService.associateBalloonTrackingWithUser(request, member);
final HttpSession session = request.getSession();
String refererHeader;
if (session.getAttribute(SSO_SAVED_REFERER_SESSION_ATTRIBUTE) != null) {
refererHeader = (String) session.getAttribute(SSO_SAVED_REFERER_SESSION_ATTRIBUTE);
session.removeAttribute(SSO_SAVED_REFERER_SESSION_ATTRIBUTE);
} else {
refererHeader = request.getHeader(HttpHeaders.REFERER);
}
StaticUserContext.getLoginLogClient().createLoginLog(member.getId(), request.getRemoteAddr(), refererHeader);
if (redirectOnSuccess) {
try {
if (StringUtils.isNotBlank(refererHeader) && !LinkUtils
.isLoginPageLink(refererHeader)) {
//Make URI relative to prevent injection of external redirect URIs
final String redirect = LinkUtils.getSafeRedirectUri(refererHeader);
getRedirectStrategy().sendRedirect(request, response, redirect);
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
} catch (ServletException e) {
// Not reachable - no ServletException is thrown by the implementations
throw new InternalException(e);
}
}
}
}
|
3e06b6774dc4ec2c43b3f3b473cea56aeb471b27
| 2,859 |
java
|
Java
|
java/common/org/linphone/core/PresenceService.java
|
Accontech/linphone
|
60f23ce7845cdaa13f442bb9fa8087336dbfd495
|
[
"BSD-2-Clause"
] | 5 |
2015-11-30T15:03:34.000Z
|
2019-01-13T09:17:17.000Z
|
java/common/org/linphone/core/PresenceService.java
|
Accontech/linphone
|
60f23ce7845cdaa13f442bb9fa8087336dbfd495
|
[
"BSD-2-Clause"
] | 486 |
2015-09-26T01:43:50.000Z
|
2016-05-13T19:14:17.000Z
|
java/common/org/linphone/core/PresenceService.java
|
VTCSecureLLC/ace-iphone
|
de3f71ffc3b9998516b3265c6a074cf74a89a855
|
[
"BSD-2-Clause"
] | 16 |
2015-09-28T13:44:36.000Z
|
2020-05-14T09:29:21.000Z
| 30.094737 | 86 | 0.714586 | 2,854 |
/*
PresenceService.java
Copyright (C) 2010-2013 Belledonne Communications, Grenoble, France
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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.linphone.core;
public interface PresenceService {
/**
* @brief Gets the id of a presence service.
* @return A string containing the id.
*/
String getId();
/**
* @brief Sets the id of a presence service.
* @param[in] id The id string to set. Can be null to generate it automatically.
* @return 0 if successful, a value < 0 in case of error.
*/
int setId(String id);
/**
* @brief Gets the basic status of a presence service.
* @return The #PresenceBasicStatus of the #PresenceService object.
*/
PresenceBasicStatus getBasicStatus();
/**
* @brief Sets the basic status of a presence service.
* @param[in] status The #PresenceBasicStatus to set for the #PresenceService object.
* @return 0 if successful, a value < 0 in case of error.
*/
int setBasicStatus(PresenceBasicStatus status);
/**
* @brief Gets the contact of a presence service.
* @return A string containing the contact, or null if no contact is found.
*/
String getContact();
/**
* @brief Sets the contact of a presence service.
* @param[in] contact The contact string to set.
* @return 0 if successful, a value < 0 in case of error.
*/
int setContact(String contact);
/**
* @brief Gets the number of notes included in the presence service.
* @return The number of notes included in the #PresenceService object.
*/
long getNbNotes();
/**
* @brief Gets the nth note of a presence service.
* @param[in] idx The index of the note to get (the first note having the index 0).
* @return A pointer to a #PresenceNote object if successful, null otherwise.
*/
PresenceNote getNthNote(long idx);
/**
* @brief Adds a note to a presence service.
* @param[in] note The #PresenceNote object to add to the service.
* @return 0 if successful, a value < 0 in case of error.
*/
int addNote(PresenceNote note);
/**
* @brief Clears the notes of a presence service.
* @return 0 if successful, a value < 0 in case of error.
*/
int clearNotes();
/**
* @brief Gets the native pointer for this object.
*/
long getNativePtr();
}
|
3e06b7269f66ea8fc9006a58cf6503eea02ecc1f
| 8,125 |
java
|
Java
|
src/main/java/com/divinity/hlspells/entities/SmartShulkerBolt.java
|
Romulus96/HLSpells
|
65656da15d762c8542b4ed4a307e0cb132a74f9a
|
[
"MIT"
] | null | null | null |
src/main/java/com/divinity/hlspells/entities/SmartShulkerBolt.java
|
Romulus96/HLSpells
|
65656da15d762c8542b4ed4a307e0cb132a74f9a
|
[
"MIT"
] | 2 |
2021-08-09T13:41:54.000Z
|
2021-10-21T00:07:06.000Z
|
src/main/java/com/divinity/hlspells/entities/SmartShulkerBolt.java
|
Romulus96/HLSpells
|
65656da15d762c8542b4ed4a307e0cb132a74f9a
|
[
"MIT"
] | 3 |
2021-07-28T23:34:14.000Z
|
2021-09-23T16:35:08.000Z
| 43.682796 | 224 | 0.589908 | 2,855 |
package com.divinity.hlspells.entities;
import com.google.common.collect.Lists;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.ProjectileHelper;
import net.minecraft.entity.projectile.ShulkerBulletEntity;
import net.minecraft.network.IPacket;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.DamageSource;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.EntityRayTraceResult;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.fml.network.NetworkHooks;
import javax.annotation.Nullable;
import java.util.List;
public class SmartShulkerBolt extends ShulkerBulletEntity {
public SmartShulkerBolt(World world, LivingEntity entity, Entity targetEntity, Direction.Axis direction) {
super(world, entity, targetEntity, direction);
}
@Override
public void tick() {
if (!this.level.isClientSide) {
if (this.finalTarget == null && this.targetId != null) {
this.finalTarget = ((ServerWorld) this.level).getEntity(this.targetId);
if (this.finalTarget == null) {
this.targetId = null;
}
}
if (this.finalTarget == null || !this.finalTarget.isAlive() || this.finalTarget instanceof PlayerEntity && this.finalTarget.isSpectator()) {
if (!this.isNoGravity()) {
this.setDeltaMovement(this.getDeltaMovement().add(0.0D, -0.04D, 0.0D));
}
} else {
this.targetDeltaX = MathHelper.clamp(this.targetDeltaX * 1.025D, -1.0D, 1.0D);
this.targetDeltaY = MathHelper.clamp(this.targetDeltaY * 1.025D, -1.0D, 1.0D);
this.targetDeltaZ = MathHelper.clamp(this.targetDeltaZ * 1.025D, -1.0D, 1.0D);
Vector3d vector3d = this.getDeltaMovement();
this.setDeltaMovement(vector3d.add((this.targetDeltaX - vector3d.x) * 0.5, (this.targetDeltaY - vector3d.y) * 0.5, (this.targetDeltaZ - vector3d.z) * 0.5));
}
RayTraceResult raytraceresult = ProjectileHelper.getHitResult(this, this::canHitEntity);
if (raytraceresult.getType() != RayTraceResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, raytraceresult)) {
this.onHit(raytraceresult);
}
}
this.checkInsideBlocks();
Vector3d vector3d1 = this.getDeltaMovement();
this.setPos(this.getX() + vector3d1.x, this.getY() + vector3d1.y, this.getZ() + vector3d1.z);
ProjectileHelper.rotateTowardsMovement(this, 0.5F);
if (this.level.isClientSide) {
this.level.addParticle(ParticleTypes.HAPPY_VILLAGER, this.getX() - vector3d1.x, this.getY() - vector3d1.y + 0.15D, this.getZ() - vector3d1.z, 0.0D, 0.0D, 0.0D);
} else if (this.finalTarget != null && !this.finalTarget.removed) {
if (this.flightSteps > 0) {
--this.flightSteps;
if (this.flightSteps == 0) {
this.selectNextMoveDirection(this.currentMoveDirection == null ? null : this.currentMoveDirection.getAxis());
}
}
if (this.currentMoveDirection != null) {
BlockPos blockpos = this.blockPosition();
Direction.Axis axis = this.currentMoveDirection.getAxis();
if (this.level.loadedAndEntityCanStandOn(blockpos.relative(this.currentMoveDirection), this)) {
this.selectNextMoveDirection(axis);
} else {
BlockPos blockpos1 = this.finalTarget.blockPosition();
if (axis == Direction.Axis.X && blockpos.getX() == blockpos1.getX() || axis == Direction.Axis.Z && blockpos.getZ() == blockpos1.getZ() || axis == Direction.Axis.Y && blockpos.getY() == blockpos1.getY()) {
this.selectNextMoveDirection(axis);
}
}
}
}
}
@Override
public void selectNextMoveDirection(@Nullable Direction.Axis axis) {
double d0 = 0.5D;
BlockPos blockpos;
if (this.finalTarget == null) {
blockpos = this.blockPosition().below();
} else {
d0 = this.finalTarget.getBbHeight() * 0.5D;
blockpos = new BlockPos(this.finalTarget.getX(), this.finalTarget.getY() + d0, this.finalTarget.getZ());
}
double d1 = blockpos.getX() + 0.5D;
double d2 = blockpos.getY() + d0;
double d3 = blockpos.getZ() + 0.5D;
Direction direction = null;
if (!blockpos.closerThan(this.position(), 2.0D)) {
BlockPos blockpos1 = this.blockPosition();
List<Direction> list = Lists.newArrayList();
if (axis != Direction.Axis.X) {
if (blockpos1.getX() < blockpos.getX() && this.level.isEmptyBlock(blockpos1.east())) {
list.add(Direction.EAST);
} else if (blockpos1.getX() > blockpos.getX() && this.level.isEmptyBlock(blockpos1.west())) {
list.add(Direction.WEST);
}
}
if (axis != Direction.Axis.Y) {
if (blockpos1.getY() < blockpos.getY() && this.level.isEmptyBlock(blockpos1.above())) {
list.add(Direction.UP);
} else if (blockpos1.getY() > blockpos.getY() && this.level.isEmptyBlock(blockpos1.below())) {
list.add(Direction.DOWN);
}
}
if (axis != Direction.Axis.Z) {
if (blockpos1.getZ() < blockpos.getZ() && this.level.isEmptyBlock(blockpos1.south())) {
list.add(Direction.SOUTH);
} else if (blockpos1.getZ() > blockpos.getZ() && this.level.isEmptyBlock(blockpos1.north())) {
list.add(Direction.NORTH);
}
}
direction = Direction.getRandom(this.random);
if (list.isEmpty()) {
for (int i = 1; !this.level.isEmptyBlock(blockpos1.relative(direction)) && i > 0; --i) {
direction = Direction.getRandom(this.random);
}
} else {
direction = list.get(this.random.nextInt(list.size()));
}
d1 = this.getX() + direction.getStepX();
d2 = this.getY() + direction.getStepY();
d3 = this.getZ() + direction.getStepZ();
}
this.setMoveDirection(direction);
double d6 = d1 - this.getX();
double d7 = d2 - this.getY();
double d4 = d3 - this.getZ();
double d5 = MathHelper.sqrt(d6 * d6 + d7 * d7 + d4 * d4);
if (d5 == 0.0D) {
this.targetDeltaX = 0.0D;
this.targetDeltaY = 0.0D;
this.targetDeltaZ = 0.0D;
} else {
this.targetDeltaX = d6 / d5 * 0.38D;
this.targetDeltaY = d7 / d5 * 0.38D;
this.targetDeltaZ = d4 / d5 * 0.38D;
}
this.hasImpulse = true;
this.flightSteps = 10;
}
@Override
public IPacket<?> getAddEntityPacket() {
return NetworkHooks.getEntitySpawningPacket(this);
}
@Override
protected void onHitEntity(EntityRayTraceResult result) {
Entity entity = result.getEntity();
Entity entity1 = this.getOwner();
LivingEntity livingentity = entity1 instanceof LivingEntity ? (LivingEntity) entity1 : null;
if (result.getEntity() == this.getOwner()) {
return;
}
boolean flag = entity.hurt(DamageSource.indirectMobAttack(this, livingentity).setProjectile(), 8.0F);
if (flag) {
this.doEnchantDamageEffects(livingentity, entity);
this.remove();
}
}
}
|
3e06b78799a6a3a307f1ffc9a1cdffe2b3eea925
| 2,315 |
java
|
Java
|
gulimall-product/src/main/java/com/feilong/gulimall/product/controller/CommentReplayController.java
|
FLxmw/gulistop
|
158344db42dff8494ed6edb48a90c9eb5d1f4561
|
[
"Apache-2.0"
] | null | null | null |
gulimall-product/src/main/java/com/feilong/gulimall/product/controller/CommentReplayController.java
|
FLxmw/gulistop
|
158344db42dff8494ed6edb48a90c9eb5d1f4561
|
[
"Apache-2.0"
] | null | null | null |
gulimall-product/src/main/java/com/feilong/gulimall/product/controller/CommentReplayController.java
|
FLxmw/gulistop
|
158344db42dff8494ed6edb48a90c9eb5d1f4561
|
[
"Apache-2.0"
] | null | null | null | 25.777778 | 71 | 0.710345 | 2,856 |
package com.feilong.gulimall.product.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.feilong.gulimall.product.entity.CommentReplayEntity;
import com.feilong.gulimall.product.service.CommentReplayService;
import com.feilong.common.utils.PageUtils;
import com.feilong.common.utils.R;
/**
* 商品评价回复关系
*
* @author xiaomingwang
* @email [email protected]
* @date 2020-11-13 12:45:43
*/
@RestController
@RequestMapping("product/commentreplay")
public class CommentReplayController {
@Autowired
private CommentReplayService commentReplayService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("product:commentreplay:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = commentReplayService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("product:commentreplay:info")
public R info(@PathVariable("id") Long id){
CommentReplayEntity commentReplay = commentReplayService.getById(id);
return R.ok().put("commentReplay", commentReplay);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("product:commentreplay:save")
public R save(@RequestBody CommentReplayEntity commentReplay){
commentReplayService.save(commentReplay);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("product:commentreplay:update")
public R update(@RequestBody CommentReplayEntity commentReplay){
commentReplayService.updateById(commentReplay);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("product:commentreplay:delete")
public R delete(@RequestBody Long[] ids){
commentReplayService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
3e06b885e0f5186a60c7a122061093931800b171
| 21,739 |
java
|
Java
|
src/test/java/com/github/robtimus/obfuscation/support/ObfuscatorUtilsTest.java
|
robtimus/obfuscation-core
|
e173ac0a8c9d0d28435a18165b298406731aa9e0
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/github/robtimus/obfuscation/support/ObfuscatorUtilsTest.java
|
robtimus/obfuscation-core
|
e173ac0a8c9d0d28435a18165b298406731aa9e0
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/com/github/robtimus/obfuscation/support/ObfuscatorUtilsTest.java
|
robtimus/obfuscation-core
|
e173ac0a8c9d0d28435a18165b298406731aa9e0
|
[
"Apache-2.0"
] | null | null | null | 46.851293 | 142 | 0.672018 | 2,857 |
/*
* ObfuscatorUtilsTest.java
* Copyright 2020 Rob Spoor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.robtimus.obfuscation.support;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.append;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.checkIndex;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.checkOffsetAndLength;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.checkStartAndEnd;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.concat;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.copyAll;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.copyTo;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.discardAll;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.getChars;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.indexOf;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.maskAll;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.readAll;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.readAtMost;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.reader;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.repeatChar;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.skipLeadingWhitespace;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.skipTrailingWhitespace;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.wrapArray;
import static com.github.robtimus.obfuscation.support.ObfuscatorUtils.writer;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.DynamicContainer.dynamicContainer;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.Supplier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.DynamicNode;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@SuppressWarnings("nls")
@TestInstance(Lifecycle.PER_CLASS)
class ObfuscatorUtilsTest {
@ParameterizedTest(name = "{1} in {0}[{2}, {3})")
@MethodSource
@DisplayName("indexOf(CharSequence, int, int, int)")
void testIndexOf(String s, int ch, int fromIndex, int toIndex, int expected) {
assertEquals(expected, indexOf(s, ch, fromIndex, toIndex));
assertEquals(expected, indexOf(new StringBuilder(s), ch, fromIndex, toIndex));
}
Arguments[] testIndexOf() {
return new Arguments[] {
arguments("hello", 'l', -1, 10, 2),
arguments("hello", 'l', 10, -1, -1),
arguments("hello", 'l', 0, 5, 2),
arguments("hello", 'l', 5, 0, -1),
arguments("hello", 'l', 3, 5, 3),
arguments("hello", 'l', 0, 2, -1),
arguments("hello", 'x', -1, 10, -1),
arguments("hello", 'x', 0, 5, -1),
arguments("hello", 'x', 3, 5, -1),
arguments("hello", 'x', 0, 2, -1),
};
}
@ParameterizedTest(name = "{0}[{1}, {2})")
@MethodSource
@DisplayName("skipLeadingWhitespace(CharSequence, int, int)")
void testSkipLeadingWhitespace(CharSequence s, int fromIndex, int toIndex, int expected) {
assertEquals(expected, skipLeadingWhitespace(s, fromIndex, toIndex));
}
Arguments[] testSkipLeadingWhitespace() {
return new Arguments[] {
arguments("hello world", 0, 11, 0),
arguments("hello world", 4, 11, 4),
arguments("hello world", 5, 11, 6),
arguments("hello world", 5, 6, 6),
};
}
@ParameterizedTest(name = "{0}[{1}, {2})")
@MethodSource
@DisplayName("skipTrailingWhitespace(CharSequence, int, int)")
void testSkipTrailingWhitespace(CharSequence s, int fromIndex, int toIndex, int expected) {
assertEquals(expected, skipTrailingWhitespace(s, fromIndex, toIndex));
}
Arguments[] testSkipTrailingWhitespace() {
return new Arguments[] {
arguments("hello world", 0, 11, 11),
arguments("hello world", 0, 7, 7),
arguments("hello world", 0, 6, 5),
arguments("hello world", 5, 6, 5),
};
}
@TestFactory
@DisplayName("getChars(CharSequence, int, int, char, int)")
DynamicNode[] testGetChars() {
return new DynamicNode[] {
testGetChars("String", s -> s),
testGetChars("StringBuilder", StringBuilder::new),
testGetChars("StringBuffer", StringBuffer::new),
testGetChars("CharSequence", CharBuffer::wrap),
};
}
private DynamicNode testGetChars(String type, Function<String, CharSequence> constructor) {
String input = "hello world";
DynamicTest[] tests = {
dynamicTest("negative srcBegin", () -> assertThrows(IndexOutOfBoundsException.class,
() -> getChars(constructor.apply(input), -1, input.length(), new char[input.length()], 0))),
dynamicTest("too large srcEnd", () -> assertThrows(IndexOutOfBoundsException.class,
() -> getChars(constructor.apply(input), 0, input.length() + 1, new char[input.length()], 0))),
dynamicTest("srcBegin > srcEnd", () -> assertThrows(IndexOutOfBoundsException.class,
() -> getChars(constructor.apply(input), 1, 0, new char[input.length()], 0))),
dynamicTest("negative dstBegin", () -> assertThrows(IndexOutOfBoundsException.class,
() -> getChars(constructor.apply(input), 0, input.length(), new char[input.length()], -1))),
dynamicTest("too large portion", () -> assertThrows(IndexOutOfBoundsException.class,
() -> getChars(constructor.apply(input), 0, input.length(), new char[input.length()], 1))),
dynamicTest("get all", () -> {
char[] dst = new char[input.length() + 2];
getChars(constructor.apply(input), 0, input.length(), dst, 1);
char[] expected = ('\0' + input + '\0').toCharArray();
assertArrayEquals(expected, dst);
}),
dynamicTest("get some", () -> {
char[] dst = new char[input.length()];
getChars(constructor.apply(input), 1, input.length() - 1, dst, 1);
char[] expected = ('\0' + input.substring(1, input.length() - 1) + '\0').toCharArray();
assertArrayEquals(expected, dst);
}),
};
return dynamicContainer(type, Arrays.asList(tests));
}
@Test
@DisplayName("checkIndex(char[], int)")
void testCheckIndexForCharArray() {
char[] array = "hello world".toCharArray();
checkIndex(array, 0);
assertThrows(IndexOutOfBoundsException.class, () -> checkIndex(array, -1));
assertThrows(IndexOutOfBoundsException.class, () -> checkIndex(array, array.length));
checkIndex(array, array.length - 1);
}
@Test
@DisplayName("checkOffsetAndLength(char[], int, int)")
void testCheckOffsetAndLengthForCharArray() {
char[] array = "hello world".toCharArray();
checkOffsetAndLength(array, 0, array.length);
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(array, -1, array.length));
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(array, 1, -1));
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(array, 0, array.length + 1));
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(array, 1, array.length));
checkOffsetAndLength(array, 1, 0);
}
@Test
@DisplayName("checkStartAndEnd(char[], int, int)")
void testCheckStartAndEndForCharArray() {
char[] array = "hello world".toCharArray();
checkStartAndEnd(array, 0, array.length);
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(array, -1, array.length));
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(array, 1, -1));
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(array, 0, array.length + 1));
checkStartAndEnd(array, 1, array.length);
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(array, 1, 0));
}
@Test
@DisplayName("checkIndex(CharSequence, int)")
void testCheckIndexForCharSequence() {
CharSequence sequence = "hello world";
checkIndex(sequence, 0);
assertThrows(IndexOutOfBoundsException.class, () -> checkIndex(sequence, -1));
assertThrows(IndexOutOfBoundsException.class, () -> checkIndex(sequence, sequence.length()));
checkIndex(sequence, sequence.length() - 1);
}
@Test
@DisplayName("checkOffsetAndLength(CharSequence, int, int)")
void testCheckOffsetAndLengthForCharSequence() {
CharSequence sequence = "hello world";
checkOffsetAndLength(sequence, 0, sequence.length());
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(sequence, -1, sequence.length()));
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(sequence, 1, -1));
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(sequence, 0, sequence.length() + 1));
assertThrows(IndexOutOfBoundsException.class, () -> checkOffsetAndLength(sequence, 1, sequence.length()));
checkOffsetAndLength(sequence, 1, 0);
}
@Test
@DisplayName("checkStartAndEnd(CharSequence, int, int)")
void testCheckStartAndEndForCharSequence() {
CharSequence sequence = "hello world";
checkStartAndEnd(sequence, 0, sequence.length());
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(sequence, -1, sequence.length()));
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(sequence, 1, -1));
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(sequence, 0, sequence.length() + 1));
checkStartAndEnd(sequence, 1, sequence.length());
assertThrows(IndexOutOfBoundsException.class, () -> checkStartAndEnd(sequence, 1, 0));
}
@Test
@DisplayName("wrapArray(char[])")
void testWrapArray() {
assertThat(wrapArray(new char[0]), instanceOf(CharArraySequence.class));
assertThrows(NullPointerException.class, () -> wrapArray(null));
}
@Test
@DisplayName("repeatChar(char, int)")
void testRepeatChar() {
assertThat(repeatChar('*', 1), instanceOf(RepeatingCharSequence.class));
assertThrows(IllegalArgumentException.class, () -> repeatChar('*', -1));
}
@Test
@DisplayName("concat(CharSequence, CharSequence)")
void testConcat() {
assertThat(concat("", ""), instanceOf(ConcatCharSequence.class));
assertThrows(NullPointerException.class, () -> concat(null, ""));
assertThrows(NullPointerException.class, () -> concat("", null));
}
@Test
@DisplayName("reader(CharSequence)")
@SuppressWarnings("resource")
void testReader() {
assertThat(reader(""), instanceOf(CharSequenceReader.class));
assertThrows(NullPointerException.class, () -> reader(null));
}
@Test
@DisplayName("reader(CharSequence, int, int)")
@SuppressWarnings("resource")
void testReaderWithRange() {
CharSequence sequence = "hello world";
assertThat(reader(sequence, 0, sequence.length()), instanceOf(CharSequenceReader.class));
assertThrows(NullPointerException.class, () -> reader(null, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> reader(sequence, -1, sequence.length()));
assertThrows(IndexOutOfBoundsException.class, () -> reader(sequence, 1, -1));
assertThrows(IndexOutOfBoundsException.class, () -> reader(sequence, 0, sequence.length() + 1));
assertThrows(IndexOutOfBoundsException.class, () -> reader(sequence, 1, 0));
}
@Test
@DisplayName("writer(Appendable)")
@SuppressWarnings("resource")
void testWriter() {
Writer writer = new StringWriter();
assertSame(writer, writer(writer));
StringBuilder sb = new StringBuilder();
writer = writer(sb);
assertThat(writer, instanceOf(AppendableWriter.class));
assertThrows(NullPointerException.class, () -> writer(null));
}
@Test
@DisplayName("copyTo(Reader, Appendable)")
@SuppressWarnings("resource")
void testCopyTo() {
assertThat(copyTo(new StringReader(""), new StringBuilder()), instanceOf(CopyingReader.class));
assertThrows(NullPointerException.class, () -> copyTo(null, new StringBuilder()));
assertThrows(NullPointerException.class, () -> copyTo(new StringReader(""), null));
}
@Test
@DisplayName("readAtMost(Reader, int)")
@SuppressWarnings("resource")
void testReadAtMost() {
assertThat(readAtMost(new StringReader(""), 5), instanceOf(LimitReader.class));
assertThrows(NullPointerException.class, () -> readAtMost(null, 5));
assertThrows(IllegalArgumentException.class, () -> readAtMost(new StringReader(""), -1));
}
@Test
@DisplayName("readAll(Reader)")
void testReadAll() throws IOException {
String string = "hello world";
StringReader input = new StringReader(string);
assertEquals(string, readAll(input).toString());
assertEquals(-1, input.read());
}
@Test
@DisplayName("discardAll(Reader)")
void testDiscardAll() throws IOException {
String string = "hello world";
StringReader input = new StringReader(string);
discardAll(input);
assertEquals(-1, input.read());
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("copyAll(Reader, Appendable)")
void testCopyAll(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier) throws IOException {
String string = "hello world";
StringReader input = new StringReader(string);
Appendable destination = destinationSupplier.get();
copyAll(input, destination);
assertEquals(string, destination.toString());
assertEquals(-1, input.read());
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("maskAll(Reader, char, Appendable)")
void testMaskAll(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier) throws IOException {
String string = "hello world";
String expected = string.replaceAll(".", "*");
StringReader input = new StringReader(string);
Appendable destination = destinationSupplier.get();
maskAll(input, '*', destination);
assertEquals(expected, destination.toString());
assertEquals(-1, input.read());
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("append(int)")
void testAppendInt(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier) throws IOException {
int c = 1 << 16 | 'a';
Appendable destination = destinationSupplier.get();
append(c, destination);
assertEquals("a", destination.toString());
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("append(char, int)")
void testAppendRepeated(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier) throws IOException {
char c = '*';
int count = 2048 + 32;
char[] array = new char[count];
Arrays.fill(array, c);
String expected = new String(array);
Appendable destination = destinationSupplier.get();
append(c, 0, destination);
assertEquals("", destination.toString());
append(c, count, destination);
assertEquals(expected, destination.toString());
assertThrows(IllegalArgumentException.class, () -> append(c, -1, destination));
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("append(char[])")
void testAppendCharArray(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier) throws IOException {
String input = "hello world";
char[] array = input.toCharArray();
Appendable destination = destinationSupplier.get();
append(array, destination);
assertEquals(input, destination.toString());
assertThrows(NullPointerException.class, () -> append((char[]) null, destination));
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("append(char[], int, int)")
void testAppendCharArrayRange(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier)
throws IOException {
String input = "hello world";
char[] array = input.toCharArray();
Appendable destination = destinationSupplier.get();
append(array, 5, 5, destination);
assertEquals("", destination.toString());
append(array, 3, 8, destination);
assertEquals(input.substring(3, 8), destination.toString());
assertThrows(NullPointerException.class, () -> append((char[]) null, 0, 0, destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(array, -1, array.length, destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(array, 0, array.length + 1, destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(array, 0, -1, destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(array, array.length + 1, array.length, destination));
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("append(String)")
void testAppendString(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier) throws IOException {
String input = "hello world";
Appendable destination = destinationSupplier.get();
append(input, destination);
assertEquals(input, destination.toString());
assertThrows(NullPointerException.class, () -> append((String) null, destination));
}
@ParameterizedTest(name = "{0}")
@MethodSource("appendableArguments")
@DisplayName("append(String, int, int)")
void testAppendStringRange(@SuppressWarnings("unused") String appendableType, Supplier<Appendable> destinationSupplier)
throws IOException {
String input = "hello world";
Appendable destination = destinationSupplier.get();
append(input, 5, 5, destination);
assertEquals("", destination.toString());
append(input, 3, 8, destination);
assertEquals(input.substring(3, 8), destination.toString());
assertThrows(NullPointerException.class, () -> append((String) null, 0, 0, destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(input, -1, input.length(), destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(input, 0, input.length() + 1, destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(input, 0, -1, destination));
assertThrows(IndexOutOfBoundsException.class, () -> append(input, input.length() + 1, input.length(), destination));
}
Arguments[] appendableArguments() {
return new Arguments[] {
arguments(StringBuilder.class.getSimpleName(), (Supplier<Appendable>) StringBuilder::new),
arguments(StringBuffer.class.getSimpleName(), (Supplier<Appendable>) StringBuffer::new),
arguments(StringWriter.class.getSimpleName(), (Supplier<Appendable>) StringWriter::new),
arguments(Appendable.class.getSimpleName(), (Supplier<Appendable>) TestAppendable::new),
};
}
}
|
3e06b989aeea9db8cada32c0cd56e956a6bf1b28
| 1,240 |
java
|
Java
|
ml-components/ml-linearalg/src/main/java/com/github/chen0040/ml/linearalg/eigens/UT.java
|
chen0040/java-machine-learning-web-api
|
562c861997392b8e50f4ce8405e9a04c340ecb14
|
[
"MIT"
] | 4 |
2018-01-15T10:49:00.000Z
|
2018-12-04T10:01:52.000Z
|
ml-components/ml-linearalg/src/main/java/com/github/chen0040/ml/linearalg/eigens/UT.java
|
chen0040/java-machine-learning-web-api
|
562c861997392b8e50f4ce8405e9a04c340ecb14
|
[
"MIT"
] | null | null | null |
ml-components/ml-linearalg/src/main/java/com/github/chen0040/ml/linearalg/eigens/UT.java
|
chen0040/java-machine-learning-web-api
|
562c861997392b8e50f4ce8405e9a04c340ecb14
|
[
"MIT"
] | 2 |
2018-03-29T10:51:53.000Z
|
2019-02-12T06:16:30.000Z
| 18.787879 | 57 | 0.578226 | 2,858 |
package com.github.chen0040.ml.linearalg.eigens;
import com.github.chen0040.ml.linearalg.Matrix;
import com.github.chen0040.ml.linearalg.Vector;
import java.util.ArrayList;
import java.util.List;
/**
* Created by chen0469 on 10/11/2015 0011.
*/
public class UT {
private Exception error;
private Matrix U;
private Matrix T;
public UT(Exception error){
this.error = error;
}
public UT(Matrix U, Matrix T){
this.U = U;
this.T = T;
}
public Exception getError() {
return error;
}
public void setError(Exception error){
this.error = error;
}
public Matrix getU() {
return U;
}
public Matrix getT() {
return T;
}
public void setU(Matrix U){
this.U = U;
}
public void setT(Matrix T){
this.T = T;
}
public List<Vector> eigenVectors(){
List<Vector> eigenVectors = U.columnVectors();
return eigenVectors;
}
public List<Double> eigenValues(){
List<Double> eigenValues=new ArrayList<Double>();
int n = T.getRowCount();
for(int i=0; i < n; ++i) {
eigenValues.add(T.get(i, i));
}
return eigenValues;
}
}
|
3e06b99c1bf6c6b83ebd938b8465d24b41f42cc9
| 6,833 |
java
|
Java
|
support/cas-server-support-dynamodb-core/src/test/java/org/apereo/cas/dynamodb/DynamoDbTableUtilsTests.java
|
JasonEverling/cas
|
9d5eb3e7dbf34a29f5f69141602b3f83b48353c8
|
[
"Apache-2.0"
] | 4 |
2015-10-31T14:57:03.000Z
|
2020-11-16T01:39:42.000Z
|
support/cas-server-support-dynamodb-core/src/test/java/org/apereo/cas/dynamodb/DynamoDbTableUtilsTests.java
|
Nurran/cas
|
43392ae8eefeb36d44a2b06fdedba589d726f4ae
|
[
"Apache-2.0"
] | 12 |
2020-07-03T06:06:14.000Z
|
2022-01-27T00:37:19.000Z
|
support/cas-server-support-dynamodb-core/src/test/java/org/apereo/cas/dynamodb/DynamoDbTableUtilsTests.java
|
isabella232/cas
|
fc570ef1f0aa6b18817a955c5158e84d35aa201d
|
[
"Apache-2.0"
] | 1 |
2016-06-22T00:54:09.000Z
|
2016-06-22T00:54:09.000Z
| 41.664634 | 114 | 0.719889 | 2,859 |
package org.apereo.cas.dynamodb;
import org.apereo.cas.configuration.model.support.dynamodb.AbstractDynamoDbProperties;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.BillingMode;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ResourceInUseException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.model.TableDescription;
import software.amazon.awssdk.services.dynamodb.model.TableStatus;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* This is {@link DynamoDbTableUtilsTests}.
*
* @author Misagh Moayyed
* @since 6.3.0
*/
@Tag("DynamoDb")
public class DynamoDbTableUtilsTests {
@Test
public void verifyCreateTable() {
val client = mock(DynamoDbClient.class);
when(client.createTable(any(CreateTableRequest.class)))
.thenThrow(ResourceInUseException.create("error", new IllegalArgumentException()));
assertFalse(DynamoDbTableUtils.createTableIfNotExists(client, CreateTableRequest.builder().build()));
}
@Test
public void verifyWaitUntilTable() {
val client = mock(DynamoDbClient.class);
val description = TableDescription.builder().tableStatus(TableStatus.CREATING).build();
val table = DescribeTableResponse.builder().table(description).build();
when(client.describeTable(any(DescribeTableRequest.class))).thenReturn(table);
assertThrows(DynamoDbTableUtils.TableNeverTransitionedToStateException.class,
() -> DynamoDbTableUtils.waitUntilActive(client, "tableName", 1000, 1000));
}
@Test
public void verifyWaitUntilTableNotFound() {
val client = mock(DynamoDbClient.class);
when(client.describeTable(any(DescribeTableRequest.class)))
.thenThrow(ResourceNotFoundException.create("fail", new IllegalArgumentException()));
assertThrows(SdkException.class,
() -> DynamoDbTableUtils.waitUntilActive(client, "tableName", 1000, 1000));
}
@Test
public void verifyCreateTableWithBillingModeProvisioned() {
val client = mock(DynamoDbClient.class);
val readCapacity = 7L;
val writeCapacity = 9L;
val createTableArgMatcher = new CreateTableRequestArgumentMatcher(readCapacity, writeCapacity);
expectCreateTable(client, createTableArgMatcher);
val attributeName = "attr1";
val props = new MinimalTestDynamoDbProperties()
.setBillingMode(AbstractDynamoDbProperties.BillingMode.PROVISIONED)
.setReadCapacity(readCapacity)
.setWriteCapacity(writeCapacity);
val attributeDefinitions = List.of(
AttributeDefinition.builder()
.attributeName(attributeName)
.attributeType(ScalarAttributeType.S).build());
val keySchema = List.of(KeySchemaElement.builder()
.attributeName(attributeName)
.keyType(KeyType.HASH).build());
try {
DynamoDbTableUtils.createTable(client, props, "test-table",
false, attributeDefinitions, keySchema);
} catch (final Exception ex) {
fail("Failed to create table");
}
verify(client).createTable(argThat(createTableArgMatcher));
}
@Test
public void verifyCreateTableWithBillingModePayPerRequest() {
val client = mock(DynamoDbClient.class);
val createTableArgMatcher = new CreateTableRequestArgumentMatcher();
expectCreateTable(client, createTableArgMatcher);
val attributeName = "attr1";
val props = new MinimalTestDynamoDbProperties()
.setBillingMode(AbstractDynamoDbProperties.BillingMode.PAY_PER_REQUEST);
val attributeDefinitions = List.of(
AttributeDefinition.builder().attributeName(attributeName)
.attributeType(ScalarAttributeType.S).build());
val keySchema = List.of(KeySchemaElement.builder().attributeName(attributeName)
.keyType(KeyType.HASH).build());
try {
DynamoDbTableUtils.createTable(client, props, "test-table",
false, attributeDefinitions, keySchema);
} catch (final Exception ex) {
fail("Failed to create table");
}
verify(client).createTable(argThat(createTableArgMatcher));
}
@SuppressWarnings("serial")
static class MinimalTestDynamoDbProperties extends AbstractDynamoDbProperties {
}
static class CreateTableRequestArgumentMatcher implements ArgumentMatcher<CreateTableRequest> {
private long readCapacity;
private long writeCapacity;
CreateTableRequestArgumentMatcher() {
}
CreateTableRequestArgumentMatcher(final long readCapacity, final long writeCapacity) {
this.readCapacity = readCapacity;
this.writeCapacity = writeCapacity;
}
@Override
public boolean matches(final CreateTableRequest createTableRequest) {
if (BillingMode.PAY_PER_REQUEST == createTableRequest.billingMode()) {
return createTableRequest.provisionedThroughput() == null;
}
val provisionedThroughput = createTableRequest.provisionedThroughput();
return provisionedThroughput.readCapacityUnits() == readCapacity
&& provisionedThroughput.writeCapacityUnits() == writeCapacity;
}
}
private void expectCreateTable(final DynamoDbClient client, final CreateTableRequestArgumentMatcher matcher) {
when(client.createTable(argThat(matcher)))
.thenReturn(CreateTableResponse.builder().build());
val description = TableDescription.builder().tableStatus(TableStatus.ACTIVE).build();
val table = DescribeTableResponse.builder().table(description).build();
when(client.describeTable(any(DescribeTableRequest.class))).thenReturn(table);
}
}
|
3e06b9c683b6ba91a25f0452d4cb5de15c2524ce
| 1,057 |
java
|
Java
|
app/src/main/java/com/joshua/escortujs/activity/BaseActivity.java
|
504865348/EscortUJS
|
610e41fa66d2270b51d0b2c55be9cc2d3727b5b7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/joshua/escortujs/activity/BaseActivity.java
|
504865348/EscortUJS
|
610e41fa66d2270b51d0b2c55be9cc2d3727b5b7
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/joshua/escortujs/activity/BaseActivity.java
|
504865348/EscortUJS
|
610e41fa66d2270b51d0b2c55be9cc2d3727b5b7
|
[
"Apache-2.0"
] | 1 |
2017-10-26T11:21:41.000Z
|
2017-10-26T11:21:41.000Z
| 21.571429 | 61 | 0.673605 | 2,860 |
package com.joshua.escortujs.activity;
import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import com.joshua.escortujs.receiver.ExitReceiver;
import org.xutils.x;
public class BaseActivity extends Activity {
private ExitReceiver exitReceiver;
public static String EXIT_APP_ACTION = "com.joshua.exit";
/**
* 注册退出广播
*/
private void registerExitReceiver() {
IntentFilter exitFilter = new IntentFilter();
exitFilter.addAction(EXIT_APP_ACTION);
registerReceiver(exitReceiver, exitFilter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
x.view().inject(this);
exitReceiver = new ExitReceiver();
registerExitReceiver();
}
@Override
protected void onDestroy() {
super.onDestroy();
unRegisterExitReceiver();
}
/**
* 注销退出广播
*/
private void unRegisterExitReceiver() {
unregisterReceiver(exitReceiver);
}
}
|
3e06baaef7243ef1a5c0bd036a525cad72f7122b
| 363 |
java
|
Java
|
src/main/java/science/atlarge/opencraft/opencraft/entity/GlowWaterMob.java
|
atlarge-research/opencraft-opencraft
|
13f9ffa4d50df2268998b1b5ec1a2c236eac09dd
|
[
"MIT"
] | 1 |
2021-01-22T01:24:32.000Z
|
2021-01-22T01:24:32.000Z
|
src/main/java/science/atlarge/opencraft/opencraft/entity/GlowWaterMob.java
|
atlarge-research/opencraft
|
13f9ffa4d50df2268998b1b5ec1a2c236eac09dd
|
[
"MIT"
] | 21 |
2021-03-09T08:33:53.000Z
|
2021-03-09T08:34:34.000Z
|
src/main/java/science/atlarge/opencraft/opencraft/entity/GlowWaterMob.java
|
atlarge-research/opencraft-opencraft
|
13f9ffa4d50df2268998b1b5ec1a2c236eac09dd
|
[
"MIT"
] | 1 |
2022-03-02T12:28:52.000Z
|
2022-03-02T12:28:52.000Z
| 27.923077 | 79 | 0.785124 | 2,861 |
package science.atlarge.opencraft.opencraft.entity;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.WaterMob;
public abstract class GlowWaterMob extends GlowCreature implements WaterMob {
public GlowWaterMob(Location location, EntityType type, double maxHealth) {
super(location, type, maxHealth);
}
}
|
3e06bb6ffde262b10c275aa43c1fad6b413d2ccb
| 1,161 |
java
|
Java
|
app/src/test/java/com/tastybug/timetracker/core/model/rounding/NoRoundingTest.java
|
tastybug/timetracker
|
89733b96a7ad188520b238d2d6069a0750b4c93d
|
[
"Apache-2.0"
] | null | null | null |
app/src/test/java/com/tastybug/timetracker/core/model/rounding/NoRoundingTest.java
|
tastybug/timetracker
|
89733b96a7ad188520b238d2d6069a0750b4c93d
|
[
"Apache-2.0"
] | 11 |
2018-01-07T15:40:49.000Z
|
2018-08-26T09:04:04.000Z
|
app/src/test/java/com/tastybug/timetracker/core/model/rounding/NoRoundingTest.java
|
tastybug/timetracker
|
89733b96a7ad188520b238d2d6069a0750b4c93d
|
[
"Apache-2.0"
] | 1 |
2021-01-05T00:48:29.000Z
|
2021-01-05T00:48:29.000Z
| 24.702128 | 62 | 0.658053 | 2,862 |
package com.tastybug.timetracker.core.model.rounding;
import org.joda.time.Duration;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NoRoundingTest extends AbstractRoundingTestcase {
private NoRounding SUBJECT = new NoRounding();
@Test
public void willRoundUpToFullMinute() {
// given: a duration of 1:10min
Duration duration = getOneMinute10SecondsDuration();
// when
long seconds = SUBJECT.getDurationInSeconds(duration);
// then
assertEquals(70, seconds);
}
@Test
public void underOneMinuteEqualsOneMinute() {
// given: a duration of 10 seconds
Duration duration = get10SecondsDuration();
// when
long seconds = SUBJECT.getDurationInSeconds(duration);
// then
assertEquals(10, seconds);
}
@Test
public void exactlyOneMinuteLeadsToUnalteredResult() {
// given: a duration of 60 seconds
Duration duration = get1MinuteDuration();
// when
long seconds = SUBJECT.getDurationInSeconds(duration);
// then
assertEquals(60, seconds);
}
}
|
3e06bbe94cea030a0d48d46d8001c08289d7e25c
| 403 |
java
|
Java
|
src/main/java/com/codercampus/Assignment11/Assignment11Application.java
|
brunopique/Spring_TransactionsParser
|
433a1e06e835885d261023c9a18a4d2582f2dff8
|
[
"MIT"
] | null | null | null |
src/main/java/com/codercampus/Assignment11/Assignment11Application.java
|
brunopique/Spring_TransactionsParser
|
433a1e06e835885d261023c9a18a4d2582f2dff8
|
[
"MIT"
] | null | null | null |
src/main/java/com/codercampus/Assignment11/Assignment11Application.java
|
brunopique/Spring_TransactionsParser
|
433a1e06e835885d261023c9a18a4d2582f2dff8
|
[
"MIT"
] | null | null | null | 28.785714 | 84 | 0.841191 | 2,863 |
package com.codercampus.Assignment11;
import java.io.IOException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Assignment11Application {
public static void main(String[] args) throws IOException, ClassNotFoundException {
SpringApplication.run(Assignment11Application.class, args);
}
}
|
3e06bc83a82613f7342a46a5700dda95b74754e4
| 1,597 |
java
|
Java
|
OgreJNI_3.3/app/src/main/java/org/ogre/TextureFrameControllerValue.java
|
octopus888/android_ogre1.12.6
|
dc93f53cf047f0167e4ecf258121518b645de7ce
|
[
"MIT"
] | 1 |
2020-07-07T07:09:39.000Z
|
2020-07-07T07:09:39.000Z
|
app/src/main/java/org/ogre/TextureFrameControllerValue.java
|
RobertPoncelet/OGREWallpaper
|
83f8126c168bdbe7ac04887bfb3fa2d7600ff0be
|
[
"MIT"
] | null | null | null |
app/src/main/java/org/ogre/TextureFrameControllerValue.java
|
RobertPoncelet/OGREWallpaper
|
83f8126c168bdbe7ac04887bfb3fa2d7600ff0be
|
[
"MIT"
] | 2 |
2020-07-31T05:58:45.000Z
|
2020-08-12T02:40:35.000Z
| 29.036364 | 120 | 0.651847 | 2,864 |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.8
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.ogre;
public class TextureFrameControllerValue {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;
protected TextureFrameControllerValue(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(TextureFrameControllerValue obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
OgreJNI.delete_TextureFrameControllerValue(swigCPtr);
}
swigCPtr = 0;
}
}
public TextureFrameControllerValue(TextureUnitState t) {
this(OgreJNI.new_TextureFrameControllerValue(TextureUnitState.getCPtr(t), t), true);
}
public static ControllerValueRealPtr create(TextureUnitState t) {
return new ControllerValueRealPtr(OgreJNI.TextureFrameControllerValue_create(TextureUnitState.getCPtr(t), t), true);
}
public float getValue() {
return OgreJNI.TextureFrameControllerValue_getValue(swigCPtr, this);
}
public void setValue(float value) {
OgreJNI.TextureFrameControllerValue_setValue(swigCPtr, this, value);
}
}
|
3e06bcbefb0c94d269946ecc6deda135ebe86eab
| 8,029 |
java
|
Java
|
src/org/uniHD/memory/allocation/LiveObjectMonitoringSampler.java
|
heiqs/leak_injector
|
1616250240e6bb2cbf24524a3852da94f24da25b
|
[
"MIT"
] | 2 |
2019-08-09T12:15:07.000Z
|
2019-08-25T09:37:39.000Z
|
src/org/uniHD/memory/allocation/LiveObjectMonitoringSampler.java
|
heiqs/leak_injector
|
1616250240e6bb2cbf24524a3852da94f24da25b
|
[
"MIT"
] | null | null | null |
src/org/uniHD/memory/allocation/LiveObjectMonitoringSampler.java
|
heiqs/leak_injector
|
1616250240e6bb2cbf24524a3852da94f24da25b
|
[
"MIT"
] | null | null | null | 41.817708 | 251 | 0.740192 | 2,865 |
package org.uniHD.memory.allocation;
import com.google.common.flogger.FluentLogger;
import com.google.common.flogger.LoggerConfig;
import com.google.monitoring.runtime.instrumentation.Sampler;
import com.sun.management.GarbageCollectionNotificationInfo;
import org.uniHD.memory.util.Configuration;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.NotificationListener;
import javax.management.openmbean.CompositeData;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.GarbageCollectorMXBean;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.uniHD.memory.LiveObjectMap.*;
import static sun.misc.Cleaner.create;
/**
* This sampler relies on bytecode instrumentation provided by the java-allocation-instrumenter (Jeremy Manson) to
* hook to java object allocation and object removal.
*
* @author Felix Langner
* @since 10/12/2012
*/
public class LiveObjectMonitoringSampler implements Sampler {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static {
logger.atFine().log("LiveObjectMonitoringSampler created");
}
static Random rand = new Random();
private final Set<String> sourceCodeFiles;
private final Configuration config;
public LiveObjectMonitoringSampler(final String[] sourceFileRootFolders, Configuration configuration) {
sourceCodeFiles = SourceFileCollector.collectSourceFile(sourceFileRootFolders);
config = configuration;
//add handler for garbage collection events
addGcHandler();
logger.atFine().log("LiveObjectMonitoringSampler constructor. Found srcCodeFiles =%s", sourceCodeFiles);
}
/*
* (non-Javadoc)
* @see com.google.monitoring.runtime.instrumentation.Sampler#
* sampleAllocation(int, java.lang.String, java.lang.Object, long)
*/
@Override
public void sampleAllocation(final int count, final String desc, final Object newObj, final long size) {
// identify the source code line responsible for the instantiation of the object on the lowest available level
String allocLocation = null;
final StackTraceElement[] strace = new Exception().getStackTrace();
int idx = 0;
// todo: make the following filter for client-code-only faster, e.g. do not instrument any agent classes (contrary to now)
// The following checks whether any part of the source code paths is contained in one of the stack trace row,
// and if yes, this row is enhanced with corresp. source line number and considered as allocLocation
// todo: fix REAL ERROR! The sourceCodeFiles seem to have only the file name (without pre-directories), but
// strace[idx].getClassName() yields a fully-qualified name. For example, in the following run (see logs),
// the sourceCodeFiles containts only "TestCode" (1 set element), but strace[idx].getClassName()=org.uniHD.test.TestCode
// [FEIN|190810 20:01:17 855] LiveObjectMonitoringSampler constructor. Found srcCodeFiles =[TestCode] [org.uniHD.memory.allocation.LiveObjectMonitoringSampler <init>]
// [FEIN|190810 20:03:27 861] Comparing srcCodeFiles vs. strace[idx].getClassName()=org.uniHD.test.TestCode [CONTEXT ratelimit_period="5000 MILLISECONDS [skipped: 1423743]" ] [org.uniHD.memory.allocation.LiveObjectMonitoringSampler sampleAllocation]
do {
if (sourceCodeFiles.contains(strace[idx].getClassName())) {
allocLocation = strace[idx].getClassName() + ":" + strace[idx].getLineNumber();
break;
} else {
logger.atFine().atMostEvery(5000, TimeUnit.MILLISECONDS).log("Comparing srcCodeFiles vs. strace[idx].getClassName()=%s",
strace[idx].getClassName());
}
} while (++idx < strace.length);
// collect the measured allocation
if (allocLocation != null) {
logger.atFine().atMostEvery(50, TimeUnit.MILLISECONDS).log("**** Found target class: allocLocation=%s, objectID=%s, desc=%s, strack=%s",
allocLocation, toIdentifierString(newObj), desc, strace);
final String objectID = toIdentifierString(newObj);
//System.out.println("objectID:" + objectID);
//System.out.println("allocationSite:" + allocLocation);
//System.out.println("size:" + size);
allocated(objectID, newObj.getClass().getName(), allocLocation, size);
// Following call creates a new PhantomReference (public class Cleaner extends PhantomReference<Object>)
create(newObj, new CleanerRunnable(objectID, allocLocation));
createLeaks(newObj, objectID, allocLocation);
}
}
final static int LEAK_LIST_INIT_CAPACITY = 1000;
static private List<Object> listOfLeaks = new ArrayList<Object>(LEAK_LIST_INIT_CAPACITY);
private void createLeaks(final Object newObj, String objectID, String allocLocation) {
if (! config.injectorOn) return;
if (rand.nextInt(100) > config.injectorLeakRatio) return;
if (config.injectorSelection) {
// Check whether current allocation site is in config.injectorSites
String candidateAllocationSite = allocLocation.toLowerCase();
if (! config.injectorSites.contains(candidateAllocationSite)) {
return;
}
}
// Ready to inject leak: add object to a static array
listOfLeaks.add(newObj);
logger.atFine().atMostEvery(200, TimeUnit.MILLISECONDS).log("Leak created for allocation site= %s and obj= %s, ", allocLocation, newObj);
}
/**
* Method to build a java standard object identifier string from the object's native hash and class.
*
* @param obj
* @return a java standard object identifier.
*/
private final static String toIdentifierString(final Object obj) {
return obj.getClass().getName() + "@0x" + Integer.toHexString(System.identityHashCode(obj));
}
private static void addGcHandler() {
List<GarbageCollectorMXBean> gcs = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gc : gcs) {
NotificationEmitter emitter = (NotificationEmitter) gc;
NotificationListener listener = new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object handback) {
//filter out other events; TODO: maybe increment currentGen only every x minor gcs
//TODO: maybe implement filter instead of filtering here
if(notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)){
//update generation counter stored in LiveObjectMap
incrementCurrentGen();
GarbageCollectionNotificationInfo gcinfo = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
//System.out.println("GC occured; generation " + getCurrentGen() );
//System.out.println("Action executed: " + gcinfo.getGcAction());
//keep counts of full gcs, so know when to execute the detection algorithm
if(gcinfo.getGcAction().equals("end of major GC")){
System.out.println("major GC was executed");
//increments the majorGC-counter and executes leak detection if needed
handleMajorGC();
}
}
}
};
emitter.addNotificationListener(listener, null, null);
}
}
// Artur Andrzejak, Aug 2019:
// The run() method is called automatically, when the corresponding obj becomes "Phantom reachable"
// (i.e. ready to be finalized)
private final static class CleanerRunnable implements Runnable {
private final String objectId;
private final String allocLocation;
private CleanerRunnable(final String objectId, final String allocLocation) {
this.objectId = objectId;
this.allocLocation = allocLocation;
}
/*
* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public final void run() {
try {
finalized(objectId);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
3e06bd8ea4efacdcd850b6d1c68ded048d0c036d
| 3,504 |
java
|
Java
|
src/main/java/edu/umich/its/cpm/StatusEndpoint.java
|
jonespm/ctools-project-migration
|
7e4d38afe68e0a5759a36a38b51ecd9048bffd85
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/edu/umich/its/cpm/StatusEndpoint.java
|
jonespm/ctools-project-migration
|
7e4d38afe68e0a5759a36a38b51ecd9048bffd85
|
[
"Apache-2.0"
] | 162 |
2015-10-01T16:30:24.000Z
|
2020-03-27T04:26:16.000Z
|
src/main/java/edu/umich/its/cpm/StatusEndpoint.java
|
jonespm/ctools-project-migration
|
7e4d38afe68e0a5759a36a38b51ecd9048bffd85
|
[
"Apache-2.0"
] | 13 |
2015-09-21T20:20:16.000Z
|
2018-10-19T20:40:32.000Z
| 36.123711 | 109 | 0.739441 | 2,866 |
package edu.umich.its.cpm;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Properties;
/**
* this is to add a new status end point with application version
* information, and link to external dependencies
*
* @author zqian
*
*/
@PropertySource("file:${catalina.base:/usr/local/ctools/app/ctools/tl}/home/application.properties")
@Component
class StatusEndpoint implements Endpoint<String>, ServletContextAware{
private static ServletContext servletContext = null;
@Autowired
private Environment env;
public String getId() {
return Utils.REPORT_ATTR_STATUS;
}
public boolean isEnabled() {
return true;
}
public boolean isSensitive() {
return true;
}
public String invoke() {
String rv = "";
// Custom logic to build the output
try {
// output the git version, CTools and Box url
HashMap<String, Object> statusMap = new HashMap<String, Object>();
// all information related to GIT build
HashMap<String, Object> buildMap = new HashMap<String, Object>();
// check to see whether there are OpenShift-related environment variables
// which contains the build information
if (env.containsProperty(Utils.OPENSHIFT_BUILD_NAMESPACE))
{
buildMap.put("project", "CTool Project Migration");
buildMap.put(Utils.OPENSHIFT_BUILD_NAMESPACE, (String) env.getProperty(Utils.OPENSHIFT_BUILD_NAMESPACE));
buildMap.put(Utils.OPENSHIFT_BUILD_NAME, (String) env.getProperty(Utils.OPENSHIFT_BUILD_NAME));
buildMap.put(Utils.OPENSHIFT_BUILD_SOURCE, (String) env.getProperty(Utils.OPENSHIFT_BUILD_SOURCE));
buildMap.put(Utils.OPENSHIFT_BUILD_COMMIT, (String) env.getProperty(Utils.OPENSHIFT_BUILD_COMMIT));
}
else
{
// maven build has put the git version information into MANIFEST.MF FILE
Properties props = new Properties();
props.load(servletContext.getResourceAsStream("/META-INF/MANIFEST.MF"));
buildMap.put("project", "CTool Project Migration");
buildMap.put("GIT URL", (String) props.get("git_url"));
buildMap.put("GIT branch", (String) props.get("git_branch"));
buildMap.put("GIT commit", (String) props.get("git_commit"));
buildMap.put("Jenkins Build ID", (String) props.get("build_id"));
buildMap.put("Jenkins Build Number", (String) props.get("build_number"));
buildMap.put("Jenkins Build URL", (String) props.get("build_url"));
buildMap.put("Jenkins Build Tag", (String) props.get("build_tag"));
}
statusMap.put("build", buildMap);
// all external links
HashMap<String, Object> urlMap = new HashMap<String, Object>();
urlMap.put("ping", env.getProperty(Utils.SERVER_URL)+"/status/ping");
urlMap.put("CTools ping", env.getProperty(Utils.SERVER_URL)+"/"+Utils.STATUS_DEPENDENCIES_CTOOLS);
urlMap.put("Box ping", env.getProperty(Utils.SERVER_URL)+"/"+Utils.STATUS_DEPENDENCIES_BOX);
statusMap.put("urls", urlMap);
rv = (new JSONObject(statusMap)).toString();
} catch (Throwable e) {
e.printStackTrace();
}
return rv;
}
public void setServletContext(ServletContext servletContext){
this.servletContext = servletContext;
}
}
|
3e06bdecd799da6ac43d1f7cd63ee85643d64db8
| 1,185 |
java
|
Java
|
integration/spark-common/src/main/java/org/apache/carbondata/spark/exception/ProcessMetaDataException.java
|
santiagomrv/carbondata
|
4dbd0e5e74ff44067bb2c6808a09e947df91607d
|
[
"Apache-2.0"
] | 1 |
2018-02-24T12:03:46.000Z
|
2018-02-24T12:03:46.000Z
|
integration/spark-common/src/main/java/org/apache/carbondata/spark/exception/ProcessMetaDataException.java
|
santiagomrv/carbondata
|
4dbd0e5e74ff44067bb2c6808a09e947df91607d
|
[
"Apache-2.0"
] | null | null | null |
integration/spark-common/src/main/java/org/apache/carbondata/spark/exception/ProcessMetaDataException.java
|
santiagomrv/carbondata
|
4dbd0e5e74ff44067bb2c6808a09e947df91607d
|
[
"Apache-2.0"
] | null | null | null | 43.888889 | 80 | 0.760338 | 2,867 |
/*
* 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.carbondata.spark.exception;
// This exception will be thrown when processMetaData failed in
// Carbon's RunnableCommand
public class ProcessMetaDataException extends MalformedCarbonCommandException {
public ProcessMetaDataException(String dbName, String tableName, String msg) {
super("operation failed for " + dbName + "." + tableName + ": " + msg);
}
}
|
3e06bee28580216236d6e66aa96a3368f10f06fb
| 5,780 |
java
|
Java
|
prediction-k3/src/main/java/org/yinyayun/prediction/k3/bayes/ProbabilityDistribution.java
|
yinyayun/-prediction
|
f7bc3865fbcb6bf34c7d26e2db9f372eb294f469
|
[
"Apache-2.0"
] | 15 |
2017-07-17T06:00:15.000Z
|
2021-12-02T08:43:39.000Z
|
prediction-k3/src/main/java/org/yinyayun/prediction/k3/bayes/ProbabilityDistribution.java
|
yinyayun/-prediction
|
f7bc3865fbcb6bf34c7d26e2db9f372eb294f469
|
[
"Apache-2.0"
] | null | null | null |
prediction-k3/src/main/java/org/yinyayun/prediction/k3/bayes/ProbabilityDistribution.java
|
yinyayun/-prediction
|
f7bc3865fbcb6bf34c7d26e2db9f372eb294f469
|
[
"Apache-2.0"
] | 4 |
2020-04-01T23:09:53.000Z
|
2021-04-04T20:21:41.000Z
| 35.030303 | 114 | 0.680796 | 2,868 |
/**
*
*/
package org.yinyayun.prediction.k3.bayes;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.yinyayun.prediction.preprocess.common.DataSample;
import org.yinyayun.prediction.preprocess.common.DataSet;
/**
* @author yinyayun 概率分布生成
*/
public class ProbabilityDistribution {
private DataSet dataSet;
public ProbabilityDistribution(DataSet dataSet) {
this.dataSet = dataSet;
}
/**
* 输出标签的概率分布
*
*/
public Map<Integer, Float> outPutProbability() {
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (DataSample dataMapper : dataSet.getSamples()) {
Integer count = counts.get(dataMapper.getLabel());
if (count == null) {
count = 0;
}
counts.put(dataMapper.getLabel(), ++count);
}
int dataSize = dataSet.getDataSize();
Map<Integer, Float> probabilitys = new HashMap<Integer, Float>();
for (Entry<Integer, Integer> entry : counts.entrySet()) {
// 拉普拉斯平滑估计
float probability = (entry.getValue() + 1.f) / (dataSize * 1.0f + dataSet.getLabels());
probabilitys.put(entry.getKey(), probability);
}
return probabilitys;
}
/**
* 输入分量的概率分布
*
* @return
*/
public Map<Integer, Float> inputProbability() {
float dataSize = 0;
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (DataSample dataMapper : dataSet.getSamples()) {
int[] inputs = dataMapper.getInput();
for (int input : inputs) {
Integer count = counts.get(input);
if (count == null) {
count = 0;
}
counts.put(input, ++count);
}
dataSize += inputs.length;
}
Map<Integer, Float> probabilitys = new HashMap<Integer, Float>();
for (Entry<Integer, Integer> entry : counts.entrySet()) {
float probability = entry.getValue() / dataSize;
probabilitys.put(entry.getKey(), probability);
}
return probabilitys;
}
/**
* 在指定输出下,对应特征分量的条件概率
*
* @return
*/
public Map<Integer, Map<Integer, float[]>> outPutConditionProbabilitys() {
Map<Integer, Integer> outputCounts = new HashMap<Integer, Integer>();
Map<Integer, Map<Integer, int[]>> outPutConditionCounts = new HashMap<Integer, Map<Integer, int[]>>();
for (DataSample dataMapper : dataSet.getSamples()) {
int out = dataMapper.getLabel();
// 输出标签计数
outputCounts.compute(out, (k, v) -> v == null ? 0 : ++v);
// 输出标签对应每个输入分量的计数
outPutConditionCounts.putIfAbsent(out, new HashMap<Integer, int[]>());
Map<Integer, int[]> inputsCounts = outPutConditionCounts.get(out);
int[] inputs = dataMapper.getInput();
for (int i = 0; i < inputs.length; i++) {
// 每个特征出现在每个位置上的次数
inputsCounts.putIfAbsent(inputs[i], new int[inputs.length]);
int[] inputCount = inputsCounts.get(inputs[i]);
inputCount[i]++;
}
}
Map<Integer, Map<Integer, float[]>> outPutConditionProbabilitys = new HashMap<Integer, Map<Integer, float[]>>();
for (Entry<Integer, Map<Integer, int[]>> entry : outPutConditionCounts.entrySet()) {
int output = entry.getKey();
int outputCount = outputCounts.get(output);
Map<Integer, float[]> inputProbabilitys = new HashMap<Integer, float[]>();
outPutConditionProbabilitys.put(output, inputProbabilitys);
for (Entry<Integer, int[]> inputsEntry : entry.getValue().entrySet()) {
int inputi = inputsEntry.getKey();
int[] inputiCountOnOut = inputsEntry.getValue();
float[] inputiCountOnOutPro = new float[inputiCountOnOut.length];
for (int i = 0; i < inputiCountOnOut.length; i++) {
// 拉普拉斯平滑估计
inputiCountOnOutPro[i] = (inputiCountOnOut[i] + 1.f) / (outputCount * 1.0f + dataSet.getLabels());
}
inputProbabilitys.put(inputi, inputiCountOnOutPro);
}
}
return outPutConditionProbabilitys;
}
/**
* 在指定输出下,对应特征分量的条件概率
*
* @return
*/
public Map<Integer, Map<Integer, float[]>> outPutConditionProbabilitys2() {
Map<Integer, Integer> outputCounts = new HashMap<Integer, Integer>();
// label->pos->inputs
Map<Integer, Map<Integer, int[]>> outPutConditionCounts = new HashMap<Integer, Map<Integer, int[]>>();
for (DataSample dataMapper : dataSet.getSamples()) {
int out = dataMapper.getLabel();
// 输出标签计数
outputCounts.compute(out, (k, v) -> v == null ? 0 : ++v);
// 输出标签对应每个输入分量的计数
outPutConditionCounts.putIfAbsent(out, new HashMap<Integer, int[]>());
Map<Integer, int[]> inputsCounts = outPutConditionCounts.get(out);
int[] inputs = dataMapper.getInput();
for (int i = 0; i < inputs.length; i++) {
// 每个特征出现在每个位置上的次数
inputsCounts.putIfAbsent(i, new int[dataSet.getLabels()]);
inputsCounts.get(i)[inputs[i] - dataSet.getMinLabelValue()]++;
}
}
Map<Integer, Map<Integer, float[]>> outPutConditionProbabilitys = new HashMap<Integer, Map<Integer, float[]>>();
for (Entry<Integer, Map<Integer, int[]>> entry : outPutConditionCounts.entrySet()) {
int output = entry.getKey();
int outputCount = outputCounts.get(output);
// pos->inputcount
Map<Integer, float[]> posInputsProbabilitys = new HashMap<Integer, float[]>();
outPutConditionProbabilitys.put(output, posInputsProbabilitys);
for (Entry<Integer, int[]> inputsEntry : entry.getValue().entrySet()) {
int pos = inputsEntry.getKey();
int[] inputCounts = inputsEntry.getValue();
float[] inputProbabilitysOnCurrentPos = new float[dataSet.getLabels()];
for (int i = 0; i < inputProbabilitysOnCurrentPos.length; i++) {
inputProbabilitysOnCurrentPos[i] = inputCounts[i] / (outputCount * 1.0f);
}
posInputsProbabilitys.put(pos, inputProbabilitysOnCurrentPos);
}
for (Entry<Integer, float[]> inputProbabilityEntry : posInputsProbabilitys.entrySet()) {
float all = 0f;
for (float f : inputProbabilityEntry.getValue())
all += f;
System.out.println(all);
}
}
return outPutConditionProbabilitys;
}
}
|
3e06bf666d7d0ef38a2c4d2d2db207e511214439
| 3,807 |
java
|
Java
|
src/main/java/at/boisgard/thesis/datasetconverter/ThesisDatasetConverterApplication.java
|
nathaniel-boisgard/thesis-data-converter
|
2558148772256c4e331c3fa23b500fc60816381d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/at/boisgard/thesis/datasetconverter/ThesisDatasetConverterApplication.java
|
nathaniel-boisgard/thesis-data-converter
|
2558148772256c4e331c3fa23b500fc60816381d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/at/boisgard/thesis/datasetconverter/ThesisDatasetConverterApplication.java
|
nathaniel-boisgard/thesis-data-converter
|
2558148772256c4e331c3fa23b500fc60816381d
|
[
"Apache-2.0"
] | null | null | null | 34.609091 | 135 | 0.730234 | 2,869 |
package at.boisgard.thesis.datasetconverter;
import at.boisgard.thesis.datasetconverter.builder.BaseBuilder;
import at.boisgard.thesis.datasetconverter.converter.CoreNLPConverter;
import at.boisgard.thesis.datasetconverter.converter.LuisConverter;
import at.boisgard.thesis.datasetconverter.converter.RasaConverter;
import at.boisgard.thesis.datasetconverter.converter.WatsonConverter;
import at.boisgard.thesis.datasetconverter.converter.WitaiConverter;
import java.io.IOException;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ComponentScan
@Configuration
@EnableAutoConfiguration
@SpringBootApplication
public class ThesisDatasetConverterApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(ThesisDatasetConverterApplication.class);
@Autowired
private BaseBuilder baseBuilder;
@PostConstruct
public void createLUISData() {
LOGGER.info("Converting {} Utterances to LUIS format", baseBuilder.utterances.size());
LuisConverter lConverter = new LuisConverter(baseBuilder.utterances, baseBuilder.language);
int nOfFiles = lConverter.convert();
LOGGER.info("Done creating {} LUIS Intents in {} files", lConverter.utterances.size(), nOfFiles);
}
@PostConstruct
public void createRasaData() {
LOGGER.info("Converting {} Utterances to rasa format", baseBuilder.utterances.size());
RasaConverter rConverter = new RasaConverter(baseBuilder.utterances, baseBuilder.language);
try {
rConverter.convert();
LOGGER.info("Done creating {} rasa Intents including {} SynSets", rConverter.utterances.size(), rConverter.synSets.size());
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
@PostConstruct
public void createWitAiData() {
LOGGER.info("Converting {} Utterances to wit.ai format", baseBuilder.utterancesIncludingSynonyms.size());
WitaiConverter wConverter = new WitaiConverter(baseBuilder.utterancesIncludingSynonyms, baseBuilder.language);
wConverter.convert();
LOGGER.info("Done creating {} wit.ai training examples", wConverter.utterances.size());
}
@PostConstruct
public void createCoreNLPData() {
LOGGER.info("Converting {} Utterances to coreNLP format", baseBuilder.utterancesIncludingSynonyms.size());
CoreNLPConverter cConverter = new CoreNLPConverter(baseBuilder.utterancesIncludingSynonyms, baseBuilder.language);
try {
cConverter.convert();
LOGGER.info("Done creating {} coreNLP NER training examples", cConverter.utterances.size());
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
@PostConstruct
public void createWatsonData() {
LOGGER.info("Converting {} Utterances to Watson format", baseBuilder.utterances.size());
WatsonConverter wConverter = new WatsonConverter(baseBuilder.utterances, baseBuilder.language);
try {
wConverter.convert();
LOGGER.info("Done creating {} Watson training examples", wConverter.utterances.size());
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
public static void main(String[] args) {
SpringApplication.run(ThesisDatasetConverterApplication.class, args).close();
}
}
|
3e06bf7296d8e30f1e5a8f7ddc3ee69915822ba4
| 10,221 |
java
|
Java
|
gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/actions/MoveMobileSystemUsingHyperspeedAction.java
|
stevetotheizz0/gemp-swccg-public
|
05529086de91ecb03807fda820d98ec8a1465246
|
[
"MIT"
] | 19 |
2020-08-30T18:44:38.000Z
|
2022-02-10T18:23:49.000Z
|
gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/actions/MoveMobileSystemUsingHyperspeedAction.java
|
stevetotheizz0/gemp-swccg-public
|
05529086de91ecb03807fda820d98ec8a1465246
|
[
"MIT"
] | 480 |
2020-09-11T00:19:27.000Z
|
2022-03-31T19:46:37.000Z
|
gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/actions/MoveMobileSystemUsingHyperspeedAction.java
|
stevetotheizz0/gemp-swccg-public
|
05529086de91ecb03807fda820d98ec8a1465246
|
[
"MIT"
] | 21 |
2020-08-29T16:19:44.000Z
|
2022-03-29T01:37:39.000Z
| 52.685567 | 223 | 0.505332 | 2,870 |
package com.gempukku.swccgo.cards.actions;
import com.gempukku.swccgo.cards.effects.PayMoveUsingHyperspeedCostEffect;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.game.state.GameState;
import com.gempukku.swccgo.logic.GameUtils;
import com.gempukku.swccgo.logic.actions.AbstractTopLevelRuleAction;
import com.gempukku.swccgo.logic.decisions.MultipleChoiceAwaitingDecision;
import com.gempukku.swccgo.logic.effects.MoveMobileSystemUsingHyperspeedEffect;
import com.gempukku.swccgo.logic.effects.PlayoutDecisionEffect;
import com.gempukku.swccgo.logic.effects.choose.ChooseCardOnTableEffect;
import com.gempukku.swccgo.logic.timing.Action;
import com.gempukku.swccgo.logic.timing.Effect;
import com.gempukku.swccgo.logic.timing.StandardEffect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* An action to move a mobile system using hyperspeed.
*/
public class MoveMobileSystemUsingHyperspeedAction extends AbstractTopLevelRuleAction {
private PhysicalCard _cardToMove;
private boolean _forFree;
private PhysicalCard _oldOrbit;
private int _oldParsec;
private PlayoutDecisionEffect _chooseParsecEffect;
private int _newParsec;
private boolean _parsecChosen;
private PlayoutDecisionEffect _chooseDeepSpaceOrOrbitEffect;
private boolean _deepSpaceOrOrbitChosen;
private StandardEffect _chooseSystemEffect;
private PhysicalCard _systemToOrbit;
private boolean _systemToOrbitChosen;
private boolean _useForceCostApplied;
private Effect _moveMobileSystemEffect;
private boolean _mobileSystemMoved;
private Action _that;
/**
* Creates an action to move a mobile system using hyperspeed.
* @param playerId the player
* @param game the game
* @param card the starship to move
* @param forFree true if moving for free, otherwise false
*/
public MoveMobileSystemUsingHyperspeedAction(String playerId, final SwccgGame game, final PhysicalCard card, boolean forFree) {
super(card, playerId);
_cardToMove = card;
_forFree = forFree;
_that = this;
final GameState gameState = game.getGameState();
_oldParsec = card.getParsec();
if (_cardToMove.getSystemOrbited() != null) {
_oldOrbit = Filters.findFirstFromTopLocationsOnTable(game, Filters.isOrbitedBy(card));
}
int hyperspeed = (int) game.getModifiersQuerying().getHyperspeed(gameState, card);
List<String> validParsecToMoveTo = new ArrayList<String>();
for (int i = Math.max(0, _oldParsec - hyperspeed); i <= Math.min(99, _oldParsec + hyperspeed); ++i) {
if (i != _oldParsec
|| _oldOrbit != null
|| Filters.canSpotFromTopLocationsOnTable(game, Filters.and(Filters.not(card), Filters.systemAtParsec(i)))) {
validParsecToMoveTo.add(String.valueOf(i));
}
}
String[] parsecs = validParsecToMoveTo.toArray(new String[validParsecToMoveTo.size()]);
_chooseParsecEffect = new PlayoutDecisionEffect(_that, getPerformingPlayer(),
new MultipleChoiceAwaitingDecision("Choose parsec to move to ", parsecs) {
@Override
protected void validDecisionMade(int index, String result) {
_newParsec = Integer.valueOf(result);
// Check if the mobile system can orbit another system (other than one it is already orbiting) at the chosen parsec
final Collection<PhysicalCard> validToOrbit = Filters.filterTopLocationsOnTable(game,
Filters.and(Filters.not(card), Filters.systemAtParsec(_newParsec), Filters.not(Filters.isOrbitedBy(card))));
if (validToOrbit.isEmpty()) {
_deepSpaceOrOrbitChosen = true;
_systemToOrbit = null;
_systemToOrbitChosen = true;
_moveMobileSystemEffect = new MoveMobileSystemUsingHyperspeedEffect(_that, _cardToMove, _oldParsec, _oldOrbit, _newParsec, null);
}
// Check if mobile system is moving from deep space to the same parsec and only one system to orbit
else if ((_oldParsec == _newParsec && _oldOrbit == null) && validToOrbit.size() == 1) {
_deepSpaceOrOrbitChosen = true;
_systemToOrbit = validToOrbit.iterator().next();
_systemToOrbitChosen = true;
_moveMobileSystemEffect = new MoveMobileSystemUsingHyperspeedEffect(_that, _cardToMove, _oldParsec, _oldOrbit, _newParsec, _systemToOrbit);
}
else {
// Ask if mobile system should orbit a system or be in deep space
String[] destinations;
if (validToOrbit.size() == 1)
destinations = new String[]{"Deep Space", "Orbit " + validToOrbit.iterator().next().getBlueprint().getTitle()};
else
destinations = new String[]{"Deep Space", "Orbit a system"};
_chooseDeepSpaceOrOrbitEffect = new PlayoutDecisionEffect(_that, getPerformingPlayer(),
new MultipleChoiceAwaitingDecision("Choose destination for " + GameUtils.getCardLink(_cardToMove) + " at parsec " + _newParsec, destinations) {
@Override
protected void validDecisionMade(int index, String result) {
if (index == 0) {
_systemToOrbit = null;
_systemToOrbitChosen = true;
_moveMobileSystemEffect = new MoveMobileSystemUsingHyperspeedEffect(_that, _cardToMove, _oldParsec, _oldOrbit, _newParsec, null);
}
else {
// Choose a system to orbit
_chooseSystemEffect =
new ChooseCardOnTableEffect(_that, getPerformingPlayer(), "Choose system for " + GameUtils.getFullName(_cardToMove) + " to orbit", validToOrbit) {
@Override
protected void cardSelected(PhysicalCard selectedCard) {
_systemToOrbit = selectedCard;
_moveMobileSystemEffect = new MoveMobileSystemUsingHyperspeedEffect(_that, _cardToMove, _oldParsec, _oldOrbit, _newParsec, _systemToOrbit);
}
};
}
}
}
);
}
}
}
);
}
@Override
public String getText() {
return "Move using hyperspeed";
}
@Override
public Effect nextEffect(SwccgGame game) {
if (!isAnyCostFailed()) {
Effect cost = getNextCost();
if (cost != null)
return cost;
if (!_parsecChosen) {
_parsecChosen = true;
appendCost(_chooseParsecEffect);
return getNextCost();
}
if (!_deepSpaceOrOrbitChosen) {
_deepSpaceOrOrbitChosen = true;
appendCost(_chooseDeepSpaceOrOrbitEffect);
return getNextCost();
}
if (!_systemToOrbitChosen) {
_systemToOrbitChosen = true;
appendCost(_chooseSystemEffect);
return getNextCost();
}
if (!_useForceCostApplied) {
_useForceCostApplied = true;
if (!_forFree) {
appendCost(new PayMoveUsingHyperspeedCostEffect(_that, getPerformingPlayer(), _cardToMove, null, false, 0));
return getNextCost();
}
}
if (!_mobileSystemMoved) {
_mobileSystemMoved = true;
return _moveMobileSystemEffect;
}
Effect effect = getNextEffect();
if (effect != null)
return effect;
}
return null;
}
@Override
public boolean wasActionCarriedOut() {
return _mobileSystemMoved && _moveMobileSystemEffect.wasCarriedOut();
}
}
|
3e06bf9c85c9319855a72e10464f99620d5a1114
| 4,962 |
java
|
Java
|
aliyun-java-sdk-vpc-v5/src/main/java/com/aliyuncs/v5/vpc/model/v20160428/DescribeVpcsRequest.java
|
aliyun/aliyun-openapi-java-sdk-v5
|
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
|
[
"Apache-2.0"
] | 4 |
2020-05-14T05:04:30.000Z
|
2021-08-20T11:08:46.000Z
|
aliyun-java-sdk-vpc-v5/src/main/java/com/aliyuncs/v5/vpc/model/v20160428/DescribeVpcsRequest.java
|
aliyun/aliyun-openapi-java-sdk-v5
|
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
|
[
"Apache-2.0"
] | 2 |
2020-10-13T07:47:10.000Z
|
2021-06-04T02:42:57.000Z
|
aliyun-java-sdk-vpc-v5/src/main/java/com/aliyuncs/v5/vpc/model/v20160428/DescribeVpcsRequest.java
|
aliyun/aliyun-openapi-java-sdk-v5
|
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
|
[
"Apache-2.0"
] | null | null | null | 23.516588 | 121 | 0.716647 | 2,871 |
/*
* 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.aliyuncs.v5.vpc.model.v20160428;
import com.aliyuncs.v5.RpcAcsRequest;
import com.aliyuncs.v5.http.MethodType;
import com.aliyuncs.v5.vpc.Endpoint;
/**
* @author auto create
* @version
*/
public class DescribeVpcsRequest extends RpcAcsRequest<DescribeVpcsResponse> {
private Long resourceOwnerId;
private Long vpcOwnerId;
private Integer pageNumber;
private String vpcName;
private String resourceGroupId;
private Integer pageSize;
private Boolean isDefault;
private Boolean dryRun;
private String dhcpOptionsSetId;
private String resourceOwnerAccount;
private String ownerAccount;
private Long ownerId;
private String vpcId;
public DescribeVpcsRequest() {
super("Vpc", "2016-04-28", "DescribeVpcs", "vpc");
setMethod(MethodType.POST);
try {
com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public Long getResourceOwnerId() {
return this.resourceOwnerId;
}
public void setResourceOwnerId(Long resourceOwnerId) {
this.resourceOwnerId = resourceOwnerId;
if(resourceOwnerId != null){
putQueryParameter("ResourceOwnerId", resourceOwnerId.toString());
}
}
public Long getVpcOwnerId() {
return this.vpcOwnerId;
}
public void setVpcOwnerId(Long vpcOwnerId) {
this.vpcOwnerId = vpcOwnerId;
if(vpcOwnerId != null){
putQueryParameter("VpcOwnerId", vpcOwnerId.toString());
}
}
public Integer getPageNumber() {
return this.pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
if(pageNumber != null){
putQueryParameter("PageNumber", pageNumber.toString());
}
}
public String getVpcName() {
return this.vpcName;
}
public void setVpcName(String vpcName) {
this.vpcName = vpcName;
if(vpcName != null){
putQueryParameter("VpcName", vpcName);
}
}
public String getResourceGroupId() {
return this.resourceGroupId;
}
public void setResourceGroupId(String resourceGroupId) {
this.resourceGroupId = resourceGroupId;
if(resourceGroupId != null){
putQueryParameter("ResourceGroupId", resourceGroupId);
}
}
public Integer getPageSize() {
return this.pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
if(pageSize != null){
putQueryParameter("PageSize", pageSize.toString());
}
}
public Boolean getIsDefault() {
return this.isDefault;
}
public void setIsDefault(Boolean isDefault) {
this.isDefault = isDefault;
if(isDefault != null){
putQueryParameter("IsDefault", isDefault.toString());
}
}
public Boolean getDryRun() {
return this.dryRun;
}
public void setDryRun(Boolean dryRun) {
this.dryRun = dryRun;
if(dryRun != null){
putQueryParameter("DryRun", dryRun.toString());
}
}
public String getDhcpOptionsSetId() {
return this.dhcpOptionsSetId;
}
public void setDhcpOptionsSetId(String dhcpOptionsSetId) {
this.dhcpOptionsSetId = dhcpOptionsSetId;
if(dhcpOptionsSetId != null){
putQueryParameter("DhcpOptionsSetId", dhcpOptionsSetId);
}
}
public String getResourceOwnerAccount() {
return this.resourceOwnerAccount;
}
public void setResourceOwnerAccount(String resourceOwnerAccount) {
this.resourceOwnerAccount = resourceOwnerAccount;
if(resourceOwnerAccount != null){
putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
}
public String getOwnerAccount() {
return this.ownerAccount;
}
public void setOwnerAccount(String ownerAccount) {
this.ownerAccount = ownerAccount;
if(ownerAccount != null){
putQueryParameter("OwnerAccount", ownerAccount);
}
}
public Long getOwnerId() {
return this.ownerId;
}
public void setOwnerId(Long ownerId) {
this.ownerId = ownerId;
if(ownerId != null){
putQueryParameter("OwnerId", ownerId.toString());
}
}
public String getVpcId() {
return this.vpcId;
}
public void setVpcId(String vpcId) {
this.vpcId = vpcId;
if(vpcId != null){
putQueryParameter("VpcId", vpcId);
}
}
@Override
public Class<DescribeVpcsResponse> getResponseClass() {
return DescribeVpcsResponse.class;
}
}
|
3e06bf9ce3c2236ecb8ed92d0a851619c8e9c46c
| 1,412 |
java
|
Java
|
src/util/BinaryUtil.java
|
utarwyn/crypto-a51
|
5b46fbd85f851a78befe485c0426c24c8352e86c
|
[
"MIT"
] | 1 |
2021-01-13T16:10:31.000Z
|
2021-01-13T16:10:31.000Z
|
src/util/BinaryUtil.java
|
utarwyn/crypto-a51
|
5b46fbd85f851a78befe485c0426c24c8352e86c
|
[
"MIT"
] | null | null | null |
src/util/BinaryUtil.java
|
utarwyn/crypto-a51
|
5b46fbd85f851a78befe485c0426c24c8352e86c
|
[
"MIT"
] | 1 |
2021-04-08T14:19:29.000Z
|
2021-04-08T14:19:29.000Z
| 27.153846 | 93 | 0.569405 | 2,872 |
package util;
import java.util.BitSet;
public class BinaryUtil {
private BinaryUtil() {
}
public static BitSet[] bytesToBitSets(byte[] values) {
BitSet[] bitSet = new BitSet[values.length];
for (int i = 0; i < values.length; i++) {
bitSet[i] = getBitSet(values[i] == 1);
}
return bitSet;
}
public static BitSet getBitSet(boolean value) {
BitSet bitSet = new BitSet(1);
bitSet.set(0, value);
return bitSet;
}
public static String bitSetArrayToString(BitSet[] arr) {
StringBuilder sb = new StringBuilder();
for (BitSet bitSet : arr) {
sb.append(bitSet.get(0) ? 1 : 0);
}
return sb.toString();
}
public static String stringToBinary(String message) {
StringBuilder result = new StringBuilder();
for (char c : message.toCharArray()) {
result.append(String.format("%8s", Integer.toBinaryString(c)).replace(' ', '0'));
}
return result.toString();
}
public static String binaryToString(String binary) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < binary.length(); i += 8) {
String temp = binary.substring(i, i + 8);
int number = Integer.parseInt(temp, 2);
result.append((char) number);
}
return result.toString();
}
}
|
3e06bfcda54cf87e976ec028a1c7962d5fe2af15
| 3,264 |
java
|
Java
|
modules/core/src/main/java/org/apache/ignite/spi/loadbalancing/roundrobin/RoundRobinPerTaskLoadBalancer.java
|
liyuj/gridgain
|
9505c0cfd7235210993b2871b17f15acf7d3dcd4
|
[
"CC0-1.0"
] | 218 |
2015-01-04T13:20:55.000Z
|
2022-03-28T05:28:55.000Z
|
modules/core/src/main/java/org/apache/ignite/spi/loadbalancing/roundrobin/RoundRobinPerTaskLoadBalancer.java
|
liyuj/gridgain
|
9505c0cfd7235210993b2871b17f15acf7d3dcd4
|
[
"CC0-1.0"
] | 175 |
2015-02-04T23:16:56.000Z
|
2022-03-28T18:34:24.000Z
|
modules/core/src/main/java/org/apache/ignite/spi/loadbalancing/roundrobin/RoundRobinPerTaskLoadBalancer.java
|
liyuj/gridgain
|
9505c0cfd7235210993b2871b17f15acf7d3dcd4
|
[
"CC0-1.0"
] | 93 |
2015-01-06T20:54:23.000Z
|
2022-03-31T08:09:00.000Z
| 31.085714 | 102 | 0.601103 | 2,873 |
/*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-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.ignite.spi.loadbalancing.roundrobin;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.ignite.cluster.ClusterNode;
/**
* Load balancer for per-task configuration.
*/
class RoundRobinPerTaskLoadBalancer {
/** Balancing nodes. */
private ArrayDeque<ClusterNode> nodeQueue;
/** Jobs mapped flag. */
private volatile boolean isMapped;
/** Mutex. */
private final Object mux = new Object();
/**
* Call back for job mapped event.
*/
void onMapped() {
isMapped = true;
}
/**
* Gets balanced node for given topology. This implementation
* is to be used only from {@link org.apache.ignite.compute.ComputeTask#map(List, Object)} method
* and, therefore, does not need to be thread-safe.
*
* @param top Topology to pick from.
* @return Best balanced node.
*/
ClusterNode getBalancedNode(List<ClusterNode> top) {
assert top != null;
assert !top.isEmpty();
boolean readjust = isMapped;
synchronized (mux) {
// Populate first time.
if (nodeQueue == null)
nodeQueue = new ArrayDeque<>(top);
// If job has been mapped, then it means
// that it is most likely being failed over.
// In this case topology might have changed
// and we need to readjust with every apply.
if (readjust)
// Add missing nodes.
for (ClusterNode node : top)
if (!nodeQueue.contains(node))
nodeQueue.offer(node);
ClusterNode next = nodeQueue.poll();
// If jobs have been mapped, we need to make sure
// that queued node is still in topology.
if (readjust && next != null) {
while (!top.contains(next) && !nodeQueue.isEmpty())
next = nodeQueue.poll();
// No nodes found and queue is empty.
if (next != null && !top.contains(next))
return null;
}
if (next != null)
// Add to the end.
nodeQueue.offer(next);
return next;
}
}
/**
* THIS METHOD IS USED ONLY FOR TESTING.
*
* @return Internal list of nodes.
*/
List<ClusterNode> getNodes() {
synchronized (mux) {
return Collections.unmodifiableList(new ArrayList<>(nodeQueue));
}
}
}
|
3e06c071168e46d0f2d344c2d4eb02160bcb0ece
| 285 |
java
|
Java
|
src/main/java/com/bowlingsystem/bowlingsystem/model/service/set/PlayerSetHistoryDataRepository.java
|
shiwangikashyap/bowling_system
|
e4c5eb25f148c64bae4dc087e707a6c663e5fa5f
|
[
"MIT"
] | 1 |
2021-03-18T01:50:07.000Z
|
2021-03-18T01:50:07.000Z
|
src/main/java/com/bowlingsystem/bowlingsystem/model/service/set/PlayerSetHistoryDataRepository.java
|
shiwangikashyap/bowling_system
|
e4c5eb25f148c64bae4dc087e707a6c663e5fa5f
|
[
"MIT"
] | null | null | null |
src/main/java/com/bowlingsystem/bowlingsystem/model/service/set/PlayerSetHistoryDataRepository.java
|
shiwangikashyap/bowling_system
|
e4c5eb25f148c64bae4dc087e707a6c663e5fa5f
|
[
"MIT"
] | null | null | null | 28.5 | 95 | 0.85614 | 2,874 |
package com.bowlingsystem.bowlingsystem.model.service.set;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PlayerSetHistoryDataRepository extends JpaRepository<PlayerSetHistory,Long> {
}
|
3e06c0a8dd668d1c36e3a75a849ec913b4cfc009
| 533 |
java
|
Java
|
src/ffhs/swea/client/Main.java
|
reecube/ffhs-swea-snake-multiplayer
|
7c39ec10b8c40122f34fe57e11d6a1ba49226eb5
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/ffhs/swea/client/Main.java
|
reecube/ffhs-swea-snake-multiplayer
|
7c39ec10b8c40122f34fe57e11d6a1ba49226eb5
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/ffhs/swea/client/Main.java
|
reecube/ffhs-swea-snake-multiplayer
|
7c39ec10b8c40122f34fe57e11d6a1ba49226eb5
|
[
"Unlicense",
"MIT"
] | null | null | null | 23.173913 | 60 | 0.709193 | 2,875 |
package ffhs.swea.client;
import ffhs.swea.client.controller.Controller;
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
private static final int COLS = 50;
private static final int ROWS = 30;
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Controller controller = new Controller(COLS, ROWS);
controller.start(primaryStage);
}
}
|
3e06c10e700621b288b13a95b7fdca9e58185b9b
| 655 |
java
|
Java
|
src/main/java/MercuryTours/ui/PageTransporter.java
|
LimbertVargas/NewTours_GUI_Automation
|
95fc304a7c91316a84b6be1a92353ee02ae6eeec
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/MercuryTours/ui/PageTransporter.java
|
LimbertVargas/NewTours_GUI_Automation
|
95fc304a7c91316a84b6be1a92353ee02ae6eeec
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/MercuryTours/ui/PageTransporter.java
|
LimbertVargas/NewTours_GUI_Automation
|
95fc304a7c91316a84b6be1a92353ee02ae6eeec
|
[
"Apache-2.0"
] | null | null | null | 25.192308 | 71 | 0.69771 | 2,876 |
package MercuryTours.ui;
import MercuryTours.common.AppReader;
import core.selenium.WebDriverManager;
import org.openqa.selenium.WebDriver;
/**
* This class is used to navigate the page.
*
* @author Limbert Alvaro Vargas Laura
* @version 0.0.1
*/
public class PageTransporter {
private static WebDriver webDriver;
/**
* This method is used for go to a page.
*
* @param url The parameter url defines a input url.
*/
public static void goToLoginPage(final String url) {
webDriver = WebDriverManager.getInstance().getWebDriver();
webDriver.navigate().to(AppReader.getInstance().getUrlLogin());
}
}
|
3e06c2cceca573d3873784a5366544103a7f4151
| 323 |
java
|
Java
|
Language/Kotlin/src/main/java/com/peachou/kotlin/advancedtypes/constructors/java/Person.java
|
Peachou/Self-Improvement
|
13b5b0acc505bfac283fef1128dab39ae75ca215
|
[
"Apache-2.0"
] | null | null | null |
Language/Kotlin/src/main/java/com/peachou/kotlin/advancedtypes/constructors/java/Person.java
|
Peachou/Self-Improvement
|
13b5b0acc505bfac283fef1128dab39ae75ca215
|
[
"Apache-2.0"
] | null | null | null |
Language/Kotlin/src/main/java/com/peachou/kotlin/advancedtypes/constructors/java/Person.java
|
Peachou/Self-Improvement
|
13b5b0acc505bfac283fef1128dab39ae75ca215
|
[
"Apache-2.0"
] | null | null | null | 15.380952 | 59 | 0.566563 | 2,877 |
package com.peachou.kotlin.advancedtypes.constructors.java;
public class Person {
private int age;
private String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
{
System.out.println("1");
}
{
System.out.println("2");
}
}
|
3e06c43d669abf365bc3714e14d8fadc0a0d6aac
| 771 |
java
|
Java
|
consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java
|
LeolichN/jdchain-core
|
dd953df23c3a1262909c9dda673d4adcfc3d0a2b
|
[
"Apache-2.0"
] | null | null | null |
consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java
|
LeolichN/jdchain-core
|
dd953df23c3a1262909c9dda673d4adcfc3d0a2b
|
[
"Apache-2.0"
] | null | null | null |
consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/settings/MsgQueueNodeSettings.java
|
LeolichN/jdchain-core
|
dd953df23c3a1262909c9dda673d4adcfc3d0a2b
|
[
"Apache-2.0"
] | null | null | null | 27.535714 | 73 | 0.771725 | 2,878 |
/**
* Copyright: Copyright 2016-2020 JD.COM All Right Reserved
* FileName: com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings
* Author: shaozhuguang
* Department: 区块链研发部
* Date: 2018/12/13 下午4:50
* Description:
*/
package com.jd.blockchain.consensus.mq.settings;
import com.jd.binaryproto.DataContract;
import com.jd.binaryproto.DataField;
import com.jd.binaryproto.PrimitiveType;
import com.jd.blockchain.consensus.NodeSettings;
import com.jd.blockchain.consts.DataCodes;
/**
* @author shaozhuguang
* @create 2018/12/13
* @since 1.0.0
*/
@DataContract(code = DataCodes.CONSENSUS_MSGQUEUE_NODE_SETTINGS)
public interface MsgQueueNodeSettings extends NodeSettings {
@DataField(order = 0, primitiveType = PrimitiveType.INT32)
int getId();
}
|
3e06c5d33169f842885c0c00cb52fede25ad6451
| 929 |
java
|
Java
|
Java_Learn/LearnJavaLang/src/com/djs/learn/javalang/classes/TestSpecialStaticInit2.java
|
djsilenceboy/LearnTest
|
9e4959db04f61133faafb206dcb2f7be67f8a4f4
|
[
"Apache-2.0"
] | 3 |
2017-11-18T21:34:33.000Z
|
2020-09-17T08:32:24.000Z
|
Java_Learn/LearnJavaLang/src/com/djs/learn/javalang/classes/TestSpecialStaticInit2.java
|
djsilenceboy/LearnTest
|
9e4959db04f61133faafb206dcb2f7be67f8a4f4
|
[
"Apache-2.0"
] | 11 |
2020-03-04T23:04:17.000Z
|
2022-03-31T18:51:08.000Z
|
Java_Learn/LearnJavaLang/src/com/djs/learn/javalang/classes/TestSpecialStaticInit2.java
|
djsilenceboy/LearnTest
|
9e4959db04f61133faafb206dcb2f7be67f8a4f4
|
[
"Apache-2.0"
] | 3 |
2019-07-02T14:24:49.000Z
|
2020-09-17T08:32:26.000Z
| 19.765957 | 85 | 0.582347 | 2,879 |
package com.djs.learn.javalang.classes;
/**
* <pre>
Static counter = 1
Instance counter = 1
Instance counter = 2
Instance counter = 3
Static counter = 2
============================================================
* </pre>
*/
public class TestSpecialStaticInit2
{
public static int counterA = 1;
static {
System.out.println("Static counter = " + counterA++);
}
public int counterB = 1;
{
System.out.println("Instance counter = " + counterB++);
}
public TestSpecialStaticInit2(){
System.out.println("Instance counter = " + counterB++);
}
static {
new TestSpecialStaticInit2();
}
static {
// This static output is output after instance output!
System.out.println("Static counter = " + counterA++);
}
{
System.out.println("Instance counter = " + counterB++);
}
public static void main(String[] args){
System.out.println("============================================================");
}
}
|
3e06c5e3bfc0c5a5ab0096e204ee5868e375dbb4
| 3,789 |
java
|
Java
|
Source/Java/PathologyWebApp/main/src/java/gov/va/med/imaging/pathology/commands/PathologyGetCaseSlidesCommand.java
|
VHAINNOVATIONS/Telepathology
|
989c06ccc602b0282c58c4af3455c5e0a33c8593
|
[
"Apache-2.0"
] | 3 |
2015-04-09T14:29:34.000Z
|
2015-11-10T19:39:06.000Z
|
Source/Java/PathologyWebApp/main/src/java/gov/va/med/imaging/pathology/commands/PathologyGetCaseSlidesCommand.java
|
VHAINNOVATIONS/Telepathology
|
989c06ccc602b0282c58c4af3455c5e0a33c8593
|
[
"Apache-2.0"
] | null | null | null |
Source/Java/PathologyWebApp/main/src/java/gov/va/med/imaging/pathology/commands/PathologyGetCaseSlidesCommand.java
|
VHAINNOVATIONS/Telepathology
|
989c06ccc602b0282c58c4af3455c5e0a33c8593
|
[
"Apache-2.0"
] | 9 |
2015-04-14T14:11:09.000Z
|
2018-09-26T07:48:23.000Z
| 31.840336 | 119 | 0.798628 | 2,880 |
/**
*
*/
package gov.va.med.imaging.pathology.commands;
import gov.va.med.URNFactory;
import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException;
import gov.va.med.imaging.core.interfaces.exceptions.MethodException;
import gov.va.med.imaging.exceptions.URNFormatException;
import gov.va.med.imaging.exchange.translation.exceptions.TranslationException;
import gov.va.med.imaging.pathology.PathologyCaseSlide;
import gov.va.med.imaging.pathology.PathologyCaseURN;
import gov.va.med.imaging.pathology.rest.translator.PathologyRestTranslator;
import gov.va.med.imaging.pathology.rest.types.PathologyCaseSlidesType;
import gov.va.med.imaging.web.commands.WebserviceInputParameterTransactionContextField;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Julian
*
*/
public class PathologyGetCaseSlidesCommand
extends AbstractPathologyCommand<List<PathologyCaseSlide>, PathologyCaseSlidesType>
{
private final String caseId;
/**
* @param methodName
*/
public PathologyGetCaseSlidesCommand(String caseId)
{
super("getCaseSlides");
this.caseId = caseId;
}
public String getCaseId()
{
return caseId;
}
/* (non-Javadoc)
* @see gov.va.med.imaging.web.commands.AbstractWebserviceCommand#executeRouterCommand()
*/
@Override
protected List<PathologyCaseSlide> executeRouterCommand()
throws MethodException, ConnectionException
{
try
{
PathologyCaseURN pathologyCaseUrn = URNFactory.create(getCaseId(), PathologyCaseURN.class);
getTransactionContext().setPatientID(pathologyCaseUrn.getPatientId().toString());
List<PathologyCaseSlide> result = getRouter().getCaseSlideInformation(pathologyCaseUrn);
getTransactionContext().setFacadeBytesSent(result == null ? 0L : result.size());
return result;
}
catch(URNFormatException rtfX)
{
throw new MethodException(rtfX);
}
}
/* (non-Javadoc)
* @see gov.va.med.imaging.web.commands.AbstractWebserviceCommand#getMethodParameterValuesString()
*/
@Override
protected String getMethodParameterValuesString()
{
return "for case '" + getCaseId() + "'.";
}
/* (non-Javadoc)
* @see gov.va.med.imaging.web.commands.AbstractWebserviceCommand#translateRouterResult(java.lang.Object)
*/
@Override
protected PathologyCaseSlidesType translateRouterResult(List<PathologyCaseSlide> routerResult)
throws TranslationException, MethodException
{
return PathologyRestTranslator.translateCaseSlides(routerResult);
}
/* (non-Javadoc)
* @see gov.va.med.imaging.web.commands.AbstractWebserviceCommand#getResultClass()
*/
@Override
protected Class<PathologyCaseSlidesType> getResultClass()
{
return PathologyCaseSlidesType.class;
}
/* (non-Javadoc)
* @see gov.va.med.imaging.web.commands.AbstractWebserviceCommand#getTransactionContextFields()
*/
@Override
protected Map<WebserviceInputParameterTransactionContextField, String> getTransactionContextFields()
{
Map<WebserviceInputParameterTransactionContextField, String> transactionContextFields =
new HashMap<WebserviceInputParameterTransactionContextField, String>();
transactionContextFields.put(WebserviceInputParameterTransactionContextField.quality, transactionContextNaValue);
transactionContextFields.put(WebserviceInputParameterTransactionContextField.urn, getCaseId());
transactionContextFields.put(WebserviceInputParameterTransactionContextField.queryFilter, transactionContextNaValue);
return transactionContextFields;
}
/* (non-Javadoc)
* @see gov.va.med.imaging.web.commands.AbstractWebserviceCommand#getEntriesReturned(java.lang.Object)
*/
@Override
public Integer getEntriesReturned(PathologyCaseSlidesType translatedResult)
{
return translatedResult == null ? 0 : translatedResult.getPathologyCaseSlide().length;
}
}
|
3e06c6478a66d5ac9e89269f58dbc418dc072ef6
| 406 |
java
|
Java
|
ha-metadata/src/main/java/com/g2forge/habitat/metadata/type/IMergeableMetadataSubjectTypeFactory.java
|
gdgib/habitat
|
a657a000a358360cca06bce6995b240271dde629
|
[
"Apache-2.0"
] | null | null | null |
ha-metadata/src/main/java/com/g2forge/habitat/metadata/type/IMergeableMetadataSubjectTypeFactory.java
|
gdgib/habitat
|
a657a000a358360cca06bce6995b240271dde629
|
[
"Apache-2.0"
] | null | null | null |
ha-metadata/src/main/java/com/g2forge/habitat/metadata/type/IMergeableMetadataSubjectTypeFactory.java
|
gdgib/habitat
|
a657a000a358360cca06bce6995b240271dde629
|
[
"Apache-2.0"
] | 1 |
2019-08-02T03:12:04.000Z
|
2019-08-02T03:12:04.000Z
| 29 | 97 | 0.795567 | 2,881 |
package com.g2forge.habitat.metadata.type;
import java.util.Collection;
import com.g2forge.alexandria.java.core.helpers.HCollection;
public interface IMergeableMetadataSubjectTypeFactory<S> extends IMetadataSubjectTypeFactory<S> {
public S subject(Collection<? extends S> types);
public default S subject(@SuppressWarnings("unchecked") S... types) {
return subject(HCollection.asList(types));
}
}
|
3e06c77314263ed1bce0ea9d2189884d4b3b24a4
| 449 |
java
|
Java
|
de/dosmike/twitch/dosbot/chat/cmdCallVote.java
|
DosMike/Twitch-Bot
|
7e3f31ffdb5cc347790709c91e47370b26431954
|
[
"Apache-2.0"
] | 1 |
2018-07-12T09:05:39.000Z
|
2018-07-12T09:05:39.000Z
|
de/dosmike/twitch/dosbot/chat/cmdCallVote.java
|
DosMike/Twitch-Bot
|
7e3f31ffdb5cc347790709c91e47370b26431954
|
[
"Apache-2.0"
] | null | null | null |
de/dosmike/twitch/dosbot/chat/cmdCallVote.java
|
DosMike/Twitch-Bot
|
7e3f31ffdb5cc347790709c91e47370b26431954
|
[
"Apache-2.0"
] | null | null | null | 26.411765 | 86 | 0.759465 | 2,882 |
package de.dosmike.twitch.dosbot.chat;
import de.dosmike.twitch.dosbot.ChatRank;
import de.dosmike.twitch.dosbot.modulehandler.VoteHandler;
public class cmdCallVote extends Command{
public cmdCallVote() {
super("Callvote", "Create a new vote. Remember to quote the question and options.");
}
@Override
public boolean run(String user, ChatRank rank, String[] args, boolean silent) {
VoteHandler.startVote(user, args);
return true;
}
}
|
3e06c7fb1f18a01047bae17a51514bef2025ec09
| 1,434 |
java
|
Java
|
service-goods/src/main/java/com/java110/goods/dao/IGroupBuyProductSpecServiceDao.java
|
2669430363/MicroCommunity
|
f7cdc8cc9b1d092403abf18239cdc88fa9c3522d
|
[
"Apache-2.0"
] | 711 |
2017-04-09T15:59:16.000Z
|
2022-03-27T07:19:02.000Z
|
service-goods/src/main/java/com/java110/goods/dao/IGroupBuyProductSpecServiceDao.java
|
yasudarui/MicroCommunity
|
1026aa5eaa86446aedfdefd092a3d6fcf0dfe470
|
[
"Apache-2.0"
] | 16 |
2017-04-09T16:13:09.000Z
|
2022-01-04T16:36:13.000Z
|
service-goods/src/main/java/com/java110/goods/dao/IGroupBuyProductSpecServiceDao.java
|
yasudarui/MicroCommunity
|
1026aa5eaa86446aedfdefd092a3d6fcf0dfe470
|
[
"Apache-2.0"
] | 334 |
2017-04-16T05:01:12.000Z
|
2022-03-30T00:49:37.000Z
| 20.485714 | 71 | 0.681311 | 2,883 |
package com.java110.goods.dao;
import com.java110.utils.exception.DAOException;
import com.java110.entity.merchant.BoMerchant;
import com.java110.entity.merchant.BoMerchantAttr;
import com.java110.entity.merchant.Merchant;
import com.java110.entity.merchant.MerchantAttr;
import java.util.List;
import java.util.Map;
/**
* 拼团产品规格组件内部之间使用,没有给外围系统提供服务能力
* 拼团产品规格服务接口类,要求全部以字符串传输,方便微服务化
* 新建客户,修改客户,删除客户,查询客户等功能
*
* Created by wuxw on 2016/12/27.
*/
public interface IGroupBuyProductSpecServiceDao {
/**
* 保存 拼团产品规格信息
* @param info
* @throws DAOException DAO异常
*/
void saveGroupBuyProductSpecInfo(Map info) throws DAOException;
/**
* 查询拼团产品规格信息(instance过程)
* 根据bId 查询拼团产品规格信息
* @param info bId 信息
* @return 拼团产品规格信息
* @throws DAOException DAO异常
*/
List<Map> getGroupBuyProductSpecInfo(Map info) throws DAOException;
/**
* 查询拼团产品规格信息(instance过程)
* 根据bId 查询拼团产品规格信息
* @param info bId 信息
* @return 拼团产品规格信息
* @throws DAOException DAO异常
*/
List<Map> queryProductStockAndSales(Map info) throws DAOException;
/**
* 修改拼团产品规格信息
* @param info 修改信息
* @throws DAOException DAO异常
*/
void updateGroupBuyProductSpecInfo(Map info) throws DAOException;
/**
* 查询拼团产品规格总数
*
* @param info 拼团产品规格信息
* @return 拼团产品规格数量
*/
int queryGroupBuyProductSpecsCount(Map info);
}
|
3e06c92e1be832c58e7854a756f07a0725dba1f8
| 3,866 |
java
|
Java
|
Package Management System/src/main/java/util/PropertyHandler.java
|
aa104/Package-Management-System
|
2df68c0ea59eae5400f587e50c1cd1dc7257d4d8
|
[
"Apache-2.0"
] | null | null | null |
Package Management System/src/main/java/util/PropertyHandler.java
|
aa104/Package-Management-System
|
2df68c0ea59eae5400f587e50c1cd1dc7257d4d8
|
[
"Apache-2.0"
] | null | null | null |
Package Management System/src/main/java/util/PropertyHandler.java
|
aa104/Package-Management-System
|
2df68c0ea59eae5400f587e50c1cd1dc7257d4d8
|
[
"Apache-2.0"
] | null | null | null | 27.034965 | 113 | 0.70538 | 2,884 |
package main.java.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;
/**
* PropertyHandler class for the project management utility.
* This class contains a properties object that holds settings
* for different functions. NOTE THAT ALL VALUES ARE STORED IN
* PLAINTEXT - PASSWORDS ARE NOT SECURE.
* @author Navin
*
*/
//TODO Add security
public class PropertyHandler {
private static PropertyHandler instance = null;
private Properties props;
private String propsFilePath;
private Logger logger = Logger.getLogger(PropertyHandler.class.getName());
private PropertyHandler() {
// prevents multiple instantiation of singleton class
}
public void init(String programDirectory) {
// setup file directories
String propsDirName = programDirectory + '\\' + "props";
this.propsFilePath = propsDirName + '\\' + "config.properties";
this.props = new Properties();
File propsDir = new File(propsDirName);
File propsFile = new File(propsFilePath);
try {
if (propsFile.exists()) {
// if the file exists, load it.
FileInputStream inProps = new FileInputStream(propsFile);
props.load(inProps);
inProps.close();
} else if(!propsDir.exists()){
logger.info("Creating new properties directory");
System.out.println("Creating new properties directory");
propsDir.mkdirs();
}
} catch (IOException e) {
// Add to logger
logger.info("Failed to read properties file");
System.out.println("Failed to read properties file: " + propsFilePath);
} finally {
// Add programDirectory passed to settings function
props.setProperty("program_directory", programDirectory);
}
}
public static synchronized PropertyHandler getInstance() {
if (instance == null) {
instance = new PropertyHandler();
}
return instance;
}
public String getProperty(String key) {
return props.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return props.getProperty(key,defaultValue);
}
public void setProperty(String key, String value) {
// System.out.println("[PropertyHandler.setProperty()] PROPERTY BEING SET: (Key)" + key+ "Value: " + value);
props.setProperty(key, value);
try {
FileOutputStream outProps = new FileOutputStream(propsFilePath);
props.store(outProps,"Properties for the Package Management System");
outProps.close();
} catch (FileNotFoundException e) {
System.out.println("Could not find file: " + propsFilePath);
} catch (IOException e) {
System.out.println("Failed to write properties file: " + propsFilePath);
}
}
/**
* Display all properties in a clean format
*/
public void printAllProperties() {
System.out.println("In printAllProps");
props.forEach((a,b) -> {
System.out.printf(" Key: %s, Property: %s. %n", a , b);
});
}
/*
public static void main(String[] args) {
PropertyHandler ph = PropertyHandler.getInstance();
ph.init("testFiles");
ph.setProperty("test_first_name", "navin");
ph.setProperty("test_last_name", "pathak");
System.out.println(ph.getProperty("test_first_name"));
System.out.println(ph.getProperty("test_last_name"));
System.out.println(ph.getProperty("test_netID"));
System.out.println(ph.getProperty("test_netID","np8"));
}
*/
// /*
// * Global
// */
// public static String rootDir;
//
// /*
// * Printer
// */
// public static String printServiceName;
//
//
// /*
// * Emailer()
// */
// // reminder emails
// public static String sendReminderEmails;
//
// public static String password;
// public static String adminEmailAddress;
// public static String mailerName;
// public static String replyToAddress;
// public static String replyToName;
}
|
3e06c95f77dbbdc18eac6f2b19f5f47d51f59112
| 56,363 |
java
|
Java
|
wayang-commons/wayang-core/src/main/java/org/apache/wayang/core/optimizer/channels/ChannelConversionGraph.java
|
hboutemy/incubator-wayang
|
a91bd3615432cd8f3bf44bd2f4b99b5d8df3cdba
|
[
"Apache-2.0"
] | 67 |
2021-02-15T18:59:42.000Z
|
2022-03-28T06:27:41.000Z
|
wayang-commons/wayang-core/src/main/java/org/apache/wayang/core/optimizer/channels/ChannelConversionGraph.java
|
hboutemy/incubator-wayang
|
a91bd3615432cd8f3bf44bd2f4b99b5d8df3cdba
|
[
"Apache-2.0"
] | 76 |
2021-02-09T13:00:41.000Z
|
2022-03-30T22:48:50.000Z
|
wayang-commons/wayang-core/src/main/java/org/apache/wayang/core/optimizer/channels/ChannelConversionGraph.java
|
hboutemy/incubator-wayang
|
a91bd3615432cd8f3bf44bd2f4b99b5d8df3cdba
|
[
"Apache-2.0"
] | 23 |
2021-02-07T05:19:10.000Z
|
2022-03-04T18:05:20.000Z
| 49.484636 | 150 | 0.617249 | 2,885 |
/*
* 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.wayang.core.optimizer.channels;
import org.apache.wayang.core.api.Configuration;
import org.apache.wayang.core.optimizer.DefaultOptimizationContext;
import org.apache.wayang.core.optimizer.OptimizationContext;
import org.apache.wayang.core.optimizer.OptimizationUtils;
import org.apache.wayang.core.optimizer.ProbabilisticDoubleInterval;
import org.apache.wayang.core.optimizer.cardinality.CardinalityEstimate;
import org.apache.wayang.core.optimizer.costs.TimeEstimate;
import org.apache.wayang.core.plan.executionplan.Channel;
import org.apache.wayang.core.plan.executionplan.ExecutionTask;
import org.apache.wayang.core.plan.wayangplan.ExecutionOperator;
import org.apache.wayang.core.plan.wayangplan.InputSlot;
import org.apache.wayang.core.plan.wayangplan.LoopHeadOperator;
import org.apache.wayang.core.plan.wayangplan.LoopSubplan;
import org.apache.wayang.core.plan.wayangplan.OutputSlot;
import org.apache.wayang.core.platform.ChannelDescriptor;
import org.apache.wayang.core.platform.Junction;
import org.apache.wayang.core.util.Bitmask;
import org.apache.wayang.core.util.OneTimeExecutable;
import org.apache.wayang.core.util.ReflectionUtils;
import org.apache.wayang.core.util.WayangCollections;
import org.apache.wayang.core.util.Tuple;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.function.ToDoubleFunction;
import java.util.stream.Collectors;
/**
* This graph contains a set of {@link ChannelConversion}s.
*/
public class ChannelConversionGraph {
/**
* Keeps track of the {@link ChannelConversion}s.
*/
private final Map<ChannelDescriptor, List<ChannelConversion>> conversions = new HashMap<>();
/**
* Caches the {@link Comparator} for {@link ProbabilisticDoubleInterval}s.
*/
private final ToDoubleFunction<ProbabilisticDoubleInterval> costSquasher;
/**
* On the face of competing {@link Tree}s, picks the one to use for converting {@link Channel}s.
*/
private final TreeSelectionStrategy treeSelectionStrategy;
private static final Logger logger = LogManager.getLogger(ChannelConversionGraph.class);
/**
* Creates a new instance.
*
* @param configuration describes how to configure the new instance
*/
public ChannelConversionGraph(Configuration configuration) {
this.costSquasher = configuration.getCostSquasherProvider().provide();
configuration.getChannelConversionProvider().provideAll().forEach(this::add);
String treeSelectionStrategyClassName = configuration.getStringProperty(
"wayang.core.optimizer.channels.selection",
this.getClass().getCanonicalName() + '$' + CostbasedTreeSelectionStrategy.class.getSimpleName()
);
this.treeSelectionStrategy = ReflectionUtils.instantiateDefault(treeSelectionStrategyClassName);
}
/**
* Register a new {@code channelConversion} in this instance, which effectively adds an edge.
*/
public void add(ChannelConversion channelConversion) {
final List<ChannelConversion> edges = this.getOrCreateChannelConversions(channelConversion.getSourceChannelDescriptor());
edges.add(channelConversion);
}
/**
* Return all registered {@link ChannelConversion}s that convert the given {@code channelDescriptor}.
*
* @param channelDescriptor should be converted
* @return the {@link ChannelConversion}s
*/
private List<ChannelConversion> getOrCreateChannelConversions(ChannelDescriptor channelDescriptor) {
return this.conversions.computeIfAbsent(channelDescriptor, key -> new ArrayList<>());
}
/**
* Finds the minimum tree {@link Junction} (w.r.t. {@link TimeEstimate}s that connects the given {@link OutputSlot} to the
* {@code destInputSlots}.
*
* @param output {@link OutputSlot} of an {@link ExecutionOperator} that should be consumed
* @param destInputSlots {@link InputSlot}s of {@link ExecutionOperator}s that should receive data from the {@code output}
* @param optimizationContext describes the above mentioned {@link ExecutionOperator} key figures
* @param isRequestBreakpoint whether a breakpoint-capable {@link Channel} should be inserted if possible
* @return a {@link Junction} or {@code null} if none could be found
*/
public Junction findMinimumCostJunction(OutputSlot<?> output,
List<InputSlot<?>> destInputSlots,
OptimizationContext optimizationContext,
boolean isRequestBreakpoint) {
return new ShortestTreeSearcher(output, null, destInputSlots, optimizationContext, isRequestBreakpoint).getJunction();
}
/**
* Finds the minimum tree {@link Junction} (w.r.t. {@link TimeEstimate}s that connects the given {@link OutputSlot} to the
* {@code destInputSlots}.
*
* @param output {@link OutputSlot} of an {@link ExecutionOperator} that should be consumed
* @param openChannels existing {@link Channel}s that must be part of the tree or {@code null}
* @param destInputSlots {@link InputSlot}s of {@link ExecutionOperator}s that should receive data from the {@code output}
* @param optimizationContext describes the above mentioned {@link ExecutionOperator} key figures
* @return a {@link Junction} or {@code null} if none could be found
*/
public Junction findMinimumCostJunction(OutputSlot<?> output,
Collection<Channel> openChannels,
List<InputSlot<?>> destInputSlots,
OptimizationContext optimizationContext) {
return new ShortestTreeSearcher(output, openChannels, destInputSlots, optimizationContext, false).getJunction();
}
/**
* Given two {@link Tree}s, select the preferred one.
*/
private Tree selectPreferredTree(Tree t1, Tree t2) {
if (t1 == null) return t2;
if (t2 == null) return t1;
return this.treeSelectionStrategy.select(t1, t2);
}
/**
* Merge several {@link Tree}s, which should have the same root but should be otherwise disjoint.
*
* @return the merged {@link Tree} or {@code null} if the input {@code trees} could not be merged
*/
private Tree mergeTrees(Collection<Tree> trees) {
assert trees.size() >= 2;
// For various trees to be combined, we require them to be "disjoint". Check this.
final Iterator<Tree> iterator = trees.iterator();
final Tree firstTree = iterator.next();
Bitmask combinationSettledIndices = new Bitmask(firstTree.settledDestinationIndices);
int maxSettledIndices = combinationSettledIndices.cardinality();
final HashSet<ChannelDescriptor> employedChannelDescriptors = new HashSet<>(firstTree.employedChannelDescriptors);
int maxVisitedChannelDescriptors = employedChannelDescriptors.size();
double costs = firstTree.costs;
TreeVertex newRoot = new TreeVertex(firstTree.root.channelDescriptor, firstTree.root.settledIndices);
newRoot.copyEdgesFrom(firstTree.root);
while (iterator.hasNext()) {
final Tree ithTree = iterator.next();
combinationSettledIndices.orInPlace(ithTree.settledDestinationIndices);
maxSettledIndices += ithTree.settledDestinationIndices.cardinality();
if (maxSettledIndices > combinationSettledIndices.cardinality()) {
return null;
}
employedChannelDescriptors.addAll(ithTree.employedChannelDescriptors);
maxVisitedChannelDescriptors += ithTree.employedChannelDescriptors.size() - 1; // NB: -1 for the root
if (maxVisitedChannelDescriptors > employedChannelDescriptors.size()) {
return null;
}
costs += ithTree.costs;
newRoot.copyEdgesFrom(ithTree.root);
}
// If all tests are passed, create the combination.
final Tree mergedTree = new Tree(newRoot, combinationSettledIndices);
mergedTree.costs = costs;
mergedTree.employedChannelDescriptors.addAll(employedChannelDescriptors);
return mergedTree;
}
/**
* Designates a strategy of which conversion tree to prefer when there are competing trees.
*/
private interface TreeSelectionStrategy {
/**
* Select the preferred {@link Tree}.
*
* @param t1 the first {@link Tree} (not {@code null}
* @param t2 the second {@link Tree} (not {@code null}
* @return the preferred {@link Tree}
*/
Tree select(Tree t1, Tree t2);
}
/**
* Prefers {@link Tree}s with lower cost.
*/
public static class CostbasedTreeSelectionStrategy implements TreeSelectionStrategy {
@Override
public Tree select(Tree t1, Tree t2) {
return t1.costs <= t2.costs ? t1 : t2;
}
}
/**
* Prefers {@link Tree}s with lower cost.
*/
public static class RandomTreeSelectionStrategy implements TreeSelectionStrategy {
private final Random random = new Random();
@Override
public Tree select(Tree t1, Tree t2) {
return this.random.nextBoolean() ? t1 : t2;
}
}
/**
* Finds the shortest tree between the {@link #sourceChannelDescriptor} and the {@link #destChannelDescriptorSets}.
*/
private class ShortestTreeSearcher extends OneTimeExecutable {
/**
* The {@link OutputSlot} that should be converted.
*/
private final OutputSlot<?> sourceOutput;
/**
* {@link ChannelDescriptor} for the {@link Channel} produced by the {@link #sourceOutput}.
*/
private final ChannelDescriptor sourceChannelDescriptor;
/**
* Describes the number of data quanta that are presumably converted.
*/
private final CardinalityEstimate cardinality;
/**
* How often the conversion is presumably performed.
*/
private final int numExecutions;
/**
* {@link ChannelDescriptor}s of {@link #existingChannels} that are allowed to have new consumers.
*/
private final Set<ChannelDescriptor> openChannelDescriptors;
/**
* Maps {@link ChannelDescriptor}s to already existing {@link Channel}s.
*/
private final Map<ChannelDescriptor, Channel> existingChannels;
/**
* Maps destination {@link InputSlot}s to {@link #existingChannels} that are their destination.
*/
private final Map<InputSlot<?>, Channel> existingDestinationChannels;
private final Bitmask existingDestinationChannelIndices,
absentDestinationChannelIndices,
allDestinationChannelIndices = new Bitmask();
private final Map<ChannelDescriptor, Bitmask> reachableExistingDestinationChannelIndices;
/**
* {@link InputSlot}s that should be served by the {@link #sourceOutput}.
*/
private final List<InputSlot<?>> destInputs;
/**
* Supported {@link ChannelDescriptor}s for each of the {@link #destInputs}.
*/
private final List<Set<ChannelDescriptor>> destChannelDescriptorSets;
/**
* The input {@link OptimizationContext} (and a write-copy, repectively).
*/
private final OptimizationContext optimizationContext, optimizationContextCopy;
/**
* Whether the {@link #result} should contain a breakpoint-capable {@link Channel}.
*/
private final boolean isRequestBreakpoint;
/**
* Maps kernelized {@link Set}s of possible input {@link ChannelDescriptor}s to destination {@link InputSlot}s via
* their respective indices in {@link #destInputs}.
*/
private Map<Set<ChannelDescriptor>, Bitmask> kernelDestChannelDescriptorSetsToIndices;
/**
* Maps specific input {@link ChannelDescriptor}s to applicable destination {@link InputSlot}s via
* their respective indices in {@link #destInputs}.
*/
private Map<ChannelDescriptor, Bitmask> kernelDestChannelDescriptorsToIndices;
/**
* Caches cost estimates for {@link ChannelConversion}s.
*/
private Map<ChannelConversion, Double> conversionCostCache = new HashMap<>();
/**
* Caches whether {@link ChannelConversion}s should be filtered.
*/
private Map<ChannelConversion, Boolean> conversionFilterCache = new HashMap<>();
/**
* Caches the result of {@link #getJunction()}.
*/
private Junction result = null;
/**
* Create a new instance.
*
* @param sourceOutput provides a {@link Channel} that should be converted
* @param openChannels existing {@link Channel} derived from {@code sourceOutput} and where we must take up
* the search; or {@code null}
* @param destInputs that consume the converted {@link Channel}(s)
* @param optimizationContext provides optimization info
*/
private ShortestTreeSearcher(OutputSlot<?> sourceOutput,
Collection<Channel> openChannels,
List<InputSlot<?>> destInputs,
OptimizationContext optimizationContext,
boolean isRequestBreakpoint) {
// Store relevant variables.
this.isRequestBreakpoint = isRequestBreakpoint && openChannels == null; // No breakpoints requestable.
this.optimizationContext = optimizationContext;
this.optimizationContextCopy = new DefaultOptimizationContext(this.optimizationContext);
this.sourceOutput = sourceOutput;
this.destInputs = destInputs;
final boolean isOpenChannelsPresent = openChannels != null && !openChannels.isEmpty();
// Figure out the optimization info via the sourceOutput.
final ExecutionOperator outputOperator = (ExecutionOperator) this.sourceOutput.getOwner();
final OptimizationContext.OperatorContext operatorContext = optimizationContext.getOperatorContext(outputOperator);
assert operatorContext != null : String.format("Optimization info for %s missing.", outputOperator);
this.cardinality = operatorContext.getOutputCardinality(this.sourceOutput.getIndex());
this.numExecutions = operatorContext.getNumExecutions();
// Figure out, if a part of the conversion is already in place and initialize accordingly.
if (isOpenChannelsPresent) {
// Take any open channel and trace it back to the source channel.
Channel existingChannel = WayangCollections.getAny(openChannels);
while (existingChannel.getProducerSlot() != sourceOutput) {
existingChannel = OptimizationUtils.getPredecessorChannel(existingChannel);
}
final Channel sourceChannel = existingChannel;
this.sourceChannelDescriptor = sourceChannel.getDescriptor();
// Now traverse down-stream to find already reached destinations.
this.existingChannels = new HashMap<>();
this.existingDestinationChannels = new HashMap<>(4);
this.existingDestinationChannelIndices = new Bitmask();
this.collectExistingChannels(sourceChannel);
this.openChannelDescriptors = new HashSet<>(openChannels.size());
for (Channel openChannel : openChannels) {
this.openChannelDescriptors.add(openChannel.getDescriptor());
}
} else {
this.sourceChannelDescriptor = outputOperator.getOutputChannelDescriptor(this.sourceOutput.getIndex());
this.existingChannels = Collections.emptyMap();
this.existingDestinationChannels = Collections.emptyMap();
this.existingDestinationChannelIndices = new Bitmask();
this.openChannelDescriptors = Collections.emptySet();
}
// Set up the destinations.
this.destChannelDescriptorSets = WayangCollections.map(destInputs, this::resolveSupportedChannels);
assert this.destChannelDescriptorSets.stream().noneMatch(Collection::isEmpty);
this.kernelizeChannelRequests();
if (isOpenChannelsPresent) {
// Update the bitmask of all already reached destination channels...
// ...and mark the paths of already reached destination channels via upstream traversal.
this.reachableExistingDestinationChannelIndices = new HashMap<>();
for (Channel existingDestinationChannel : this.existingDestinationChannels.values()) {
final Bitmask channelIndices = this.kernelDestChannelDescriptorsToIndices
.get(existingDestinationChannel.getDescriptor())
.and(this.existingDestinationChannelIndices);
while (true) {
this.reachableExistingDestinationChannelIndices.compute(
existingDestinationChannel.getDescriptor(),
(k, v) -> v == null ? new Bitmask(channelIndices) : v.orInPlace(channelIndices)
);
if (existingDestinationChannel.getDescriptor().equals(this.sourceChannelDescriptor)) break;
existingDestinationChannel = OptimizationUtils.getPredecessorChannel(existingDestinationChannel);
}
}
} else {
this.reachableExistingDestinationChannelIndices = Collections.emptyMap();
}
this.absentDestinationChannelIndices = this.allDestinationChannelIndices
.andNot(this.existingDestinationChannelIndices);
}
/**
* Traverse the given {@link Channel} downstream and collect any {@link Channel} that feeds some
* {@link InputSlot} of a non-conversion {@link ExecutionOperator}.
*
* @param channel the {@link Channel} to traverse from
* @see #existingChannels
* @see #existingDestinationChannels
*/
private void collectExistingChannels(Channel channel) {
this.existingChannels.put(channel.getDescriptor(), channel);
for (ExecutionTask consumer : channel.getConsumers()) {
final ExecutionOperator operator = consumer.getOperator();
if (!operator.isAuxiliary()) {
final InputSlot<?> input = consumer.getInputSlotFor(channel);
this.existingDestinationChannels.put(input, channel);
int destIndex = 0;
while (this.destInputs.get(destIndex) != input) destIndex++;
this.existingDestinationChannelIndices.set(destIndex);
} else {
for (Channel outputChannel : consumer.getOutputChannels()) {
if (outputChannel != null) this.collectExistingChannels(outputChannel);
}
}
}
}
/**
* Creates and caches a {@link Junction} according to the initialization parameters.
*
* @return the {@link Junction} or {@code null} if none could be found
*/
public Junction getJunction() {
this.tryExecute();
return this.result;
}
/**
* Find the supported {@link ChannelDescriptor}s for the given {@link InputSlot}. If the latter is a
* "loop invariant" {@link InputSlot}, then require to only reusable {@link ChannelDescriptor}.
*
* @param input for which supported {@link ChannelDescriptor}s are requested
* @return all eligible {@link ChannelDescriptor}s
*/
private Set<ChannelDescriptor> resolveSupportedChannels(final InputSlot<?> input) {
final Channel existingChannel = this.existingDestinationChannels.get(input);
if (existingChannel != null) {
return Collections.singleton(existingChannel.getDescriptor());
}
final ExecutionOperator owner = (ExecutionOperator) input.getOwner();
final List<ChannelDescriptor> supportedInputChannels = owner.getSupportedInputChannels(input.getIndex());
if (input.isLoopInvariant()) {
// Loop input is needed in several iterations and must therefore be reusable.
return supportedInputChannels.stream().filter(ChannelDescriptor::isReusable).collect(Collectors.toSet());
} else {
return WayangCollections.asSet(supportedInputChannels);
}
}
@Override
protected void doExecute() {
// Start from the root vertex.
final Tree tree = this.searchTree();
if (tree != null) {
this.createJunction(tree);
} else {
logger.debug("Could not connect {} with {}.", this.sourceOutput, this.destInputs);
}
}
/**
* Rule out any non-reusable {@link ChannelDescriptor}s in recurring {@link ChannelDescriptor} sets.
*
* @see #kernelDestChannelDescriptorSetsToIndices
* @see #kernelDestChannelDescriptorsToIndices
*/
private void kernelizeChannelRequests() {
// Check if the Junction enters a loop "from the side", i.e., across multiple iterations.
// CHECK: Since we rule out non-reusable Channels in #resolveSupportedChannels, do we really need this?
// final LoopSubplan outputLoop = this.sourceOutput.getOwner().getInnermostLoop();
// final int outputLoopDepth = this.sourceOutput.getOwner().getLoopStack().size();
// boolean isSideEnterLoop = this.destInputs.stream().anyMatch(input ->
// !input.getOwner().isLoopHead() &&
// (input.getOwner().getLoopStack().size() > outputLoopDepth ||
// (input.getOwner().getLoopStack().size() == outputLoopDepth && input.getOwner().getInnermostLoop() != outputLoop)
// )
// );
// Index the (unreached) Channel requests by their InputSlots, thereby merging equal ones.
int index = 0;
this.kernelDestChannelDescriptorSetsToIndices = new HashMap<>(this.destChannelDescriptorSets.size());
for (Set<ChannelDescriptor> destChannelDescriptorSet : this.destChannelDescriptorSets) {
final Bitmask indices = this.kernelDestChannelDescriptorSetsToIndices.computeIfAbsent(
destChannelDescriptorSet, key -> new Bitmask(this.destChannelDescriptorSets.size())
);
this.allDestinationChannelIndices.set(index);
indices.set(index++);
}
// Strip off the non-reusable, superfluous ChannelDescriptors where applicable.
Collection<Tuple<Set<ChannelDescriptor>, Bitmask>> kernelDestChannelDescriptorSetsToIndicesUpdates = new LinkedList<>();
final Iterator<Map.Entry<Set<ChannelDescriptor>, Bitmask>> iterator =
this.kernelDestChannelDescriptorSetsToIndices.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<Set<ChannelDescriptor>, Bitmask> entry = iterator.next();
final Bitmask indices = entry.getValue();
// Don't touch destination channel sets that occur only once.
if (indices.cardinality() < 2) continue;
// If there is exactly one non-reusable and more than one reusable channel, we can remove the
// non-reusable one.
Set<ChannelDescriptor> channelDescriptors = entry.getKey();
int numReusableChannels = (int) channelDescriptors.stream().filter(ChannelDescriptor::isReusable).count();
if (numReusableChannels == 0 && channelDescriptors.size() == 1) {
logger.warn(
"More than two target operators request only the non-reusable channel {}.",
WayangCollections.getSingle(channelDescriptors)
);
}
if (channelDescriptors.size() - numReusableChannels == 1) {
iterator.remove();
channelDescriptors = new HashSet<>(channelDescriptors);
channelDescriptors.removeIf(channelDescriptor -> !channelDescriptor.isReusable());
kernelDestChannelDescriptorSetsToIndicesUpdates.add(new Tuple<>(channelDescriptors, indices));
}
}
for (Tuple<Set<ChannelDescriptor>, Bitmask> channelsToIndicesChange : kernelDestChannelDescriptorSetsToIndicesUpdates) {
this.kernelDestChannelDescriptorSetsToIndices.computeIfAbsent(
channelsToIndicesChange.getField0(),
key -> new Bitmask(this.destChannelDescriptorSets.size())
).orInPlace(channelsToIndicesChange.getField1());
}
// Index the single ChannelDescriptors.
this.kernelDestChannelDescriptorsToIndices = new HashMap<>();
for (Map.Entry<Set<ChannelDescriptor>, Bitmask> entry : this.kernelDestChannelDescriptorSetsToIndices.entrySet()) {
final Set<ChannelDescriptor> channelDescriptorSet = entry.getKey();
final Bitmask indices = entry.getValue();
for (ChannelDescriptor channelDescriptor : channelDescriptorSet) {
this.kernelDestChannelDescriptorsToIndices.merge(channelDescriptor, new Bitmask(indices), Bitmask::or);
}
}
}
/**
* Starts the actual search.
*/
private Tree searchTree() {
// Prepare the recursive traversal.
final HashSet<ChannelDescriptor> visitedChannelDescriptors = new HashSet<>(16);
visitedChannelDescriptors.add(this.sourceChannelDescriptor);
// Perform the traversal.
final Map<Bitmask, Tree> solutions = this.enumerate(
visitedChannelDescriptors,
this.sourceChannelDescriptor,
Bitmask.EMPTY_BITMASK,
this.sourceChannelDescriptor.isSuitableForBreakpoint()
);
// Get hold of a comprehensive solution (if it exists).
Bitmask requestedIndices = new Bitmask(this.destChannelDescriptorSets.size());
requestedIndices.flip(0, this.destChannelDescriptorSets.size());
return solutions.get(requestedIndices);
}
/**
* Recursive {@link Tree} enumeration strategy.
*
* @param visitedChannelDescriptors previously visited {@link ChannelDescriptor}s (inclusive of {@code channelDescriptor};
* can be altered but must be in original state before leaving the method
* @param channelDescriptor the currently enumerated {@link ChannelDescriptor}
* @param settledDestinationIndices indices of destinations that have already been reached via the
* {@code visitedChannelDescriptors} (w/o {@code channelDescriptor};
* can be altered but must be in original state before leaving the method
* @param isVisitedBreakpointChannel whether the {@code visitedChannelDescriptors} contain a breakpoint-capable {@link Channel}
* @return solutions to the search problem reachable from this node; {@link Tree}s must still be rerooted
*/
public Map<Bitmask, Tree> enumerate(
Set<ChannelDescriptor> visitedChannelDescriptors,
ChannelDescriptor channelDescriptor,
Bitmask settledDestinationIndices,
boolean isVisitedBreakpointChannel) {
// Mapping from settled indices to the cheapest tree settling them. Will be the return value.
Map<Bitmask, Tree> newSolutions = new HashMap<>(16);
Tree newSolution;
// Check if current path is a (new) solution.
// Exclude existing destinations that are not reached via the current path.
final Bitmask excludedExistingIndices = this.existingDestinationChannelIndices.andNot(
this.reachableExistingDestinationChannelIndices.getOrDefault(channelDescriptor, Bitmask.EMPTY_BITMASK)
);
// Exclude missing destinations if the current channel exists but is not open.
final Bitmask excludedAbsentIndices =
(this.existingChannels.containsKey(channelDescriptor) && !openChannelDescriptors.contains(channelDescriptor)) ?
this.absentDestinationChannelIndices :
Bitmask.EMPTY_BITMASK;
final Bitmask newSettledIndices = this.kernelDestChannelDescriptorsToIndices
.getOrDefault(channelDescriptor, Bitmask.EMPTY_BITMASK)
.andNot(settledDestinationIndices)
.andNotInPlace(excludedExistingIndices)
.andNotInPlace(excludedAbsentIndices);
if (!newSettledIndices.isEmpty()) {
if (channelDescriptor.isReusable() || newSettledIndices.cardinality() == 1) {
// If the channel is reusable, it is almost safe to say that we either use it for all possible
// destinations or for none, because no extra costs can incur.
// TODO: Create all possible combinations if required.
// The same is for when there is only a single destination reached.
newSolution = Tree.singleton(channelDescriptor, newSettledIndices);
newSolutions.put(newSolution.settledDestinationIndices, newSolution);
} else {
// Otherwise, create an entry for each settled index.
for (int index = newSettledIndices.nextSetBit(0); index != -1; index = newSettledIndices.nextSetBit(index + 1)) {
Bitmask newSettledIndicesSubset = new Bitmask(index + 1);
newSettledIndicesSubset.set(index);
newSolution = Tree.singleton(channelDescriptor, newSettledIndicesSubset);
newSolutions.put(newSolution.settledDestinationIndices, newSolution);
}
}
// Check early stopping criteria:
// There are no more channels that could be settled.
if (newSettledIndices.cardinality() == this.destChannelDescriptorSets.size() - excludedExistingIndices.cardinality()
&& (!this.isRequestBreakpoint || isVisitedBreakpointChannel)) {
return newSolutions;
}
}
// For each outgoing edge, explore all combinations of reachable target indices.
if (channelDescriptor.isReusable()) {
// When descending, "pick" the newly settled destinations only for reusable ChannelDescriptors.
settledDestinationIndices.orInPlace(newSettledIndices);
}
final List<ChannelConversion> channelConversions =
ChannelConversionGraph.this.conversions.getOrDefault(channelDescriptor, Collections.emptyList());
final List<Collection<Tree>> childSolutionSets = new ArrayList<>(channelConversions.size());
final Set<ChannelDescriptor> successorChannelDescriptors = this.getSuccessorChannelDescriptors(channelDescriptor);
for (ChannelConversion channelConversion : channelConversions) {
final ChannelDescriptor targetChannelDescriptor = channelConversion.getTargetChannelDescriptor();
// Skip if there are successor channel descriptors that do not contain the target channel descriptor.
if (successorChannelDescriptors != null && !successorChannelDescriptors.contains(targetChannelDescriptor)) {
continue;
}
// Check if the channelConversion can be filtered.
if (successorChannelDescriptors == null && this.isFiltered(channelConversion)) {
logger.info("Filtering conversion {} between {} and {}.", channelConversion, this.sourceOutput, this.destInputs);
continue;
}
if (visitedChannelDescriptors.add(targetChannelDescriptor)) {
final Map<Bitmask, Tree> childSolutions = this.enumerate(
visitedChannelDescriptors,
targetChannelDescriptor,
settledDestinationIndices,
isVisitedBreakpointChannel || targetChannelDescriptor.isSuitableForBreakpoint()
);
childSolutions.values().forEach(
tree -> tree.reroot(
channelDescriptor,
channelDescriptor.isReusable() ? newSettledIndices : Bitmask.EMPTY_BITMASK,
channelConversion,
this.getCostEstimate(channelConversion)
)
);
if (!childSolutions.isEmpty()) childSolutionSets.add(childSolutions.values());
visitedChannelDescriptors.remove(targetChannelDescriptor);
}
}
settledDestinationIndices.andNotInPlace(newSettledIndices);
// Merge the childSolutionSets into the newSolutions.
// Each childSolutionSet corresponds to a traversed outgoing ChannelConversion.
// If a breakpoint is requested, we don't need to merge if there are already comprehensive solutions with
// breakpoints.
if (this.isRequestBreakpoint && !isVisitedBreakpointChannel) {
Tree bestBreakpointSolution = null;
for (Collection<Tree> trees : childSolutionSets) {
for (Tree tree : trees) {
if (this.allDestinationChannelIndices.isSubmaskOf(tree.settledDestinationIndices)) {
bestBreakpointSolution = selectPreferredTree(bestBreakpointSolution, tree);
}
}
}
if (bestBreakpointSolution != null) {
newSolutions.put(bestBreakpointSolution.settledDestinationIndices, bestBreakpointSolution);
return newSolutions;
}
}
// At first, consider the childSolutionSet for each outgoing ChannelConversion individually.
for (Collection<Tree> childSolutionSet : childSolutionSets) {
// Each childSolutionSet its has a mapping from settled indices to trees.
for (Tree tree : childSolutionSet) {
// Update newSolutions if the current tree is cheaper or settling new indices.
newSolutions.merge(tree.settledDestinationIndices, tree, ChannelConversionGraph.this::selectPreferredTree);
}
}
// If the current Channel/vertex is reusable, also detect valid combinations.
// Check if the combinations yield new solutions.
if (channelDescriptor.isReusable()
&& this.kernelDestChannelDescriptorSetsToIndices.size() > 1
&& childSolutionSets.size() > 1
&& this.destInputs.size() > newSettledIndices.cardinality() + settledDestinationIndices.cardinality() + 1) {
// Determine the number of "unreached" destChannelDescriptorSets.
int numUnreachedDestinationSets = 0;
for (Bitmask settlableDestinationIndices : this.kernelDestChannelDescriptorSetsToIndices.values()) {
if (!settlableDestinationIndices.isSubmaskOf(settledDestinationIndices)) {
numUnreachedDestinationSets++;
}
}
if (numUnreachedDestinationSets >= 2) { // only combine when there is more than one destination left
final Collection<List<Collection<Tree>>> childSolutionSetCombinations =
WayangCollections.createPowerList(childSolutionSets, numUnreachedDestinationSets);
for (List<Collection<Tree>> childSolutionSetCombination : childSolutionSetCombinations) {
if (childSolutionSetCombination.size() < 2)
continue; // only combine when we have more than on child solution
for (List<Tree> solutionCombination : WayangCollections.streamedCrossProduct(childSolutionSetCombination)) {
final Tree tree = ChannelConversionGraph.this.mergeTrees(solutionCombination);
if (tree != null) {
newSolutions.merge(tree.settledDestinationIndices, tree, ChannelConversionGraph.this::selectPreferredTree);
}
}
}
}
}
return newSolutions;
}
/**
* Find {@link ChannelDescriptor}s of {@link Channel}s that can be reached from the current
* {@link ChannelDescriptor}. This is relevant only when there are {@link #existingChannels}.
*
* @param descriptor from which successor {@link ChannelDescriptor}s are requested
* @return the successor {@link ChannelDescriptor}s or {@code null} if no restrictions apply
*/
private Set<ChannelDescriptor> getSuccessorChannelDescriptors(ChannelDescriptor descriptor) {
final Channel channel = this.existingChannels.get(descriptor);
if (channel == null || this.openChannelDescriptors.contains(descriptor)) return null;
Set<ChannelDescriptor> result = new HashSet<>();
for (ExecutionTask consumer : channel.getConsumers()) {
if (!consumer.getOperator().isAuxiliary()) continue;
for (Channel successorChannel : consumer.getOutputChannels()) {
result.add(successorChannel.getDescriptor());
}
}
return result;
}
/**
* Retrieve a cached or calculate and cache the cost estimate for a given {@link ChannelConversion}
* w.r.t. the {@link #cardinality}.
*
* @param channelConversion whose cost estimate is requested
* @return the cost estimate
*/
private double getCostEstimate(ChannelConversion channelConversion) {
return this.conversionCostCache.computeIfAbsent(
channelConversion,
key -> {
final ProbabilisticDoubleInterval costEstimate = key.estimateConversionCost(
this.cardinality, this.numExecutions, this.optimizationContextCopy
);
return costSquasher.applyAsDouble(costEstimate);
}
);
}
/**
* Determine whether the given {@link ChannelConversion} should be filtered.
*
* @param channelConversion which should be checked for filtering
* @return whether to filter the {@link ChannelConversion}
*/
private boolean isFiltered(ChannelConversion channelConversion) {
return this.conversionFilterCache.computeIfAbsent(
channelConversion,
key -> key.isFiltered(this.cardinality, this.numExecutions, this.optimizationContextCopy)
);
}
private void createJunction(Tree tree) {
List<OptimizationContext> localOptimizationContexts = this.forkLocalOptimizationContext();
// Create the a new Junction.
final Junction junction = new Junction(this.sourceOutput, this.destInputs, localOptimizationContexts);
Channel sourceChannel = this.existingChannels.get(this.sourceChannelDescriptor);
if (sourceChannel == null) {
sourceChannel = this.sourceChannelDescriptor.createChannel(this.sourceOutput, this.optimizationContext.getConfiguration());
}
junction.setSourceChannel(sourceChannel);
this.createJunctionAux(tree.root, sourceChannel, junction);
// Assign appropriate LoopSubplans to the newly created ExecutionTasks.
// Determine the LoopSubplan from the "source side" of the Junction.
final OutputSlot<?> sourceOutput = sourceChannel.getProducerSlot();
final ExecutionOperator sourceOperator = (ExecutionOperator) sourceOutput.getOwner();
final LoopSubplan sourceLoop =
(!sourceOperator.isLoopHead() || sourceOperator.isFeedforwardOutput(sourceOutput)) ?
sourceOperator.getInnermostLoop() : null;
if (sourceLoop != null) {
// If the source side is determining a LoopSubplan, it should be what the "target sides" request.
for (int destIndex = 0; destIndex < this.destInputs.size(); destIndex++) {
assert this.destInputs.get(destIndex).getOwner().getInnermostLoop() == sourceLoop :
String.format(
"Expected that %s would belong to %s, just as %s does.",
this.destInputs.get(destIndex), sourceLoop, sourceOutput
);
Channel targetChannel = junction.getTargetChannel(destIndex);
while (targetChannel != sourceChannel) {
final ExecutionTask producer = targetChannel.getProducer();
producer.getOperator().setContainer(sourceLoop);
assert producer.getNumInputChannels() == 1 : String.format(
"Glue operator %s was expected to have exactly one input channel.",
producer
);
targetChannel = producer.getInputChannel(0);
}
}
}
assert tree.settledDestinationIndices.stream().allMatch(i -> junction.getTargetChannel(i) != null) :
String.format("Junction from %s to %s has no target channels.",
junction.getSourceOutput(),
tree.settledDestinationIndices.stream()
.filter(idx -> junction.getTargetChannel(idx) == null)
.mapToObj(idx -> String.format("%s (index=%d)", this.destInputs.get(idx), idx))
.collect(Collectors.joining(" and "))
);
// CHECK: We don't need to worry about entering loops, because in this case #resolveSupportedChannels(...)
// does all the magic!?
this.result = junction;
}
/**
* Helper function to create a {@link Junction} from a {@link Tree}.
*
* @param vertex the currently iterated {@link TreeVertex} (start at the root)
* @param baseChannel the corresponding {@link Channel}
* @param junction that is being initialized
*/
private void createJunctionAux(TreeVertex vertex, Channel baseChannel, Junction junction) {
Channel baseChannelCopy = null;
for (int index = vertex.settledIndices.nextSetBit(0);
index >= 0;
index = vertex.settledIndices.nextSetBit(index + 1)) {
// Beware that, if the base channel is existent (and open), we need to create a copy for any new
// destinations.
if (!this.existingDestinationChannelIndices.get(index) && this.openChannelDescriptors.contains(baseChannel.getDescriptor())) {
if (baseChannelCopy == null) baseChannelCopy = baseChannel.copy();
junction.setTargetChannel(index, baseChannelCopy);
} else {
junction.setTargetChannel(index, baseChannel);
}
}
for (TreeEdge edge : vertex.outEdges) {
// See if there is an already existing channel in place.
Channel newChannel = this.existingChannels.get(edge.channelConversion.getTargetChannelDescriptor());
// Otherwise, create a new channel conversion.
if (newChannel == null) {
// Beware that, if the base channel is existent (and open), we need to create a copy of it for the
// new channel conversions.
if (baseChannelCopy == null) {
baseChannelCopy = this.openChannelDescriptors.contains(baseChannel.getDescriptor()) ?
baseChannel.copy() :
baseChannel;
}
newChannel = edge.channelConversion.convert(
baseChannelCopy,
this.optimizationContext.getConfiguration(),
junction.getOptimizationContexts(),
// Hacky: Inject cardinality for cases where we convert a LoopHeadOperator output.
junction.getOptimizationContexts().size() == 1 ? this.cardinality : null
);
} else {
edge.channelConversion.update(
baseChannel,
newChannel,
junction.getOptimizationContexts(),
// Hacky: Inject cardinality for cases where we convert a LoopHeadOperator output.
junction.getOptimizationContexts().size() == 1 ? this.cardinality : null
);
}
if (baseChannel != newChannel) {
final ExecutionTask producer = newChannel.getProducer();
final ExecutionOperator conversionOperator = producer.getOperator();
conversionOperator.setName(String.format(
"convert %s", junction.getSourceOutput()
));
junction.register(producer);
}
this.createJunctionAux(edge.destination, newChannel, junction);
}
}
/**
* Creates a new {@link OptimizationContext} that forks
* <ul>
* <li>the given {@code optimizationContext}'s parent if the {@link #sourceOutput} is the final
* {@link OutputSlot} of a {@link LoopHeadOperator}</li>
* <li>or else the given {@code optimizationContext}.</li>
* </ul>
* We have to do this because in the former case the {@link Junction} {@link ExecutionOperator}s should not
* reside in a loop {@link OptimizationContext}.
*
* @return the forked {@link OptimizationContext}
*/
// TODO: Refactor this.
private List<OptimizationContext> forkLocalOptimizationContext() {
OptimizationContext baseOptimizationContext =
this.sourceOutput.getOwner().isLoopHead() && !this.sourceOutput.isFeedforward() ?
this.optimizationContext.getParent() :
this.optimizationContext;
return baseOptimizationContext.getDefaultOptimizationContexts().stream()
.map(DefaultOptimizationContext::new)
.collect(Collectors.toList());
}
}
/**
* A tree consisting of {@link TreeVertex}es connected by {@link TreeEdge}s.
*/
private static class Tree {
/**
* The root node of this instance.
*/
private TreeVertex root;
/**
* The union of all settled indices of the contained {@link TreeVertex}es in this instance.
*
* @see TreeVertex#settledIndices
*/
private final Bitmask settledDestinationIndices;
/**
* The {@link Set} of {@link ChannelDescriptor}s in all {@link TreeVertex}es of this instance.
*
* @see TreeVertex#channelDescriptor
*/
private final Set<ChannelDescriptor> employedChannelDescriptors = new HashSet<>();
/**
* The sum of the costs of all {@link TreeEdge}s of this instance.
*/
private double costs = 0d;
/**
* Creates a new instance with a single {@link TreeVertex}.
*
* @param channelDescriptor represented by the {@link TreeVertex}
* @param settledIndices indices to destinations settled by the {@code channelDescriptor}
* @return the new instance
*/
static Tree singleton(ChannelDescriptor channelDescriptor, Bitmask settledIndices) {
return new Tree(new TreeVertex(channelDescriptor, settledIndices), new Bitmask(settledIndices));
}
Tree(TreeVertex root, Bitmask settledDestinationIndices) {
this.root = root;
this.settledDestinationIndices = settledDestinationIndices;
this.employedChannelDescriptors.add(root.channelDescriptor);
}
/**
* Push down the {@link #root} of this instance by adding a new {@link TreeVertex} as root and put the old
* root as its child node.
*
* @param newRootChannelDescriptor will be wrapped in the new {@link #root}
* @param newRootSettledIndices destination indices settled by the {@code newRootChannelDescriptor}
* @param newToObsoleteRootConversion used to establish the {@link TreeEdge} between the old and new {@link #root}
* @param costEstimate of the {@code newToObsoleteRootConversion}
*/
void reroot(ChannelDescriptor newRootChannelDescriptor,
Bitmask newRootSettledIndices,
ChannelConversion newToObsoleteRootConversion,
double costEstimate) {
// Exchange the root.
final TreeVertex newRoot = new TreeVertex(newRootChannelDescriptor, newRootSettledIndices);
final TreeEdge edge = newRoot.linkTo(newToObsoleteRootConversion, this.root, costEstimate);
this.root = newRoot;
// Update metadata.
this.employedChannelDescriptors.add(newRootChannelDescriptor);
this.settledDestinationIndices.orInPlace(newRootSettledIndices);
this.costs += edge.costEstimate;
}
@Override
public String toString() {
return String.format("%s[%s, %s]", this.getClass().getSimpleName(), this.costs, this.root.getChildChannelConversions());
}
}
/**
* Vertex in a {@link Tree}. Corresponds to a {@link ChannelDescriptor}.
*/
private static class TreeVertex {
/**
* The {@link ChannelDescriptor} represented by this instance.
*/
private final ChannelDescriptor channelDescriptor;
/**
* {@link TreeEdge}s to child {@link TreeVertex}es.
*/
private final List<TreeEdge> outEdges;
/**
* Indices to settled {@link ShortestTreeSearcher#destInputs}.
*/
private final Bitmask settledIndices;
/**
* Creates a new instance.
*
* @param channelDescriptor to be represented by this instance
* @param settledIndices indices to settled destinations
*/
private TreeVertex(ChannelDescriptor channelDescriptor, Bitmask settledIndices) {
this.channelDescriptor = channelDescriptor;
this.settledIndices = settledIndices;
this.outEdges = new ArrayList<>(4);
}
private TreeEdge linkTo(ChannelConversion channelConversion, TreeVertex destination, double costEstimate) {
final TreeEdge edge = new TreeEdge(channelConversion, destination, costEstimate);
this.outEdges.add(edge);
return edge;
}
private void copyEdgesFrom(TreeVertex that) {
assert this.channelDescriptor.equals(that.channelDescriptor);
this.outEdges.addAll(that.outEdges);
}
/**
* Collects all {@link ChannelConversion}s employed by (indirectly) outgoing {@link TreeEdge}s.
*
* @return a {@link Set} of said {@link ChannelConversion}s
*/
private Set<ChannelConversion> getChildChannelConversions() {
Set<ChannelConversion> channelConversions = new HashSet<>();
for (TreeEdge edge : this.outEdges) {
channelConversions.add(edge.channelConversion);
channelConversions.addAll(edge.destination.getChildChannelConversions());
}
return channelConversions;
}
@Override
public String toString() {
return String.format("%s[%s]", this.getClass().getSimpleName(), this.channelDescriptor);
}
}
/**
* Edge in a {@link Tree}.
*/
private static class TreeEdge {
/**
* The target {@link TreeVertex}.
*/
private final TreeVertex destination;
/**
* The {@link ChannelConversion} represented by this instance.
*/
private final ChannelConversion channelConversion;
/**
* The cost estimate of the {@link #channelConversion}.
*/
private final double costEstimate;
private TreeEdge(ChannelConversion channelConversion, TreeVertex destination, double costEstimate) {
this.channelConversion = channelConversion;
this.destination = destination;
this.costEstimate = costEstimate;
}
@Override
public String toString() {
return String.format("%s[%s, %s]", this.getClass().getSimpleName(), this.channelConversion, this.costEstimate);
}
}
}
|
3e06c9bfab46d32df5f3026e170dba285500483e
| 1,481 |
java
|
Java
|
android/src/com/marpies/ane/androidutils/functions/HideWindowStatusBarFunction.java
|
marpies/air-android-utils
|
6b2aa0706aa06868e9fbccf4fa8bf846d207b82a
|
[
"Apache-2.0"
] | 20 |
2015-11-02T16:52:28.000Z
|
2021-03-23T11:06:00.000Z
|
android/src/com/marpies/ane/androidutils/functions/HideWindowStatusBarFunction.java
|
marpies/air-android-utils
|
6b2aa0706aa06868e9fbccf4fa8bf846d207b82a
|
[
"Apache-2.0"
] | 2 |
2019-09-09T22:30:42.000Z
|
2021-02-17T09:43:54.000Z
|
android/src/com/marpies/ane/androidutils/functions/HideWindowStatusBarFunction.java
|
marpies/air-android-utils
|
6b2aa0706aa06868e9fbccf4fa8bf846d207b82a
|
[
"Apache-2.0"
] | 8 |
2015-11-09T08:04:36.000Z
|
2022-01-25T08:58:08.000Z
| 32.911111 | 76 | 0.760972 | 2,886 |
/**
* Copyright 2016 Marcel Piestansky (http://marpies.com)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.marpies.ane.androidutils.functions;
import android.os.Build;
import android.view.Window;
import android.view.WindowManager;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREObject;
import com.marpies.ane.androidutils.utils.AIR;
public class HideWindowStatusBarFunction extends BaseFunction {
@Override
public FREObject call( FREContext context, FREObject[] args ) {
super.call( context, args );
Window window = AIR.getContext().getActivity().getWindow();
window.clearFlags( WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN );
/* Enabled translucent status bar on Kitkat and above */
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ) {
window.addFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS );
}
window.addFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN );
return null;
}
}
|
3e06cab39fe39a80bf81a3450852f6a538a1eddc
| 1,029 |
java
|
Java
|
bundles/specmate-emfrest/src/com/specmate/emfrest/internal/TransactionFactory.java
|
Qualicen/Specmate
|
7a4411d14c6c7d4c9127eb64690c33121ac47a39
|
[
"Apache-2.0"
] | 7 |
2019-10-17T10:53:40.000Z
|
2022-03-02T12:43:30.000Z
|
bundles/specmate-emfrest/src/com/specmate/emfrest/internal/TransactionFactory.java
|
Qualicen/Specmate
|
7a4411d14c6c7d4c9127eb64690c33121ac47a39
|
[
"Apache-2.0"
] | 180 |
2019-09-30T11:23:47.000Z
|
2022-03-03T18:38:32.000Z
|
bundles/specmate-emfrest/src/com/specmate/emfrest/internal/TransactionFactory.java
|
Qualicen/Specmate
|
7a4411d14c6c7d4c9127eb64690c33121ac47a39
|
[
"Apache-2.0"
] | 11 |
2019-12-07T12:46:38.000Z
|
2021-02-08T14:11:45.000Z
| 27.078947 | 84 | 0.759961 | 2,887 |
package com.specmate.emfrest.internal;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.PerThread;
import org.osgi.service.log.Logger;
import com.specmate.common.exception.SpecmateException;
import com.specmate.persistency.IPersistencyService;
import com.specmate.persistency.ITransaction;
public class TransactionFactory implements Factory<ITransaction> {
private IPersistencyService persistencyService;
private Logger logger;
public TransactionFactory(IPersistencyService persistencyService, Logger logger) {
this.persistencyService = persistencyService;
this.logger = logger;
}
@Override
public void dispose(ITransaction transaction) {
transaction.close();
}
@PerThread
@Override
public ITransaction provide() {
try {
logger.debug("Create new transaction.");
return persistencyService.openTransaction();
} catch (SpecmateException e) {
logger.error("Transaction factory could not create new transaction.", e);
return null;
}
}
}
|
3e06cb94c1d2bce0f85a636d7108b99963b02850
| 16,650 |
java
|
Java
|
xui_lib/src/main/java/com/xuexiang/xui/widget/edittext/verify/VerifyCodeEditText.java
|
dandycheung/XUI
|
9f10d357a60c428ab36931a4841c5176d9b9502f
|
[
"Apache-2.0"
] | null | null | null |
xui_lib/src/main/java/com/xuexiang/xui/widget/edittext/verify/VerifyCodeEditText.java
|
dandycheung/XUI
|
9f10d357a60c428ab36931a4841c5176d9b9502f
|
[
"Apache-2.0"
] | null | null | null |
xui_lib/src/main/java/com/xuexiang/xui/widget/edittext/verify/VerifyCodeEditText.java
|
dandycheung/XUI
|
9f10d357a60c428ab36931a4841c5176d9b9502f
|
[
"Apache-2.0"
] | null | null | null | 31.714286 | 195 | 0.583123 | 2,888 |
package com.xuexiang.xui.widget.edittext.verify;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.xuexiang.xui.R;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
/**
* 验证码输入框
*
* @author XUE
* @since 2019/5/7 11:22
*/
public class VerifyCodeEditText extends FrameLayout {
private static final int DEFAULT_HEIGHT = 50;
private static final int DEFAULT_EDIT_TEXT_SIZE = 4;
private LinearLayout mLlContainer;
private PwdEditText mEditText;
/**
* 输入框数量
*/
private int mEtNumber;
/**
* 输入框的宽度
*/
private int mEtWidth;
/**
* 是否等分输入框
*/
private boolean mIsDivideEqually;
/**
* 输入框分割线
*/
private Drawable mEtDivider;
/**
* 输入框文字颜色
*/
private int mEtTextColor;
/**
* 输入框文字大小
*/
private float mEtTextSize;
/**
* 输入框获取焦点时背景
*/
private Drawable mBackgroundFocus;
/**
* 输入框没有焦点时背景
*/
private Drawable mBackgroundNormal;
/**
* 是否是密码模式
*/
private boolean mIsPwd;
/**
* 密码模式时圆的半径
*/
private float mPwdRadius;
/**
* 存储TextView的数据 数量由自定义控件的属性传入
*/
private PwdTextView[] mPwdTextViews;
private InputNumberTextWatcher mTextWatcher = new InputNumberTextWatcher();
public VerifyCodeEditText(Context context) {
this(context, null);
}
public VerifyCodeEditText(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.VerifyCodeEditTextStyle);
}
public VerifyCodeEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
/**
* 初始化 布局和属性
*
* @param context 上下文
* @param attrs 属性
* @param defStyleAttr 默认属性
*/
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
LayoutInflater.from(context).inflate(R.layout.xui_layout_verify_code, this);
mLlContainer = findViewById(R.id.ll_container);
mEditText = findViewById(R.id.et_input);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.VerifyCodeEditText, defStyleAttr, 0);
mEtNumber = typedArray.getInteger(R.styleable.VerifyCodeEditText_vcet_number, DEFAULT_EDIT_TEXT_SIZE);
mEtWidth = typedArray.getDimensionPixelSize(R.styleable.VerifyCodeEditText_vcet_width, ResUtils.getDimensionPixelSize(R.dimen.default_vcet_width));
mIsDivideEqually = typedArray.getBoolean(R.styleable.VerifyCodeEditText_vcet_is_divide_equally, false);
mEtDivider = ResUtils.getDrawableAttrRes(context, typedArray, R.styleable.VerifyCodeEditText_vcet_divider);
mEtTextSize = typedArray.getDimensionPixelSize(R.styleable.VerifyCodeEditText_vcet_text_size, ResUtils.getDimensionPixelSize(R.dimen.default_vcet_text_size));
mEtTextColor = typedArray.getColor(R.styleable.VerifyCodeEditText_vcet_text_color, Color.BLACK);
mBackgroundFocus = ResUtils.getDrawableAttrRes(context, typedArray, R.styleable.VerifyCodeEditText_vcet_bg_focus);
mBackgroundNormal = ResUtils.getDrawableAttrRes(context, typedArray, R.styleable.VerifyCodeEditText_vcet_bg_normal);
mIsPwd = typedArray.getBoolean(R.styleable.VerifyCodeEditText_vcet_is_pwd, false);
mPwdRadius = typedArray.getDimensionPixelSize(R.styleable.VerifyCodeEditText_vcet_pwd_radius, ResUtils.getDimensionPixelSize(R.dimen.default_vcet_pwd_radius));
//释放资源
typedArray.recycle();
// 当xml中未配置时 这里进行初始配置默认图片
if (mEtDivider == null) {
mEtDivider = ResUtils.getDrawable(context, R.drawable.vcet_shape_divider);
}
if (mBackgroundFocus == null) {
mBackgroundFocus = ResUtils.getDrawable(context, R.drawable.vcet_shape_bg_focus);
}
if (mBackgroundNormal == null) {
mBackgroundNormal = ResUtils.getDrawable(context, R.drawable.vcet_shape_bg_normal);
}
// 平分每个输入框的宽度
if (mIsDivideEqually) {
post(new Runnable() {
@Override
public void run() {
refreshEditSizeWhenDivideEqually();
initView(getContext());
}
});
} else {
initView(context);
}
}
private void refreshEditSizeWhenDivideEqually() {
MarginLayoutParams params = (MarginLayoutParams) getLayoutParams();
int dividerWidth = mEtDivider != null ? mEtDivider.getMinimumWidth() : 0;
mEtWidth = (DensityUtils.getDisplayWidth(getContext(), true) - dividerWidth * (mEtNumber - 1) - getPaddingLeft() - getPaddingRight() - params.leftMargin - params.rightMargin) / mEtNumber;
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mIsDivideEqually) {
String input = getInputValue();
mEditText.removeTextChangedListener(mTextWatcher);
mLlContainer.removeAllViews();
refreshEditSizeWhenDivideEqually();
restoreView(getContext(), input);
}
}
private void restoreView(Context context, String input) {
initTextViews(context, mEtNumber, mEtWidth, mEtDivider, mEtTextSize, mEtTextColor);
initEtContainer(mPwdTextViews);
if (!TextUtils.isEmpty(input)) {
String[] strArray = input.split("");
for (int i = 0; i < strArray.length; i++) {
// 不能大于输入框个数
if (i > mEtNumber) {
break;
}
setText(strArray[i], true);
}
}
setListener();
}
/**
* 初始化控件
*
* @param context 上下文
*/
private void initView(Context context) {
initTextViews(context, mEtNumber, mEtWidth, mEtDivider, mEtTextSize, mEtTextColor);
initEtContainer(mPwdTextViews);
setListener();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpecValue = heightMeasureSpec;
int heightMode = MeasureSpec.getMode(heightMeasureSpecValue);
if (heightMode == MeasureSpec.AT_MOST) {
// 设置当高为 warpContent 模式时的最小高度是50dp
int minHeight = (int) dp2px(DEFAULT_HEIGHT, getContext());
if (mEtWidth < minHeight) {
heightMeasureSpecValue = MeasureSpec.makeMeasureSpec(minHeight, MeasureSpec.EXACTLY);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpecValue);
}
/**
* 初始化TextView
*
* @param context 上下文
* @param etNumber 输入长度
* @param etWidth 输入框宽度
* @param etDividerDrawable 分割线
* @param etTextSize 输入文字大小
* @param etTextColor 输入文字颜色
*/
private void initTextViews(Context context, int etNumber, int etWidth, Drawable etDividerDrawable, float etTextSize, int etTextColor) {
// 设置 editText 的输入长度
// 将光标隐藏
mEditText.setCursorVisible(false);
//最大输入长度
mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(etNumber)});
// 设置分割线的宽度
if (etDividerDrawable != null) {
etDividerDrawable.setBounds(0, 0, etDividerDrawable.getMinimumWidth(), etDividerDrawable.getMinimumHeight());
mLlContainer.setDividerDrawable(etDividerDrawable);
}
mPwdTextViews = new PwdTextView[etNumber];
for (int i = 0; i < mPwdTextViews.length; i++) {
PwdTextView textView = new PwdTextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, etTextSize);
textView.setTextColor(etTextColor);
if (!mIsDivideEqually) {
textView.setWidth(etWidth);
}
textView.setHeight(etWidth);
if (i == 0) {
textView.setBackgroundDrawable(mBackgroundFocus);
} else {
textView.setBackgroundDrawable(mBackgroundNormal);
}
textView.setGravity(Gravity.CENTER);
textView.setFocusable(false);
mPwdTextViews[i] = textView;
}
}
/**
* 初始化存储TextView 的容器
*
* @param textViews 输入文字
*/
private void initEtContainer(TextView[] textViews) {
if (mIsDivideEqually) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mLlContainer.getLayoutParams();
if (layoutParams == null) {
layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
} else {
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
}
mLlContainer.setLayoutParams(layoutParams);
LinearLayout.LayoutParams childParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
childParams.weight = 1;
for (TextView textView : textViews) {
mLlContainer.addView(textView, childParams);
}
} else {
for (TextView textView : textViews) {
mLlContainer.addView(textView);
}
}
}
private void setListener() {
// 监听输入内容
mEditText.addTextChangedListener(mTextWatcher);
// 监听删除按键
mEditText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
onKeyDelete();
return true;
}
return false;
}
});
mEditText.setBackSpaceListener(new TInputConnection.BackspaceListener() {
@Override
public boolean onBackspace() {
onKeyDelete();
return true;
}
});
}
/**
* 设置输入
*
* @param inputContent 输入内容
* @param isSilent 是否静默输入
*/
private void setText(String inputContent, boolean isSilent) {
if (TextUtils.isEmpty(inputContent)) {
return;
}
for (int i = 0; i < mPwdTextViews.length; i++) {
PwdTextView tv = mPwdTextViews[i];
if ("".equals(tv.getText().toString().trim())) {
if (mIsPwd) {
tv.drawPassword(mPwdRadius);
}
tv.setText(inputContent);
tv.setBackgroundDrawable(mBackgroundNormal);
if (i < mEtNumber - 1) {
mPwdTextViews[i + 1].setBackgroundDrawable(mBackgroundFocus);
if (mOnInputListener != null && !isSilent) {
mOnInputListener.onChange(getInputValue());
}
} else if (i == mEtNumber - 1) {
if (mOnInputListener != null && !isSilent) {
mOnInputListener.onComplete(getInputValue());
}
}
break;
}
}
}
// 监听删除
private void onKeyDelete() {
for (int i = mPwdTextViews.length - 1; i >= 0; i--) {
PwdTextView tv = mPwdTextViews[i];
if (!"".equals(tv.getText().toString().trim())) {
if (mIsPwd) {
tv.clearPassword();
}
tv.setText("");
tv.setBackgroundDrawable(mBackgroundFocus);
if (i < mEtNumber - 1) {
mPwdTextViews[i + 1].setBackgroundDrawable(mBackgroundNormal);
if (i == 0) {
if (mOnInputListener != null) {
mOnInputListener.onClear();
}
} else {
if (mOnInputListener != null) {
mOnInputListener.onChange(getInputValue());
}
}
} else if (i == mEtNumber - 1) {
if (mOnInputListener != null) {
mOnInputListener.onChange(getInputValue());
}
}
break;
}
}
}
/**
* 获取输入文本
*
* @return string
*/
public String getInputValue() {
StringBuilder sb = new StringBuilder();
for (TextView tv : mPwdTextViews) {
sb.append(tv.getText().toString().trim());
}
return sb.toString();
}
/**
* 删除输入内容
*/
public void clearInputValue() {
for (int i = 0; i < mPwdTextViews.length; i++) {
if (i == 0) {
mPwdTextViews[i].setBackgroundDrawable(mBackgroundFocus);
} else {
mPwdTextViews[i].setBackgroundDrawable(mBackgroundNormal);
}
if (mIsPwd) {
mPwdTextViews[i].clearPassword();
}
mPwdTextViews[i].setText("");
}
if (mOnInputListener != null) {
mOnInputListener.onClear();
}
}
/**
* 设置输入框个数
*
* @param etNumber 输入框个数
*/
public void setEtNumber(int etNumber) {
mEtNumber = etNumber;
mEditText.removeTextChangedListener(mTextWatcher);
mLlContainer.removeAllViews();
if (mIsDivideEqually) {
refreshEditSizeWhenDivideEqually();
}
initView(getContext());
}
/**
* 获取输入的位数
*
* @return int
*/
public int getEtNumber() {
return mEtNumber;
}
/**
* 设置是否是密码模式 默认false
*
* @param isPwdMode 是否是密码模式
*/
public void setPwdMode(boolean isPwdMode) {
this.mIsPwd = isPwdMode;
}
/**
* 获取输入的EditText 用于外界设置键盘弹出
*
* @return EditText
*/
public EditText getEditText() {
return mEditText;
}
/**
* 输入完成 和 删除成功 的监听
*/
private OnInputListener mOnInputListener;
public void setOnInputListener(OnInputListener onInputListener) {
mOnInputListener = onInputListener;
}
/**
* 输入框监听
*/
public interface OnInputListener {
/**
* 输入完成
*
* @param input 输入内容
*/
void onComplete(String input);
/**
* 输入变化
*
* @param input 变化内容
*/
void onChange(String input);
/**
* 输入清空
*/
void onClear();
}
public float dp2px(float dpValue, Context context) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpValue, context.getResources().getDisplayMetrics());
}
public float sp2px(float spValue, Context context) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spValue, context.getResources().getDisplayMetrics());
}
/**
* 监听输入框输入的数量
*/
private class InputNumberTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
String inputStr = editable.toString();
if (!TextUtils.isEmpty(inputStr)) {
String[] strArray = inputStr.split("");
for (int i = 0; i < strArray.length; i++) {
// 不能大于输入框个数
if (i > mEtNumber) {
break;
}
setText(strArray[i], false);
mEditText.setText("");
}
}
}
}
}
|
3e06ccb4448d5a9873e9cead8011a2b79a701c0b
| 4,364 |
java
|
Java
|
src/main/java/org/snmp4j/CommunityTarget.java
|
trishafuntanilla/snmp4j
|
1f9394f41cf50c27e5f4ce71a458b230e46af8e2
|
[
"Apache-2.0"
] | 12 |
2018-10-24T10:52:21.000Z
|
2022-02-07T16:28:25.000Z
|
src/main/java/org/snmp4j/CommunityTarget.java
|
trishafuntanilla/snmp4j
|
1f9394f41cf50c27e5f4ce71a458b230e46af8e2
|
[
"Apache-2.0"
] | 6 |
2018-10-30T22:03:48.000Z
|
2020-10-11T19:24:44.000Z
|
src/main/java/org/snmp4j/CommunityTarget.java
|
trishafuntanilla/snmp4j
|
1f9394f41cf50c27e5f4ce71a458b230e46af8e2
|
[
"Apache-2.0"
] | 5 |
2019-01-09T16:09:54.000Z
|
2021-06-29T02:03:34.000Z
| 33.569231 | 116 | 0.684464 | 2,889 |
/*_############################################################################
_##
_## SNMP4J 2 - CommunityTarget.java
_##
_## Copyright (C) 2003-2016 Frank Fock and Jochen Katz (SNMP4J.org)
_##
_## 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.snmp4j;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModel;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Address;
import org.snmp4j.mp.SnmpConstants;
/**
* A <code>CommunityTarget</code> represents SNMP target properties for
* community based message processing models (SNMPv1 and SNMPv2c).
* @author Frank Fock
* @version 1.1
*/
public class CommunityTarget extends AbstractTarget {
static final long serialVersionUID = 147443821594052003L;
/**
* Default constructor.
*/
public CommunityTarget() {
setVersion(SnmpConstants.version1);
setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
setSecurityModel(SecurityModel.SECURITY_MODEL_SNMPv1);
}
/**
* Creates a fully specified community target.
* @param address
* the transport <code>Address</code> of the target.
* @param community
* the community to be used for the target.
*/
public CommunityTarget(Address address, OctetString community) {
super(address, community);
setVersion(SnmpConstants.version1);
setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
setSecurityModel(SecurityModel.SECURITY_MODEL_SNMPv1);
}
/**
* Gets the community octet string (which is the same as the security name).
* Thus, you can (and should) use {@link #getSecurityName()} directly.
* @return
* an <code>OctetString</code> instance, should be never <code>null</code> when using this target to send
* messages over community based SNMP (v1 and v2c).
*/
public OctetString getCommunity() {
return getSecurityName();
}
/**
* Sets the community octet sting. This is a convenience method to set the
* security name for community based SNMP (v1 and v2c). It basically checks
* that the community is not <code>null</code> and then calls {@link #setSecurityName(org.snmp4j.smi.OctetString)}
* with the supplied parameter.
* @param community
* an <code>OctetString</code> instance which must not be
* <code>null</code>.
*/
public void setCommunity(OctetString community) {
if (community == null) {
throw new IllegalArgumentException("Community must not be null");
}
setSecurityName(community);
}
@Override
public int getSecurityModel() {
switch (getVersion()) {
case SnmpConstants.version1:
return SecurityModel.SECURITY_MODEL_SNMPv1;
default:
return SecurityModel.SECURITY_MODEL_SNMPv2c;
}
}
@Override
public void setSecurityLevel(int securityLevel) {
if (securityLevel != SecurityLevel.NOAUTH_NOPRIV) {
throw new IllegalArgumentException("CommunityTarget only supports SecurityLevel.NOAUTH_NOPRIV");
}
super.setSecurityLevel(securityLevel);
}
@Override
public void setSecurityModel(int securityModel) {
switch (securityModel) {
case SecurityModel.SECURITY_MODEL_SNMPv1:
super.setSecurityModel(securityModel);
super.setVersion(SnmpConstants.version1);
break;
case SecurityModel.SECURITY_MODEL_SNMPv2c:
super.setSecurityModel(securityModel);
super.setVersion(SnmpConstants.version2c);
break;
default:
throw new UnsupportedOperationException("To set security model for a CommunityTarget, use setVersion");
}
}
public String toString() {
return "CommunityTarget["+toStringAbstractTarget()+']';
}
}
|
3e06cd5d2f9e29e0a44b5e40ff56f3e118c24580
| 23,297 |
java
|
Java
|
zm-mailbox/store/src/java-test/com/zimbra/cs/db/DbMailItemTest.java
|
hernad/zimbra9
|
cf61ffa40d9600ab255ef4516ca25029fff6603b
|
[
"Apache-2.0"
] | null | null | null |
zm-mailbox/store/src/java-test/com/zimbra/cs/db/DbMailItemTest.java
|
hernad/zimbra9
|
cf61ffa40d9600ab255ef4516ca25029fff6603b
|
[
"Apache-2.0"
] | null | null | null |
zm-mailbox/store/src/java-test/com/zimbra/cs/db/DbMailItemTest.java
|
hernad/zimbra9
|
cf61ffa40d9600ab255ef4516ca25029fff6603b
|
[
"Apache-2.0"
] | null | null | null | 63.130081 | 128 | 0.611762 | 2,890 |
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011, 2013, 2014, 2016 Synacor, Inc.
*
* 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,
* version 2 of the License.
*
* 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 <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.db;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.db.DbMailItem.QueryParams;
import com.zimbra.cs.db.DbPool.DbConnection;
import com.zimbra.cs.mailbox.Flag;
import com.zimbra.cs.mailbox.Flag.FlagInfo;
import com.zimbra.cs.mailbox.MailItem;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
/**
* Unit test for {@link DbMailItem}.
*
* @author ysasaki
*/
public final class DbMailItemTest {
@BeforeClass
public static void init() throws Exception {
MailboxTestUtil.initServer();
Provisioning prov = Provisioning.getInstance();
prov.createAccount("[email protected]", "secret", new HashMap<String, Object>());
}
private DbConnection conn = null;
private Mailbox mbox = null;
@Before
public void setUp() throws Exception {
MailboxTestUtil.clearData();
mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
conn = DbPool.getConnection(mbox);
}
@After
public void tearDown() {
conn.closeQuietly();
}
@Test
public void getIndexDeferredIds() throws Exception {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 100, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 101, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 102, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 103, MailItem.Type.MESSAGE.toByte(), 103);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 200, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 201, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 202, MailItem.Type.CONTACT.toByte(), 202);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 300, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 301, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 302, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 303, MailItem.Type.MESSAGE.toByte(), 303);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 400, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 401, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 402, MailItem.Type.CONTACT.toByte(), 402);
Multimap<MailItem.Type, Integer> result = DbMailItem.getIndexDeferredIds(conn, mbox);
Assert.assertEquals(10, result.size());
Assert.assertEquals(ImmutableSet.of(100, 101, 102, 300, 301, 302), result.get(MailItem.Type.MESSAGE));
Assert.assertEquals(ImmutableSet.of(200, 201, 400, 401), result.get(MailItem.Type.CONTACT));
}
@Test
public void setIndexIds() throws Exception {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 100, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 200, MailItem.Type.MESSAGE.toByte(), 0);
DbMailItem.setIndexIds(conn, mbox, ImmutableList.of(100, 200));
Assert.assertEquals(100, DbUtil.executeQuery(conn,
"SELECT index_id FROM mboxgroup1.mail_item WHERE id = ?", 100).getInt(1));
Assert.assertEquals(200, DbUtil.executeQuery(conn,
"SELECT index_id FROM mboxgroup1.mail_item_dumpster WHERE id = ?", 200).getInt(1));
}
@Test
public void getReIndexIds() throws Exception {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 100, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 101, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 102, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 103, MailItem.Type.MESSAGE.toByte(), null);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 200, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 201, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 202, MailItem.Type.CONTACT.toByte(), null);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 300, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 301, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 302, MailItem.Type.MESSAGE.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 303, MailItem.Type.MESSAGE.toByte(), null);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 400, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 401, MailItem.Type.CONTACT.toByte(), 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 402, MailItem.Type.CONTACT.toByte(), null);
Assert.assertEquals(ImmutableList.of(100, 101, 102, 300, 301, 302),
DbMailItem.getReIndexIds(conn, mbox, EnumSet.<MailItem.Type>of(MailItem.Type.MESSAGE)));
Assert.assertEquals(ImmutableList.of(200, 201, 400, 401),
DbMailItem.getReIndexIds(conn, mbox, EnumSet.<MailItem.Type>of(MailItem.Type.CONTACT)));
Assert.assertEquals(ImmutableList.of(100, 101, 102, 200, 201, 300, 301, 302, 400, 401),
DbMailItem.getReIndexIds(conn, mbox, EnumSet.<MailItem.Type>noneOf(MailItem.Type.class)));
}
@Test
public void resetIndexId() throws Exception {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 100, MailItem.Type.MESSAGE.toByte(), 100);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item_dumpster " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, 0, 0, 0, 0, 0, 0)", mbox.getId(), 200, MailItem.Type.MESSAGE.toByte(), 200);
DbMailItem.resetIndexId(conn, mbox);
Assert.assertEquals(0, DbUtil.executeQuery(conn,
"SELECT index_id FROM mboxgroup1.mail_item WHERE id = ?", 100).getInt(1));
Assert.assertEquals(0, DbUtil.executeQuery(conn,
"SELECT index_id FROM mboxgroup1.mail_item_dumpster WHERE id = ?", 200).getInt(1));
}
@Test
public void completeConversation() throws Exception {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, 0, 0, 0, 0, 0, 0, 0)", mbox.getId(), 200, MailItem.Type.CONVERSATION.toByte());
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, 0, 0, 0, 0, 0, 0, 0)", mbox.getId(), 201, MailItem.Type.CONVERSATION.toByte());
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, folder_id, parent_id, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, ?, 0, 0, 0, ?, 0, 0, 0)", mbox.getId(), 100, MailItem.Type.MESSAGE.toByte(),
Mailbox.ID_FOLDER_INBOX, 200, 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, folder_id, parent_id, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, ?, 0, 0, 0, ?, 0, 0, 0)", mbox.getId(), 101, MailItem.Type.MESSAGE.toByte(),
Mailbox.ID_FOLDER_INBOX, 200, 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, folder_id, parent_id, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, ?, 0, 0, 0, ?, 0, 0, 0)", mbox.getId(), 102, MailItem.Type.MESSAGE.toByte(),
Mailbox.ID_FOLDER_INBOX, 200, 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, folder_id, parent_id, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, ?, 0, 0, 0, ?, 0, 0, 0)", mbox.getId(), 103, MailItem.Type.MESSAGE.toByte(),
Mailbox.ID_FOLDER_INBOX, 201, Flag.BITMASK_FROM_ME);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, folder_id, parent_id, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, ?, 0, 0, 0, ?, 0, 0, 0)", mbox.getId(), 104, MailItem.Type.MESSAGE.toByte(),
Mailbox.ID_FOLDER_INBOX, 201, 0);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, folder_id, parent_id, index_id, date, size, flags, tags, mod_metadata, mod_content) " +
"VALUES(?, ?, ?, ?, ?, 0, 0, 0, ?, 0, 0, 0)", mbox.getId(), 105, MailItem.Type.MESSAGE.toByte(),
Mailbox.ID_FOLDER_INBOX, 201, 0);
MailItem.UnderlyingData data = new MailItem.UnderlyingData();
data.id = 200;
data.type = MailItem.Type.CONVERSATION.toByte();
DbMailItem.completeConversation(mbox, conn, data);
Assert.assertFalse(data.isSet(Flag.FlagInfo.FROM_ME));
data = new MailItem.UnderlyingData();
data.id = 201;
data.type = MailItem.Type.CONVERSATION.toByte();
DbMailItem.completeConversation(mbox, conn, data);
Assert.assertTrue(data.isSet(Flag.FlagInfo.FROM_ME));
}
@Test
public void getIds() throws Exception {
int now = (int) (System.currentTimeMillis()/1000);
int beforeNow = now - 1000;
int afterNow = now + 1000;
int deleteNow = now + 2000;
final int beforeNowCount = 9;
final int afterNowCount = 13;
final int notDeleteCount = 7;
final int deleteCount = 17;
int id = 100;
Set<Integer> ids = DbMailItem.getIds(mbox, conn, new QueryParams(), false);
QueryParams params = new QueryParams();
params.setChangeDateBefore(now);
Set<Integer> idsInitBeforeNow = DbMailItem.getIds(mbox, conn, params, false);
params = new QueryParams();
params.setChangeDateAfter(now);
Set<Integer> idsInitAftereNow = DbMailItem.getIds(mbox, conn, params, false);
int idsInit = ids.size();
for (int i = 0; i < beforeNowCount; i++) {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, change_date, mod_content) " +
"VALUES(?, ?, ?, 0, 0, 0, 0, 0, 0, ?, 0)", mbox.getId(), id++, MailItem.Type.MESSAGE.toByte(), beforeNow);
}
id = 200;
Set<Integer> idsAddBeforeNow = DbMailItem.getIds(mbox, conn, new QueryParams(), false);
Assert.assertTrue(beforeNowCount == idsAddBeforeNow.size() - idsInit);
for (int i = 0; i < afterNowCount; i++) {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, change_date, mod_content) " +
"VALUES(?, ?, ?, 0, 0, 0, 0, 0, 0, ?, 0)", mbox.getId(), id++, MailItem.Type.MESSAGE.toByte(), afterNow);
}
Set<Integer> idsAddAfterNow = DbMailItem.getIds(mbox, conn, new QueryParams(), false);
Assert.assertTrue(afterNowCount == idsAddAfterNow.size() - idsAddBeforeNow.size());
params = new QueryParams();
params.setChangeDateBefore(now);
Set<Integer> idsBeforeNow = DbMailItem.getIds(mbox, conn, params, false);
Assert.assertTrue((idsBeforeNow.size()-idsInitBeforeNow.size()) == beforeNowCount);
params = new QueryParams();
params.setChangeDateAfter(now);
Set<Integer> idsAfterNow = DbMailItem.getIds(mbox, conn, params, false);
Assert.assertTrue((idsAfterNow.size()-idsInitAftereNow.size()) == afterNowCount);
id = 300;
for (int i = 0; i < notDeleteCount; i++) {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, change_date, mod_content) " +
"VALUES(?, ?, ?, 0, 0, 0, 0, 0, 0, ?, 0)", mbox.getId(), id++, MailItem.Type.MESSAGE.toByte(), deleteNow);
}
for (int i = 0; i < deleteCount; i++) {
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.mail_item " +
"(mailbox_id, id, type, index_id, date, size, flags, tags, mod_metadata, change_date, mod_content) " +
"VALUES(?, ?, ?, 0, 0, 0, 128, 0, 0, ?, 0)", mbox.getId(), id++, MailItem.Type.MESSAGE.toByte(), deleteNow);
}
params = new QueryParams();
params.setChangeDateAfter(deleteNow-1);
Set<Integer> idsForDelete = DbMailItem.getIds(mbox, conn, params, false);
Assert.assertTrue(idsForDelete.size() == (deleteCount + notDeleteCount));
params.setFlagToExclude(FlagInfo.DELETED);
idsForDelete = DbMailItem.getIds(mbox, conn, params, false);
Assert.assertTrue(idsForDelete.size() == notDeleteCount);
}
@Test
public void readTombstones() throws Exception {
int now = (int) (System.currentTimeMillis() / 1000);
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.tombstone " +
"(mailbox_id, sequence, date, type, ids) " +
"VALUES(?, ?, ?, ?, ?)", mbox.getId(), 100, now, MailItem.Type.MESSAGE.toByte(), "1,2,3");
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.tombstone " +
"(mailbox_id, sequence, date, type, ids) " +
"VALUES(?, ?, ?, ?, ?)", mbox.getId(), 100, now, MailItem.Type.APPOINTMENT.toByte(), "11,12,13,14");
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.tombstone " +
"(mailbox_id, sequence, date, type, ids) " +
"VALUES(?, ?, ?, ?, ?)", mbox.getId(), 100, now, MailItem.Type.TASK.toByte(), "21,22,23,24,25");
DbUtil.executeUpdate(conn, "INSERT INTO mboxgroup1.tombstone " +
"(mailbox_id, sequence, date, type, ids) " +
"VALUES(?, ?, ?, ?, ?)", mbox.getId(), 100, now, MailItem.Type.CONTACT.toByte(), "31,32");
Set<MailItem.Type> types = new HashSet<MailItem.Type>();
types.add(MailItem.Type.MESSAGE);
List<Integer> tombstones = DbMailItem.readTombstones(mbox, conn, 0, types);
Assert.assertEquals(tombstones.size(), 3);
types.add(MailItem.Type.APPOINTMENT);
tombstones = DbMailItem.readTombstones(mbox, conn, 0, types);
Assert.assertEquals(tombstones.size(), 7);
types = new HashSet<MailItem.Type>();
types.add(MailItem.Type.APPOINTMENT);
tombstones = DbMailItem.readTombstones(mbox, conn, 0, types);
Assert.assertEquals(tombstones.size(), 4);
types = new HashSet<MailItem.Type>();
types.add(MailItem.Type.TASK);
tombstones = DbMailItem.readTombstones(mbox, conn, 0, types);
Assert.assertEquals(tombstones.size(), 5);
types = new HashSet<MailItem.Type>();
types.add(MailItem.Type.CONTACT);
tombstones = DbMailItem.readTombstones(mbox, conn, 0, types);
Assert.assertEquals(tombstones.size(), 2);
types = new HashSet<MailItem.Type>();
types.add(MailItem.Type.MESSAGE);
types.add(MailItem.Type.APPOINTMENT);
types.add(MailItem.Type.TASK);
tombstones = DbMailItem.readTombstones(mbox, conn, 0, types);
Assert.assertEquals(tombstones.size(), 12);
}
}
|
3e06ce4fb9dc41d118f3884cd93fa4cb3e123dbd
| 803 |
java
|
Java
|
server/src/au/com/codeka/warworlds/server/model/BuildingPosition.java
|
ronnysuero/wwmmo
|
55ef2be8a8c869680a162c2614074be53b9c4609
|
[
"MIT"
] | 1 |
2020-04-14T11:32:58.000Z
|
2020-04-14T11:32:58.000Z
|
server/src/au/com/codeka/warworlds/server/model/BuildingPosition.java
|
ronnysuero/wwmmo
|
55ef2be8a8c869680a162c2614074be53b9c4609
|
[
"MIT"
] | null | null | null |
server/src/au/com/codeka/warworlds/server/model/BuildingPosition.java
|
ronnysuero/wwmmo
|
55ef2be8a8c869680a162c2614074be53b9c4609
|
[
"MIT"
] | null | null | null | 23.617647 | 64 | 0.647572 | 2,891 |
package au.com.codeka.warworlds.server.model;
import java.sql.SQLException;
import au.com.codeka.warworlds.server.data.SqlResult;
public class BuildingPosition extends Building {
private long mSectorX;
private long mSectorY;
private int mOffsetX;
private int mOffsetY;
public BuildingPosition(SqlResult res) throws SQLException {
super(res);
mSectorX = res.getLong("sector_x");
mSectorY = res.getLong("sector_y");
mOffsetX = res.getInt("offset_x");
mOffsetY = res.getInt("offset_y");
}
public long getSectorX() {
return mSectorX;
}
public long getSectorY() {
return mSectorY;
}
public int getOffsetX() {
return mOffsetX;
}
public int getOffsetY() {
return mOffsetY;
}
}
|
3e06cf80db0e7ba1d7ec6feaab0479638fc85ab2
| 152 |
java
|
Java
|
src/main/java/rabbitmq/producer/exchanges/RoutingKeyTwoImpl.java
|
gustavotemple/RabbitMQproducer
|
c12d5af8604c702a87f76a4fdc90bfc460c356cb
|
[
"MIT"
] | null | null | null |
src/main/java/rabbitmq/producer/exchanges/RoutingKeyTwoImpl.java
|
gustavotemple/RabbitMQproducer
|
c12d5af8604c702a87f76a4fdc90bfc460c356cb
|
[
"MIT"
] | null | null | null |
src/main/java/rabbitmq/producer/exchanges/RoutingKeyTwoImpl.java
|
gustavotemple/RabbitMQproducer
|
c12d5af8604c702a87f76a4fdc90bfc460c356cb
|
[
"MIT"
] | null | null | null | 19 | 54 | 0.842105 | 2,892 |
package rabbitmq.producer.exchanges;
import org.springframework.stereotype.Service;
@Service
public class RoutingKeyTwoImpl extends RoutingKeyTwo {
}
|
3e06cfccc7e15c20fbcddb1d8e4bf4b0d7fd24bd
| 768 |
java
|
Java
|
src/main/java/nl/rug/oop/grapheditor/controller/items/remove/RemoveNode.java
|
rosarioscavo/Graph-Editor
|
1e3026aa4d85c25169d1f356de5b68e9c924b065
|
[
"MIT"
] | null | null | null |
src/main/java/nl/rug/oop/grapheditor/controller/items/remove/RemoveNode.java
|
rosarioscavo/Graph-Editor
|
1e3026aa4d85c25169d1f356de5b68e9c924b065
|
[
"MIT"
] | null | null | null |
src/main/java/nl/rug/oop/grapheditor/controller/items/remove/RemoveNode.java
|
rosarioscavo/Graph-Editor
|
1e3026aa4d85c25169d1f356de5b68e9c924b065
|
[
"MIT"
] | null | null | null | 27.428571 | 76 | 0.68099 | 2,893 |
package nl.rug.oop.grapheditor.controller.items.remove;
import nl.rug.oop.grapheditor.controller.undoRedo.remove.RemoveNodeUndoable;
import nl.rug.oop.grapheditor.model.GraphModel;
import javax.swing.*;
import static java.awt.event.KeyEvent.VK_DELETE;
public class RemoveNode extends JMenuItem {
/**
* Constructor for a button that allows the user to remove a node
*
* @param graph the graph the user is editing
*/
public RemoveNode(GraphModel graph) {
super("Remove Node");
setAccelerator(KeyStroke.getKeyStroke(
VK_DELETE, 0));
addActionListener(e -> {
RemoveNodeUndoable removeNode = new RemoveNodeUndoable(graph);
graph.addOperation(removeNode);
});
}
}
|
3e06d061cbce6231e449885ab6550fc6feb61a4f
| 754 |
java
|
Java
|
miracle-system/src/main/java/pers/miracle/miraclecloud/system/vo/UserRoleVO.java
|
miracle-peak/miracle-cloud
|
cb0469ef411e1d61af6ec7675b8332e33e2480fb
|
[
"MulanPSL-1.0"
] | 7 |
2020-09-10T12:26:20.000Z
|
2021-07-30T01:59:00.000Z
|
miracle-system/src/main/java/pers/miracle/miraclecloud/system/vo/UserRoleVO.java
|
miracle-peak/miracle-cloud
|
cb0469ef411e1d61af6ec7675b8332e33e2480fb
|
[
"MulanPSL-1.0"
] | null | null | null |
miracle-system/src/main/java/pers/miracle/miraclecloud/system/vo/UserRoleVO.java
|
miracle-peak/miracle-cloud
|
cb0469ef411e1d61af6ec7675b8332e33e2480fb
|
[
"MulanPSL-1.0"
] | 1 |
2020-11-05T07:09:42.000Z
|
2020-11-05T07:09:42.000Z
| 19.842105 | 83 | 0.615385 | 2,894 |
package pers.miracle.miraclecloud.system.vo;
import pers.miracle.miraclecloud.system.entity.Role;
import pers.miracle.miraclecloud.system.entity.User;
import java.util.List;
/**
* @author: 蔡奇峰
* @date: 2020/8/14 下午5:59
*/
public class UserRoleVO extends User {
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public UserRoleVO() {
}
public UserRoleVO(String userId, String userName, String mail, String locked) {
super(userId, userName, mail, locked);
}
@Override
public String toString() {
return "UserRoleVO{" +
"roles=" + roles +
'}';
}
}
|
3e06d0e74c5ea8d6ec6cb6bfe49bffc7aae3d4a0
| 269 |
java
|
Java
|
backend/src/main/java/com/bakdata/conquery/apiv1/OverviewExecutionStatus.java
|
manuel-hegner/conquery
|
94d7915e56e10187dd1c8298df962875d3f7a897
|
[
"MIT"
] | 29 |
2018-01-18T10:46:11.000Z
|
2022-02-15T00:27:29.000Z
|
backend/src/main/java/com/bakdata/conquery/apiv1/OverviewExecutionStatus.java
|
bakdata/conquery
|
94f44e9e42508d8b27884621f27395603a755f79
|
[
"MIT"
] | 818 |
2018-01-18T12:00:05.000Z
|
2022-03-29T09:14:22.000Z
|
backend/src/main/java/com/bakdata/conquery/apiv1/OverviewExecutionStatus.java
|
manuel-hegner/conquery
|
94d7915e56e10187dd1c8298df962875d3f7a897
|
[
"MIT"
] | 11 |
2018-10-22T22:20:42.000Z
|
2021-08-11T14:46:42.000Z
| 22.416667 | 104 | 0.810409 | 2,895 |
package com.bakdata.conquery.apiv1;
import lombok.NoArgsConstructor;
/**
* Light weight description of an execution. Rendering the overview should not cause heavy computations.
*/
@NoArgsConstructor
public class OverviewExecutionStatus extends ExecutionStatus {
}
|
3e06d0f33daa47ba1042b1d77e9b14fb0c0b68f2
| 2,265 |
java
|
Java
|
Codefest2021androidproject/app/src/main/java/com/heymeowcat/codefest2021androidproject/MyFirebaseMessagingService.java
|
heymeowcat/Codefest-2021-Android
|
91f6fe9a3f3ae6c733080cc04b6069df0ca10b47
|
[
"MIT"
] | null | null | null |
Codefest2021androidproject/app/src/main/java/com/heymeowcat/codefest2021androidproject/MyFirebaseMessagingService.java
|
heymeowcat/Codefest-2021-Android
|
91f6fe9a3f3ae6c733080cc04b6069df0ca10b47
|
[
"MIT"
] | null | null | null |
Codefest2021androidproject/app/src/main/java/com/heymeowcat/codefest2021androidproject/MyFirebaseMessagingService.java
|
heymeowcat/Codefest-2021-Android
|
91f6fe9a3f3ae6c733080cc04b6069df0ca10b47
|
[
"MIT"
] | null | null | null | 38.389831 | 136 | 0.709051 | 2,896 |
package com.heymeowcat.codefest2021androidproject;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title="";
String msg="";
if (remoteMessage.getData().size() > 0) {
title=remoteMessage.getData().get("title");
msg=remoteMessage.getData().get("message");
}
if (remoteMessage.getNotification() != null) {
title=remoteMessage.getNotification().getTitle();
msg=remoteMessage.getNotification().getBody();
}
// for forground :)
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(msg).setAutoCancel(true).setContentIntent(pendingIntent);;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
super.onMessageReceived(remoteMessage);
}
@Override
public void onNewToken(@NonNull String s) {
super.onNewToken(s);
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
}
|
3e06d1c46986a54e50a3eab5ede166644be1e079
| 5,230 |
java
|
Java
|
scala/scala-impl/src/org/jetbrains/plugins/scala/icons/Icons.java
|
EnverOsmanov/intellij-scala
|
5f2d7c8823d92212410fe43ca6b5bac5279191d6
|
[
"Apache-2.0"
] | 2 |
2018-08-19T02:34:41.000Z
|
2018-08-19T02:35:04.000Z
|
scala/scala-impl/src/org/jetbrains/plugins/scala/icons/Icons.java
|
smarter/intellij-scala
|
11887455c2f4a8f4af46b4e160c01298e9fed16e
|
[
"Apache-2.0"
] | null | null | null |
scala/scala-impl/src/org/jetbrains/plugins/scala/icons/Icons.java
|
smarter/intellij-scala
|
11887455c2f4a8f4af46b4e160c01298e9fed16e
|
[
"Apache-2.0"
] | 1 |
2018-09-24T23:40:48.000Z
|
2018-09-24T23:40:48.000Z
| 55.638298 | 124 | 0.777247 | 2,897 |
/*
* Copyright 2000-2008 JetBrains s.r.o.
* 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.jetbrains.plugins.scala.icons;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
/**
* @author ilyas
*/
public interface Icons {
Icon COMPILE_SERVER = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/compileServer.png");
Icon FILE_TYPE_LOGO = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/scala16.png");
//todo worksheet logo
Icon WORKSHEET_LOGO = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/file_scala.png");
Icon SCALA_SMALL_LOGO = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/scala-small-logo.png");
Icon SCRIPT_FILE_LOGO = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/scala_script_icon.png");
Icon ADD_CLAUSE = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/AddClause.png");
Icon REMOVE_CLAUSE = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/RemoveClause.png");
//SDK configuration
Icon SCALA_SDK = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/scala_sdk.png");
Icon NO_SCALA_SDK = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/no_scala_sdk.png");
//Toplevel nodes
Icon FILE = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/file_scala.png");
Icon CLASS = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/class_scala.png");
Icon ABSTRACT_CLASS = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/abstract_class_scala.png");
Icon TRAIT = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/trait_scala.png");
Icon OBJECT = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/object_scala.png");
Icon PACKAGE_OBJECT = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/package_object.png");
Icon CLASS_AND_OBJECT = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/class_object_scala.png");
Icon ABSTRACT_CLASS_AND_OBJECT = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/abstract_class_object_scala.png");
Icon TRAIT_AND_OBJECT = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/trait_object_scala.png");
//Internal nodes
Icon FIELD_VAR = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/field_variable.png");
Icon ABSTRACT_FIELD_VAR = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/abstract_field_variable.png");
Icon FIELD_VAL = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/field_value.png");
Icon ABSTRACT_FIELD_VAL = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/abstract_field_value.png");
Icon TYPE_ALIAS = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/type_alias.png");
Icon ABSTRACT_TYPE_ALIAS = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/abstract_type_alias.png");
Icon FUNCTION = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/function.png");
Icon VAR = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/variable.png");
Icon VAL = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/value.png");
Icon PARAMETER = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/parameter.png");
Icon PATTERN_VAL = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/pattern_value.png");
Icon LAMBDA = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/lambda.png");
//Testing support
Icon SCALA_TEST = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/scala_test_icon.png");
Icon SCALA_TEST_NODE = IconLoader.getIcon("/org/jetbrains/plugins/scala/nodes/scalaTest.png");
//Console
Icon SCALA_CONSOLE = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/scala_console.png");
// Highlighting (status bar)
Icon TYPED = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/typed.png");
Icon UNTYPED = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/untyped.png");
Icon ERROR = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/error.png");
Icon WARNING = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/warning.png");
Icon LIGHTBEND_LOGO = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/lightbend_logo.png");
// sbt
Icon SBT = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/sbt_icon.png");
// used from SBT.xml
Icon SBT_TOOLWINDOW = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/sbt_toolwin.png");
Icon SBT_FILE = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/sbt_file.png");
Icon SBT_FOLDER = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/sbt_folder.png");
Icon SBT_SHELL = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/sbt_shell.png");
// used from SBT.xml
Icon SBT_SHELL_TOOLWINDOW = IconLoader.getIcon("/org/jetbrains/plugins/scala/images/sbt_shell_toolwin.png");
}
|
3e06d3883b5329307c4530248afb344dd70972f6
| 6,800 |
java
|
Java
|
dlpractice-web/src/test/java/com/hzm/test/lucene/IndexCreate.java
|
hzmdream/dead_local
|
c0cfc5aaacefdfac29ed4002fd2784e56b766221
|
[
"MIT"
] | null | null | null |
dlpractice-web/src/test/java/com/hzm/test/lucene/IndexCreate.java
|
hzmdream/dead_local
|
c0cfc5aaacefdfac29ed4002fd2784e56b766221
|
[
"MIT"
] | null | null | null |
dlpractice-web/src/test/java/com/hzm/test/lucene/IndexCreate.java
|
hzmdream/dead_local
|
c0cfc5aaacefdfac29ed4002fd2784e56b766221
|
[
"MIT"
] | null | null | null | 32.692308 | 93 | 0.704412 | 2,898 |
package com.hzm.test.lucene;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.FloatField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import com.hzm.test.lucene.dao.BookDao;
import com.hzm.test.lucene.dao.impl.BookDaoImpl;
import com.hzm.test.lucene.pojo.Book;
public class IndexCreate {
@Test
public void create() throws IOException{
// 采集数据
BookDao dao = new BookDaoImpl();
List<Book> list = dao.queryBooks();
// 将采集到的数据封装到Document对象中
List<Document> documents = new ArrayList<Document>();
Document document;
for (Book book : list) {
document = new Document();
// store:如果是yes,则说明存储到文档域中
Field id = new StringField("id", book.getId().toString(), Store.YES); // 图书ID
Field name = new TextField("name", book.getName(), Store.YES);// 图书名称
Field price = new FloatField("price", book.getPrice(),Store.YES);// 图书价格
Field pic = new StoredField("pic", book.getPic());// 图书图片地址
Field description = new TextField("description",book.getDescription(), Store.YES);// 图书描述
// 将field域设置到Document对象中
document.add(id);
document.add(name);
document.add(price);
document.add(pic);
document.add(description);
documents.add(document);
}
Analyzer analyzer = new StandardAnalyzer();//创建分词器---标准分词器
IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);//创建保存索引的配置
File indexfile = new File("F:/tools_dead_local/lucene-home");//指定索引库的地址
Directory directory = FSDirectory.open(indexfile);
IndexWriter writer = new IndexWriter(directory, cfg);
for (Document doc : documents) {//通过IndexWriter对象将Document写入到索引库中
writer.addDocument(doc);
}
writer.close();// 关闭writer
}
/**
* @author houzm
* @time 2017年4月24日下午7:10:26
* @description
* @return void
*
* 通过Query子类来创建查询对象
* Query子类常用的有:TermQuery、NumericRangeQuery、BooleanQuery
* 不能输入lucene的查询语法,不需要指定分词器
* 通过QueryParser来创建查询对象(常用)
* QueryParser、MultiFieldQueryParser
* 可以输入lucene的查询语法、可以指定分词器
*
*/
//termQuery精确的词项查询
@Test
public void termQuery(){
Query query = new TermQuery(new Term("description","java"));
doSearch(query);
}
/**
* @author houzm
* @time 2017年4月24日下午7:38:01
* @description 数字范围查询--亲测中失败,本来应该有2条数据,但是返回0
* @return void
*/
@Test
public void numericRangeQuery(){
//创建NumericRangeQuery对象
//参数:域的名称,最小值,最大值,是否包含最小值,是否包含最大值
Query query = NumericRangeQuery.newFloatRange("price", 55f, 60f, true, true);
doSearch(query);
}
@Test
public void booleanQuery(){
//创建BooleanQuery
BooleanQuery query = new BooleanQuery();
//创建TermQuery对象
Query q1 = new TermQuery(new Term("description","java"));
Query q2 = NumericRangeQuery.newFloatRange("price", 55f, 60f, true, false);
query.add(q1, Occur.MUST);
query.add(q2, Occur.MUST);
doSearch(query);
}
private void doSearch(Query query) {
// 创建IndexSearcher
// 指定索引库的地址
try {
File indexFile = new File("F:/tools_dead_local/lucene-home");
Directory directory = FSDirectory.open(indexFile);
IndexReader reader = DirectoryReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader);
// 通过searcher来搜索索引库
// 第二个参数:指定需要显示的顶部记录的N条
TopDocs topDocs = searcher.search(query, 10);
// 根据查询条件匹配出的记录总数
int count = topDocs.totalHits;
System.out.println("匹配出的记录总数:" + count);
// 根据查询条件匹配出的记录
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
// 获取文档的ID
int docId = scoreDoc.doc;
// 通过ID获取文档
Document doc = searcher.doc(docId);
System.out.println("商品ID:" + doc.get("id"));
System.out.println("商品名称:" + doc.get("name"));
System.out.println("商品价格:" + doc.get("price"));
System.out.println("商品图片地址:" + doc.get("pic"));
System.out.println("==========================");
// System.out.println("商品描述:" + doc.get("description"));
}
// 关闭资源
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void deletedIndex() throws Exception{
//创建分词器,标准分词器
Analyzer analyzer = new StandardAnalyzer();
//创建IndexWriter
IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);
Directory directory = FSDirectory.open(new File("F:/tools_dead_local/lucene-home"));
//创建IndexWriter
IndexWriter writer = new IndexWriter(directory, cfg);
//Terms
writer.deleteDocuments(new Term("id", "1"));
writer.close();
}
@Test
public void deletedAll() throws Exception{
//创建分词器,标准分词器
Analyzer analyzer = new StandardAnalyzer();
//创建IndexWriter
IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);
Directory directory = FSDirectory.open(new File("F:/tools_dead_local/lucene-home"));
//创建IndexWriter
IndexWriter writer = new IndexWriter(directory, cfg);
//Terms
writer.deleteAll();
writer.close();
}
@Test
public void updateIndex() throws Exception{
//创建分词器,标准分词器
Analyzer analyzer = new StandardAnalyzer();
//创建IndexWriter
IndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_4_10_3, analyzer);
Directory directory = FSDirectory.open(new File("F:/tools_dead_local/lucene-home"));
//创建IndexWriter
IndexWriter writer = new IndexWriter(directory, cfg);
//第一个参数:指定查询条件
//第二个参数:修改后的对象
//修改时,如果根据查询条件,可以查询出结果,
// 则将以前的删掉,然后覆盖新的document对象,
// 如果没有查询出结果,则新增一个doc
Document doc = new Document();
doc.add(new TextField("name","lisi",Store.YES));
writer.updateDocument(new Term("name","houzm"), doc);
writer.close();
}
}
|
3e06d3b7294c415ef66ee64f13c13be255347cde
| 3,771 |
java
|
Java
|
jdk11/jdk.jshell/module-info.java
|
1446554749/jdk_11_src_read
|
b9c070d7232ee3cf5f2f6270e748ada74cbabb3f
|
[
"Apache-2.0"
] | 2 |
2018-06-19T05:43:32.000Z
|
2018-06-23T10:04:56.000Z
|
jdk11/jdk.jshell/module-info.java
|
1446554749/jdk_11_src_read
|
b9c070d7232ee3cf5f2f6270e748ada74cbabb3f
|
[
"Apache-2.0"
] | null | null | null |
jdk11/jdk.jshell/module-info.java
|
1446554749/jdk_11_src_read
|
b9c070d7232ee3cf5f2f6270e748ada74cbabb3f
|
[
"Apache-2.0"
] | null | null | null | 40.548387 | 93 | 0.730841 | 2,900 |
/*
* Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* This module provides support for
* Java Programming Language 'snippet' evaluating tools, such as
* Read-Eval-Print Loops (REPLs), including the <em>{@index jshell jshell tool}</em> tool.
* Separate packages support building tools, configuring the execution of tools,
* and programmatically launching the existing Java shell tool.
* <p>
* The {@link jdk.jshell} is the package for creating 'snippet' evaluating tools.
* Generally, this is only package that would be needed for creating tools.
* </p>
* <p>
* The {@link jdk.jshell.spi} package specifies a Service Provider Interface (SPI)
* for defining execution engine implementations for tools based on the
* {@link jdk.jshell} API. The {@link jdk.jshell.execution} package provides
* standard implementations of {@link jdk.jshell.spi} interfaces and supporting code. It
* also serves as a library of functionality for defining new execution engine
* implementations.
* </p>
* <p>
* The {@link jdk.jshell.tool} package supports programmatically launching the
* <em>jshell</em> tool.
* </p>
* <p>
* The {@link jdk.jshell.execution} package contains implementations of the
* interfaces in {@link jdk.jshell.spi}. Otherwise, the four packages are
* independent, operate at different levels, and do not share functionality or
* definitions.
* </p>
*
* <dl style="font-family:'DejaVu Sans', Arial, Helvetica, sans serif">
* <dt class="simpleTagLabel">Tool Guides:
* <dd>{@extLink jshell_tool_reference jshell}
* </dl>
*
* @provides javax.tools.Tool
* @provides jdk.jshell.spi.ExecutionControlProvider
* @uses jdk.jshell.spi.ExecutionControlProvider
*
* @moduleGraph
* @since 9
*/
module jdk.jshell {
requires java.logging;
requires jdk.compiler;
requires jdk.internal.ed;
requires jdk.internal.le;
requires jdk.internal.opt;
requires transitive java.compiler;
requires transitive java.prefs;
requires transitive jdk.jdi;
exports jdk.jshell;
exports jdk.jshell.execution;
exports jdk.jshell.spi;
exports jdk.jshell.tool;
uses jdk.jshell.spi.ExecutionControlProvider;
uses jdk.internal.editor.spi.BuildInEditorProvider;
provides javax.tools.Tool with
jdk.internal.jshell.tool.JShellToolProvider;
provides jdk.jshell.spi.ExecutionControlProvider with
jdk.jshell.execution.JdiExecutionControlProvider,
jdk.jshell.execution.LocalExecutionControlProvider,
jdk.jshell.execution.FailOverExecutionControlProvider;
}
|
3e06d40f573e15961667f93de512b4cd5078b32e
| 13,047 |
java
|
Java
|
dialog/src/main/java/tk/nkduy/dialog/DialogBuilder.java
|
khanhduy1407/Dialog
|
91607ed0698cc87ad335a2339f7a78441229a169
|
[
"Apache-2.0"
] | null | null | null |
dialog/src/main/java/tk/nkduy/dialog/DialogBuilder.java
|
khanhduy1407/Dialog
|
91607ed0698cc87ad335a2339f7a78441229a169
|
[
"Apache-2.0"
] | null | null | null |
dialog/src/main/java/tk/nkduy/dialog/DialogBuilder.java
|
khanhduy1407/Dialog
|
91607ed0698cc87ad335a2339f7a78441229a169
|
[
"Apache-2.0"
] | null | null | null | 30.13164 | 115 | 0.660688 | 2,901 |
package tk.nkduy.dialog;
import android.app.Activity;
import android.content.Context;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import java.util.Arrays;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class DialogBuilder {
private static final int INVALID = -1;
private final int[] margin = new int[4];
private final int[] padding = new int[4];
private final int[] outMostMargin = new int[4];
private final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM
);
private BaseAdapter adapter;
private Context context;
private View footerView;
private View headerView;
private Holder holder;
private int gravity = Gravity.BOTTOM;
private OnItemClickListener onItemClickListener;
private OnClickListener onClickListener;
private OnDismissListener onDismissListener;
private OnCancelListener onCancelListener;
private OnBackPressListener onBackPressListener;
private boolean isCancelable = true;
private int contentBackgroundResource = android.R.color.white;
private int headerViewResourceId = INVALID;
private boolean fixedHeader = false;
private int footerViewResourceId = INVALID;
private boolean fixedFooter = false;
private int inAnimation = INVALID;
private int outAnimation = INVALID;
private boolean expanded;
private int defaultContentHeight;
private int overlayBackgroundResource = R.color.dialogplus_black_overlay;
private DialogBuilder() {
}
/**
* Initialize the builder with a valid context in order to inflate the dialog
*/
DialogBuilder(@NonNull Context context) {
this.context = context;
Arrays.fill(margin, INVALID);
}
/**
* Set the adapter that will be used when ListHolder or GridHolder are passed
*/
public DialogBuilder setAdapter(@NonNull BaseAdapter adapter) {
this.adapter = adapter;
return this;
}
/**
* Set the footer view using the id of the layout resource
*/
public DialogBuilder setFooter(int resourceId) {
return setFooter(resourceId, false);
}
/**
* Set the footer view using the id of the layout resource
*
* @param fixed is used to determine whether footer should be fixed or not. Fixed if true, scrollable otherwise
*/
public DialogBuilder setFooter(int resourceId, boolean fixed) {
this.footerViewResourceId = resourceId;
this.fixedFooter = fixed;
return this;
}
/**
* Sets the given view as footer.
*/
public DialogBuilder setFooter(@NonNull View view) {
return setFooter(view, false);
}
/**
* Sets the given view as footer.
*
* @param fixed is used to determine whether footer should be fixed or not. Fixed if true, scrollable otherwise
*/
public DialogBuilder setFooter(@NonNull View view, boolean fixed) {
this.footerView = view;
this.fixedFooter = fixed;
return this;
}
/**
* Set the header view using the id of the layout resource
*/
public DialogBuilder setHeader(int resourceId) {
return setHeader(resourceId, false);
}
/**
* Set the header view using the id of the layout resource
*
* @param fixed is used to determine whether header should be fixed or not. Fixed if true, scrollable otherwise
*/
public DialogBuilder setHeader(int resourceId, boolean fixed) {
this.headerViewResourceId = resourceId;
this.fixedHeader = fixed;
return this;
}
/**
* Set the header view using a view
*/
public DialogBuilder setHeader(@NonNull View view) {
return setHeader(view, false);
}
/**
* Set the header view using a view
*
* @param fixed is used to determine whether header should be fixed or not. Fixed if true, scrollable otherwise
*/
public DialogBuilder setHeader(@NonNull View view, boolean fixed) {
this.headerView = view;
this.fixedHeader = fixed;
return this;
}
/**
* Define if the dialog is cancelable and should be closed when back pressed or click outside is pressed
*/
public DialogBuilder setCancelable(boolean isCancelable) {
this.isCancelable = isCancelable;
return this;
}
/**
* Set the content of the dialog by passing one of the provided Holders
*/
public DialogBuilder setContentHolder(@NonNull Holder holder) {
this.holder = holder;
return this;
}
/**
* Use setBackgroundResource
*/
@Deprecated public DialogBuilder setBackgroundColorResId(int resourceId) {
return setContentBackgroundResource(resourceId);
}
/**
* Set background color for your dialog. If no resource is passed 'white' will be used
*/
public DialogBuilder setContentBackgroundResource(int resourceId) {
this.contentBackgroundResource = resourceId;
return this;
}
public DialogBuilder setOverlayBackgroundResource(int resourceId) {
this.overlayBackgroundResource = resourceId;
return this;
}
/**
* Set the gravity you want the dialog to have among the ones that are provided
*/
public DialogBuilder setGravity(int gravity) {
this.gravity = gravity;
params.gravity = gravity;
return this;
}
/**
* Customize the in animation by passing an animation resource
*/
public DialogBuilder setInAnimation(int inAnimResource) {
this.inAnimation = inAnimResource;
return this;
}
/**
* Customize the out animation by passing an animation resource
*/
public DialogBuilder setOutAnimation(int outAnimResource) {
this.outAnimation = outAnimResource;
return this;
}
/**
* Add margins to your outmost view which contains everything. As default they are 0
* are applied
*/
public DialogBuilder setOutMostMargin(int left, int top, int right, int bottom) {
this.outMostMargin[0] = left;
this.outMostMargin[1] = top;
this.outMostMargin[2] = right;
this.outMostMargin[3] = bottom;
return this;
}
/**
* Add margins to your dialog. They are set to 0 except when gravity is center. In that case basic margins
* are applied
*/
public DialogBuilder setMargin(int left, int top, int right, int bottom) {
this.margin[0] = left;
this.margin[1] = top;
this.margin[2] = right;
this.margin[3] = bottom;
return this;
}
/**
* Set paddings for the dialog content
*/
public DialogBuilder setPadding(int left, int top, int right, int bottom) {
this.padding[0] = left;
this.padding[1] = top;
this.padding[2] = right;
this.padding[3] = bottom;
return this;
}
/**
* Set an item click listener when list or grid holder is chosen. In that way you can have callbacks when one
* of your items is clicked
*/
public DialogBuilder setOnItemClickListener(OnItemClickListener listener) {
this.onItemClickListener = listener;
return this;
}
/**
* Set a global click listener to you dialog in order to handle all the possible click events. You can then
* identify the view by using its id and handle the correct behaviour
*/
public DialogBuilder setOnClickListener(@Nullable OnClickListener listener) {
this.onClickListener = listener;
return this;
}
public DialogBuilder setOnDismissListener(@Nullable OnDismissListener listener) {
this.onDismissListener = listener;
return this;
}
public DialogBuilder setOnCancelListener(@Nullable OnCancelListener listener) {
this.onCancelListener = listener;
return this;
}
public DialogBuilder setOnBackPressListener(@Nullable OnBackPressListener listener) {
this.onBackPressListener = listener;
return this;
}
public DialogBuilder setExpanded(boolean expanded) {
this.expanded = expanded;
return this;
}
public DialogBuilder setExpanded(boolean expanded, int defaultContentHeight) {
this.expanded = expanded;
this.defaultContentHeight = defaultContentHeight;
return this;
}
public DialogBuilder setContentHeight(int height) {
params.height = height;
return this;
}
public DialogBuilder setContentWidth(int width) {
params.width = width;
return this;
}
/**
* Create the dialog using this builder
*/
@NonNull public Dialog create() {
getHolder().setBackgroundResource(getContentBackgroundResource());
return new Dialog(this);
}
@Nullable public View getFooterView() {
return Utils.getView(context, footerViewResourceId, footerView);
}
@Nullable public View getHeaderView() {
return Utils.getView(context, headerViewResourceId, headerView);
}
@NonNull public Holder getHolder() {
if (holder == null) {
holder = new ListHolder();
}
return holder;
}
@NonNull public Context getContext() {
return context;
}
public BaseAdapter getAdapter() {
return adapter;
}
public Animation getInAnimation() {
int res = (inAnimation == INVALID) ? Utils.getAnimationResource(this.gravity, true) : inAnimation;
return AnimationUtils.loadAnimation(context, res);
}
public Animation getOutAnimation() {
int res = (outAnimation == INVALID) ? Utils.getAnimationResource(this.gravity, false) : outAnimation;
return AnimationUtils.loadAnimation(context, res);
}
public FrameLayout.LayoutParams getContentParams() {
if (expanded) {
params.height = getDefaultContentHeight();
}
return params;
}
public boolean isExpanded() {
return expanded;
}
public FrameLayout.LayoutParams getOutmostLayoutParams() {
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
);
params.setMargins(outMostMargin[0], outMostMargin[1], outMostMargin[2], outMostMargin[3]);
return params;
}
public boolean isCancelable() {
return isCancelable;
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public OnClickListener getOnClickListener() {
return onClickListener;
}
public OnDismissListener getOnDismissListener() {
return onDismissListener;
}
public OnCancelListener getOnCancelListener() {
return onCancelListener;
}
public OnBackPressListener getOnBackPressListener() {
return onBackPressListener;
}
public int[] getContentMargin() {
int minimumMargin = context.getResources().getDimensionPixelSize(R.dimen.dialogplus_default_center_margin);
for (int i = 0; i < margin.length; i++) {
margin[i] = getMargin(this.gravity, margin[i], minimumMargin);
}
return margin;
}
public int[] getContentPadding() {
return padding;
}
public int getDefaultContentHeight() {
Activity activity = (Activity) context;
Display display = activity.getWindowManager().getDefaultDisplay();
int displayHeight = display.getHeight() - Utils.getStatusBarHeight(activity);
if (defaultContentHeight == 0) {
defaultContentHeight = (displayHeight * 2) / 5;
}
return defaultContentHeight;
}
public int getOverlayBackgroundResource() {
return overlayBackgroundResource;
}
public int getContentBackgroundResource() {
return contentBackgroundResource;
}
/**
* Get margins if provided or assign default values based on gravity
*
* @param gravity the gravity of the dialog
* @param margin the value defined in the builder
* @param minimumMargin the minimum margin when gravity center is selected
* @return the value of the margin
*/
private int getMargin(int gravity, int margin, int minimumMargin) {
switch (gravity) {
case Gravity.CENTER:
return (margin == INVALID) ? minimumMargin : margin;
default:
return (margin == INVALID) ? 0 : margin;
}
}
public boolean isFixedHeader() {
return fixedHeader;
}
public boolean isFixedFooter() {
return fixedFooter;
}
}
|
3e06d4cd5c4732667b7642a91716e87bccb1c6bd
| 3,870 |
java
|
Java
|
rd-web-impl/src/test/java/io/radien/webapp/permission/PermissionConverterTest.java
|
radien-org/radien-ce
|
9a44472a9ab39ef874787a9c2d871010e33b5240
|
[
"Apache-2.0"
] | 2 |
2021-11-02T21:01:50.000Z
|
2022-01-19T17:06:19.000Z
|
rd-web-impl/src/test/java/io/radien/webapp/permission/PermissionConverterTest.java
|
radien-org/radien-ce
|
9a44472a9ab39ef874787a9c2d871010e33b5240
|
[
"Apache-2.0"
] | null | null | null |
rd-web-impl/src/test/java/io/radien/webapp/permission/PermissionConverterTest.java
|
radien-org/radien-ce
|
9a44472a9ab39ef874787a9c2d871010e33b5240
|
[
"Apache-2.0"
] | 1 |
2021-11-09T10:17:22.000Z
|
2021-11-09T10:17:22.000Z
| 30.96 | 115 | 0.747287 | 2,902 |
/*
* Copyright (c) 2006-present radien GmbH & its legal owners. All rights reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.radien.webapp.permission;
import io.radien.exception.SystemException;
import io.radien.api.model.permission.SystemPermission;
import io.radien.api.service.permission.PermissionRESTServiceAccess;
import io.radien.ms.permissionmanagement.client.entities.Permission;
import io.radien.webapp.JSFUtil;
import io.radien.webapp.JSFUtilAndFaceContextMessagesTest;
import java.util.Optional;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.doReturn;
/**
* Class that aggregates UnitTest cases for PermissionConverter
*
* @author Rajesh Gavvala
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({JSFUtil.class, FacesContext.class, ExternalContext.class})
public class PermissionConverterTest extends JSFUtilAndFaceContextMessagesTest {
@InjectMocks
private PermissionConverter permissionConverter;
@Mock
private PermissionRESTServiceAccess permissionRESTServiceAccess;
FacesContext facesContext;
SystemPermission systemPermission;
Optional<SystemPermission> optionalSystemPermission;
/**
* Constructs mock object
*/
@Before
public void before(){
MockitoAnnotations.initMocks(this);
facesContext = getFacesContext();
systemPermission = new Permission();
systemPermission.setName("testPermission");
optionalSystemPermission = Optional.of(systemPermission);
}
/**
* Test method getAsString()
* Asserts Object couldn't be null
*/
@Test
public void testGetAsObject() throws SystemException {
doReturn(optionalSystemPermission).when(permissionRESTServiceAccess).getPermissionByName("testPermission");
assertNotNull(permissionConverter.getAsObject(facesContext, null, "testPermission"));
}
/**
* Test method getAsString()
* Asserts Object null
*/
@Test
public void testGetAsObjectNull() {
assertNull(permissionConverter.getAsObject(facesContext, null, ""));
}
/**
* Test method getAsString()
* Asserts ConversionException
*/
@Test(expected = ConverterException.class)
public void testGetAsObjectConversionError() throws SystemException {
doReturn(optionalSystemPermission).when(permissionRESTServiceAccess).getPermissionByName("");
permissionConverter.getAsObject(facesContext, null, "testPermission");
}
/**
* Test method getAsString()
* Asserts equality the test method
* Returns value
*/
@Test
public void testGetAsString(){
String expected = permissionConverter.getAsString(null, null, systemPermission);
assertEquals(systemPermission.getName(), expected);
}
}
|
3e06d59d92181c6a6bead742c326a92d78188529
| 1,306 |
java
|
Java
|
cdt-java-client/src/main/java/com/github/kklisura/cdt/protocol/types/profiler/PositionTickInfo.java
|
sinaa/chrome-devtools-java-client
|
5123704e373059460314e8411cfe22686ce4ed45
|
[
"Apache-2.0"
] | 165 |
2018-04-22T09:09:53.000Z
|
2022-03-22T13:01:37.000Z
|
cdt-java-client/src/main/java/com/github/kklisura/cdt/protocol/types/profiler/PositionTickInfo.java
|
sinaa/chrome-devtools-java-client
|
5123704e373059460314e8411cfe22686ce4ed45
|
[
"Apache-2.0"
] | 58 |
2018-07-03T08:06:38.000Z
|
2022-03-30T05:13:34.000Z
|
cdt-java-client/src/main/java/com/github/kklisura/cdt/protocol/types/profiler/PositionTickInfo.java
|
sinaa/chrome-devtools-java-client
|
5123704e373059460314e8411cfe22686ce4ed45
|
[
"Apache-2.0"
] | 52 |
2018-07-03T07:43:57.000Z
|
2022-03-24T02:57:13.000Z
| 26.12 | 77 | 0.690658 | 2,903 |
package com.github.kklisura.cdt.protocol.types.profiler;
/*-
* #%L
* cdt-java-client
* %%
* Copyright (C) 2018 - 2021 Kenan Klisura
* %%
* 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%
*/
/** Specifies a number of samples attributed to a certain source position. */
public class PositionTickInfo {
private Integer line;
private Integer ticks;
/** Source line number (1-based). */
public Integer getLine() {
return line;
}
/** Source line number (1-based). */
public void setLine(Integer line) {
this.line = line;
}
/** Number of samples attributed to the source line. */
public Integer getTicks() {
return ticks;
}
/** Number of samples attributed to the source line. */
public void setTicks(Integer ticks) {
this.ticks = ticks;
}
}
|
3e06d5c6232d39fbf1c0fda501eededdb841cf69
| 1,277 |
java
|
Java
|
gmall-ums/src/main/java/com/atguigu/gmall/ums/entity/UserStatisticsEntity.java
|
maigo11/gmall-0420
|
086a22f50a0cf369ffd86317b270f4940a5b35ec
|
[
"Apache-2.0"
] | null | null | null |
gmall-ums/src/main/java/com/atguigu/gmall/ums/entity/UserStatisticsEntity.java
|
maigo11/gmall-0420
|
086a22f50a0cf369ffd86317b270f4940a5b35ec
|
[
"Apache-2.0"
] | null | null | null |
gmall-ums/src/main/java/com/atguigu/gmall/ums/entity/UserStatisticsEntity.java
|
maigo11/gmall-0420
|
086a22f50a0cf369ffd86317b270f4940a5b35ec
|
[
"Apache-2.0"
] | null | null | null | 14.860465 | 59 | 0.674491 | 2,904 |
package com.atguigu.gmall.ums.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 统计信息表
*
* @author sqq
* @email [email protected]
* @date 2020-09-21 19:27:42
*/
@Data
@TableName("ums_user_statistics")
public class UserStatisticsEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 用户id
*/
private Long userId;
/**
* 累计消费金额
*/
private BigDecimal consumeAmount;
/**
* 累计优惠金额
*/
private BigDecimal couponAmount;
/**
* 订单数量
*/
private Integer orderCount;
/**
* 优惠券数量
*/
private Integer couponCount;
/**
* 评价数
*/
private Integer commentCount;
/**
* 退货数量
*/
private Integer returnOrderCount;
/**
* 登录次数
*/
private Integer loginCount;
/**
* 关注数量
*/
private Integer attendCount;
/**
* 粉丝数量
*/
private Integer fansCount;
/**
* 收藏的商品数量
*/
private Integer collectProductCount;
/**
* 收藏的专题活动数量
*/
private Integer collectSubjectCount;
/**
* 收藏的评论数量
*/
private Integer collectCommentCount;
/**
* 邀请的朋友数量
*/
private Integer inviteFriendCount;
}
|
3e06d62759869e72bdeab492b965b9a595cfec53
| 7,017 |
java
|
Java
|
runescape-client/src/main/java/StudioGame.java
|
JourneyScape/runelite
|
e97b21c8e0a6205bf10cd1ebb85cb593dcacc64a
|
[
"BSD-2-Clause"
] | null | null | null |
runescape-client/src/main/java/StudioGame.java
|
JourneyScape/runelite
|
e97b21c8e0a6205bf10cd1ebb85cb593dcacc64a
|
[
"BSD-2-Clause"
] | null | null | null |
runescape-client/src/main/java/StudioGame.java
|
JourneyScape/runelite
|
e97b21c8e0a6205bf10cd1ebb85cb593dcacc64a
|
[
"BSD-2-Clause"
] | null | null | null | 36.73822 | 168 | 0.67194 | 2,905 |
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("jr")
@Implements("StudioGame")
public enum StudioGame implements Enumerated {
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "Ljr;"
)
@Export("runescape")
runescape("runescape", "RuneScape", 0),
@ObfuscatedName("t")
@ObfuscatedSignature(
descriptor = "Ljr;"
)
@Export("stellardawn")
stellardawn("stellardawn", "Stellar Dawn", 1),
@ObfuscatedName("v")
@ObfuscatedSignature(
descriptor = "Ljr;"
)
@Export("game3")
game3("game3", "Game 3", 2),
@ObfuscatedName("j")
@ObfuscatedSignature(
descriptor = "Ljr;"
)
@Export("game4")
game4("game4", "Game 4", 3),
@ObfuscatedName("l")
@ObfuscatedSignature(
descriptor = "Ljr;"
)
@Export("game5")
game5("game5", "Game 5", 4),
@ObfuscatedName("n")
@ObfuscatedSignature(
descriptor = "Ljr;"
)
@Export("oldscape")
oldscape("oldscape", "RuneScape 2007", 5);
@ObfuscatedName("fa")
@ObfuscatedSignature(
descriptor = "Lex;"
)
@Export("socketTask")
static Task socketTask;
@ObfuscatedName("hf")
@ObfuscatedSignature(
descriptor = "[Lom;"
)
@Export("headIconPrayerSprites")
static SpritePixels[] headIconPrayerSprites;
@ObfuscatedName("w")
@Export("name")
public final String name;
@ObfuscatedName("f")
@ObfuscatedGetter(
intValue = -840829897
)
@Export("id")
final int id;
StudioGame(String var3, String var4, int var5) {
this.name = var3;
this.id = var5;
}
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "-1806959663"
)
@Export("rsOrdinal")
public int rsOrdinal() {
return this.id;
}
@ObfuscatedName("t")
@ObfuscatedSignature(
descriptor = "(IIIB)Lom;",
garbageValue = "-5"
)
static SpritePixels method4914(int var0, int var1, int var2) {
return (SpritePixels)WorldMapRegion.WorldMapRegion_cachedSprites.get(HitSplatDefinition.method2988(var0, var1, var2));
}
@ObfuscatedName("fv")
@ObfuscatedSignature(
descriptor = "(IS)V",
garbageValue = "6409"
)
@Export("getLoginError")
static void getLoginError(int var0) {
if (var0 == -3) {
Client.setLoginResponseString("Connection timed out.", "Please try using a different world.", "");
} else if (var0 == -2) {
Client.setLoginResponseString("Error connecting to server.", "Please try using a different world.", "");
} else if (var0 == -1) {
Client.setLoginResponseString("No response from server.", "Please try using a different world.", "");
} else if (var0 == 3) {
Login.loginIndex = 3;
Login.field809 = 1;
} else if (var0 == 4) {
Login.loginIndex = 12;
Login.field804 = 0;
} else if (var0 == 5) {
Login.field809 = 2;
Client.setLoginResponseString("Your account has not logged out from its last", "session or the server is too busy right now.", "Please try again in a few minutes.");
} else if (var0 != 68 && (Client.onMobile || var0 != 6)) {
if (var0 == 7) {
Client.setLoginResponseString("This world is full.", "Please use a different world.", "");
} else if (var0 == 8) {
Client.setLoginResponseString("Unable to connect.", "Login server offline.", "");
} else if (var0 == 9) {
Client.setLoginResponseString("Login limit exceeded.", "Too many connections from your address.", "");
} else if (var0 == 10) {
Client.setLoginResponseString("Unable to connect.", "Bad session id.", "");
} else if (var0 == 11) {
Client.setLoginResponseString("We suspect someone knows your password.", "Press 'change your password' on front page.", "");
} else if (var0 == 12) {
Client.setLoginResponseString("You need a members account to login to this world.", "Please subscribe, or use a different world.", "");
} else if (var0 == 13) {
Client.setLoginResponseString("Could not complete login.", "Please try using a different world.", "");
} else if (var0 == 14) {
Client.setLoginResponseString("The server is being updated.", "Please wait 1 minute and try again.", "");
} else if (var0 == 16) {
Client.setLoginResponseString("Too many login attempts.", "Please wait a few minutes before trying again.", "");
} else if (var0 == 17) {
Client.setLoginResponseString("You are standing in a members-only area.", "To play on this world move to a free area first", "");
} else if (var0 == 18) {
Login.loginIndex = 12;
Login.field804 = 1;
} else if (var0 == 19) {
Client.setLoginResponseString("This world is running a closed Beta.", "Sorry invited players only.", "Please use a different world.");
} else if (var0 == 20) {
Client.setLoginResponseString("Invalid loginserver requested.", "Please try using a different world.", "");
} else if (var0 == 22) {
Client.setLoginResponseString("Malformed login packet.", "Please try again.", "");
} else if (var0 == 23) {
Client.setLoginResponseString("No reply from loginserver.", "Please wait 1 minute and try again.", "");
} else if (var0 == 24) {
Client.setLoginResponseString("Error loading your profile.", "Please contact customer support.", "");
} else if (var0 == 25) {
Client.setLoginResponseString("Unexpected loginserver response.", "Please try using a different world.", "");
} else if (var0 == 26) {
Client.setLoginResponseString("This computers address has been blocked", "as it was used to break our rules.", "");
} else if (var0 == 27) {
Client.setLoginResponseString("", "Service unavailable.", "");
} else if (var0 == 31) {
Client.setLoginResponseString("Your account must have a displayname set", "in order to play the game. Please set it", "via the website, or the main game.");
} else if (var0 == 32) {
Client.setLoginResponseString("Your attempt to log into your account was", "unsuccessful. Don't worry, you can sort", "this out by visiting the billing system.");
} else if (var0 == 37) {
Client.setLoginResponseString("Your account is currently inaccessible.", "Please try again in a few minutes.", "");
} else if (var0 == 38) {
Client.setLoginResponseString("You need to vote to play!", "Visit runescape.com and vote,", "and then come back here!");
} else if (var0 == 55) {
Login.loginIndex = 8;
} else {
if (var0 == 56) {
Client.setLoginResponseString("Enter the 6-digit code generated by your", "authenticator app.", "");
class16.updateGameState(11);
return;
}
if (var0 == 57) {
Client.setLoginResponseString("The code you entered was incorrect.", "Please try again.", "");
class16.updateGameState(11);
return;
}
if (var0 == 61) {
Login.loginIndex = 7;
} else {
Client.setLoginResponseString("Unexpected server response", "Please try using a different world.", "");
}
}
} else {
Client.setLoginResponseString("RuneScape has been updated!", "Please reload this page.", "");
}
class16.updateGameState(10);
}
}
|
3e06d6703043f555d96e555b12d2a70029cced88
| 1,937 |
java
|
Java
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DefaultBinaryArithmeticOperation.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null |
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DefaultBinaryArithmeticOperation.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null |
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DefaultBinaryArithmeticOperation.java
|
diwasjoshi/elasticsearch
|
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
|
[
"Apache-2.0"
] | null | null | null | 28.485294 | 105 | 0.710377 | 2,906 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Arithmetics.NumericArithmetic;
import java.io.IOException;
import java.util.function.BiFunction;
public enum DefaultBinaryArithmeticOperation implements BinaryArithmeticOperation {
ADD(Arithmetics::add, "+"),
SUB(Arithmetics::sub, "-"),
MUL(Arithmetics::mul, "*"),
DIV(Arithmetics::div, "/"),
MOD(Arithmetics::mod, "%");
public static final String NAME = "abn-def";
private final BiFunction<Object, Object, Object> process;
private final String symbol;
DefaultBinaryArithmeticOperation(BiFunction<Object, Object, Object> process, String symbol) {
this.process = process;
this.symbol = symbol;
}
DefaultBinaryArithmeticOperation(NumericArithmetic process, String symbol) {
this(process::wrap, symbol);
}
@Override
public String symbol() {
return symbol;
}
@Override
public final Object doApply(Object left, Object right) {
return process.apply(left, right);
}
@Override
public String toString() {
return symbol;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeEnum(this);
}
public static DefaultBinaryArithmeticOperation read(StreamInput in) throws IOException {
return in.readEnum(DefaultBinaryArithmeticOperation.class);
}
}
|
3e06d689dcd15c7a5734e4c98d56dccc852c7a89
| 807 |
java
|
Java
|
commons-buffer/src/test/java/com/navercorp/pinpoint/common/buffer/StringCacheableBufferTest.java
|
windy26205/pinpoint
|
fe99471106ba2c28cf7170e30632c95ef2644f3b
|
[
"Apache-2.0"
] | 1,473 |
2020-10-14T02:18:07.000Z
|
2022-03-31T11:43:49.000Z
|
commons-buffer/src/test/java/com/navercorp/pinpoint/common/buffer/StringCacheableBufferTest.java
|
windy26205/pinpoint
|
fe99471106ba2c28cf7170e30632c95ef2644f3b
|
[
"Apache-2.0"
] | 995 |
2020-10-14T05:09:43.000Z
|
2022-03-31T12:04:05.000Z
|
commons-buffer/src/test/java/com/navercorp/pinpoint/common/buffer/StringCacheableBufferTest.java
|
windy26205/pinpoint
|
fe99471106ba2c28cf7170e30632c95ef2644f3b
|
[
"Apache-2.0"
] | 446 |
2020-10-14T02:42:50.000Z
|
2022-03-31T03:03:53.000Z
| 27.827586 | 99 | 0.700124 | 2,907 |
package com.navercorp.pinpoint.common.buffer;
import com.navercorp.pinpoint.common.util.LRUCache;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer;
public class StringCacheableBufferTest {
@Test
public void stringCache() {
Buffer writer = new AutomaticBuffer();
writer.putPrefixedString("abc");
writer.putPrefixedString("123");
writer.putPrefixedString("abc");
StringAllocator allocator = new CachedStringAllocator(new LRUCache<ByteBuffer, String>(2));
Buffer buffer = new StringCacheableBuffer(writer.getBuffer(), allocator);
String s1 = buffer.readPrefixedString();
String s2 = buffer.readPrefixedString();
String s3 = buffer.readPrefixedString();
Assert.assertSame(s1, s3);
}
}
|
3e06d7442273cc51a74c67e732549da65d3751ad
| 4,383 |
java
|
Java
|
src/test/java/com/i4one/base/tests/core/AgedLRUMapTest.java
|
badiozam/concord
|
343842aa69f25ff9917e51936eabe72999b81407
|
[
"MIT"
] | null | null | null |
src/test/java/com/i4one/base/tests/core/AgedLRUMapTest.java
|
badiozam/concord
|
343842aa69f25ff9917e51936eabe72999b81407
|
[
"MIT"
] | 1 |
2020-07-01T19:26:51.000Z
|
2020-07-01T19:26:51.000Z
|
src/test/java/com/i4one/base/tests/core/AgedLRUMapTest.java
|
badiozam/concord
|
343842aa69f25ff9917e51936eabe72999b81407
|
[
"MIT"
] | null | null | null | 26.089286 | 81 | 0.69587 | 2,908 |
/*
* MIT License
*
* Copyright (c) 2018 i4one Interactive, LLC
*
* 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.i4one.base.tests.core;
import org.junit.Test;
import com.i4one.base.core.AgingLRUMap;
import com.i4one.base.core.AgingObject;
import static java.lang.Integer.valueOf;
import static java.lang.Thread.sleep;
import org.junit.Before;
import static org.junit.Assert.*;
/**
* @author Hamid Badiozamani
*/
public class AgedLRUMapTest
{
private AgingLRUMap<Integer, Integer> map;
// Max age for each object is 100ms
//
private static final int MAXAGE = 100;
private static final int MAXSIZE = 3;
@Before
public void setUp()
{
map = new AgingLRUMap<>(MAXSIZE, MAXAGE);
map.put(0, 1);
map.put(1, 1);
map.put(2, 2);
}
@Test
public void testAgedObject() throws InterruptedException
{
AgingObject<Integer> agedObject = new AgingObject<>(42, MAXAGE);
assertNotNull(agedObject.getObject());
assertEquals(valueOf(42), agedObject.getObject());
sleep(MAXAGE + 1);
assertNull(agedObject.getObject());
// The object should be valid from birth to birth + age milliseconds
//
for ( int i = 0; i < MAXAGE; i++ )
{
long currTime = agedObject.getBirthTime() + i;
assertEquals(valueOf(42), agedObject.getObject(currTime));
}
}
@Test
public void testSetsAndGets() throws InterruptedException
{
assertEquals(map.get(0), valueOf(1));
assertEquals(map.get(1), valueOf(1));
assertEquals(map.get(2), valueOf(2));
assertEquals(3, map.size());
sleep(MAXAGE + 1);
// Despite having expired objects in there the size
// remains the same
//
assertEquals(3, map.size());
assertNull(map.get(0));
assertNull(map.get(1));
assertNull(map.get(2));
// Having attempted to access the expired elements should
// have removed them from the map
//
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
@Test
public void testDropOff()
{
// First make the first and second items the most recently used
//
Integer val = map.get(1);
assertEquals(val, valueOf(1));
val = map.get(0);
assertEquals(val, valueOf(1));
// Now add one more element
//
map.put(3, 3);
// Here both the first and second element should still exist
//
assertEquals(valueOf(1), map.get(0));
assertEquals(valueOf(1), map.get(1));
assertEquals(valueOf(3), map.get(3));
assertNull(map.get(2));
}
@Test
public void testOverwrite() throws InterruptedException
{
assertEquals(valueOf(2), map.get(2));
map.put(2, 5);
assertEquals(valueOf(5), map.get(2));
// Add more elements
//
map.put(3, 3);
map.put(4, 5);
map.put(5, 8);
// All of the first three elements should have been overwritten
//
assertNull(map.get(0));
assertNull(map.get(1));
assertNull(map.get(2));
// Make sure the new values work
//
assertEquals(valueOf(3), map.get(3));
assertEquals(valueOf(5), map.get(4));
assertEquals(valueOf(8), map.get(5));
// Now, let's sleep for a little to let the objects age
//
sleep(MAXAGE / 2 + 1);
// Re-insert values for a few items
map.put(3, 3);
map.put(4, 4);
sleep(MAXAGE / 2 + 1);
// Here the oldest element should be removed, but the newly
// inserted ones still have some time left
//
assertNull(map.get(5));
assertEquals(valueOf(3), map.get(3));
assertEquals(valueOf(4), map.get(4));
}
}
|
3e06d84f1734492a0bb8150f4b8b53a747fd266b
| 369 |
java
|
Java
|
GreenNest/src/main/java/com/example/GreenNest/repository/OrderDetailsRepository.java
|
GreenNest/Backend
|
ae05edf8fed0873c608ac6d18fc8b2427ddac066
|
[
"Apache-2.0"
] | null | null | null |
GreenNest/src/main/java/com/example/GreenNest/repository/OrderDetailsRepository.java
|
GreenNest/Backend
|
ae05edf8fed0873c608ac6d18fc8b2427ddac066
|
[
"Apache-2.0"
] | null | null | null |
GreenNest/src/main/java/com/example/GreenNest/repository/OrderDetailsRepository.java
|
GreenNest/Backend
|
ae05edf8fed0873c608ac6d18fc8b2427ddac066
|
[
"Apache-2.0"
] | null | null | null | 28.384615 | 83 | 0.831978 | 2,909 |
package com.example.GreenNest.repository;
import com.example.GreenNest.model.Customer;
import com.example.GreenNest.model.OrderDetails;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface OrderDetailsRepository extends JpaRepository<OrderDetails, Long> {
List<OrderDetails> findByCustomer(Customer customer);
}
|
3e06d893bb1348c2e728af6c241a99b04c8854ba
| 3,562 |
java
|
Java
|
spring-boot/webflux-tdd-demo/src/main/java/com/pintailconsultingllc/webflux/demo/controllers/DepartmentController.java
|
cebartling/test-driven
|
e75ffd7e1f117f69a88c382e75955db184245a6a
|
[
"MIT"
] | 3 |
2021-12-01T14:02:02.000Z
|
2022-01-28T14:55:16.000Z
|
spring-boot/webflux-tdd-demo/src/main/java/com/pintailconsultingllc/webflux/demo/controllers/DepartmentController.java
|
cebartling/test-driven
|
e75ffd7e1f117f69a88c382e75955db184245a6a
|
[
"MIT"
] | null | null | null |
spring-boot/webflux-tdd-demo/src/main/java/com/pintailconsultingllc/webflux/demo/controllers/DepartmentController.java
|
cebartling/test-driven
|
e75ffd7e1f117f69a88c382e75955db184245a6a
|
[
"MIT"
] | null | null | null | 40.022472 | 98 | 0.740034 | 2,910 |
package com.pintailconsultingllc.webflux.demo.controllers;
import com.pintailconsultingllc.webflux.demo.dtos.DepartmentDTO;
import com.pintailconsultingllc.webflux.demo.entities.Department;
import com.pintailconsultingllc.webflux.demo.exceptions.ResourceLocationURIException;
import com.pintailconsultingllc.webflux.demo.repositories.DepartmentRepository;
import com.pintailconsultingllc.webflux.demo.services.DepartmentService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
@RequiredArgsConstructor
@RestController
@RequestMapping("/departments")
public class DepartmentController {
public static final String APPLICATION_JSON = "application/json";
private final DepartmentRepository departmentRepository;
private final DepartmentService departmentService;
@GetMapping
public Flux<DepartmentDTO> getAllDepartments() {
return departmentRepository.findAll().map(DepartmentDTO::new);
}
@GetMapping("/{id}")
public Mono<ResponseEntity<DepartmentDTO>> getDepartmentById(
@PathVariable("id") BigInteger id
) {
return departmentRepository.findById(id)
.map(DepartmentDTO::new)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}
@SneakyThrows
@PostMapping(consumes = APPLICATION_JSON)
@ResponseStatus(HttpStatus.CREATED)
public Mono<ResponseEntity<Void>> create(@RequestBody DepartmentDTO departmentDTO) {
return departmentService.create(departmentDTO)
.map(department -> ResponseEntity.created(createResourceUri(department)).build());
}
@PutMapping(value = "/{id}", consumes = APPLICATION_JSON)
@ResponseStatus(HttpStatus.NO_CONTENT)
public Mono<ResponseEntity<Void>> update(
@PathVariable("id") BigInteger id,
@RequestBody DepartmentDTO departmentDTO
) {
return departmentService.update(id, departmentDTO)
.map(department -> ResponseEntity.noContent().<Void>build())
.defaultIfEmpty(ResponseEntity.notFound().build());
}
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public Mono<ResponseEntity<Void>> delete(
@PathVariable("id") BigInteger id
) {
return departmentService.delete(id)
.map(department -> ResponseEntity.noContent().<Void>build())
.defaultIfEmpty(ResponseEntity.notFound().build());
}
private URI createResourceUri(Department department) {
try {
return new URI(String.format("/departments/%d", department.getId()));
} catch (URISyntaxException e) {
throw new ResourceLocationURIException(e);
}
}
}
|
3e06d9dabb7370a1831f5f75e8ab3c3049005929
| 1,533 |
java
|
Java
|
com/strongdm/api/v1/AccountUpdateResponse.java
|
strongdm/strongdm-sdk-java
|
4515cca7b17b1778f47c4b068862e57a0b605789
|
[
"Apache-2.0"
] | 3 |
2021-04-29T19:45:36.000Z
|
2022-03-24T20:25:09.000Z
|
com/strongdm/api/v1/AccountUpdateResponse.java
|
strongdm/strongdm-sdk-java
|
4515cca7b17b1778f47c4b068862e57a0b605789
|
[
"Apache-2.0"
] | null | null | null |
com/strongdm/api/v1/AccountUpdateResponse.java
|
strongdm/strongdm-sdk-java
|
4515cca7b17b1778f47c4b068862e57a0b605789
|
[
"Apache-2.0"
] | 1 |
2021-07-27T12:47:26.000Z
|
2021-07-27T12:47:26.000Z
| 28.924528 | 85 | 0.729289 | 2,911 |
// Copyright 2020 StrongDM 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.
//
// This file was generated by protogen. DO NOT EDIT.
package com.strongdm.api.v1;
// AccountUpdateResponse returns the fields of a Account after it has been updated by
// a AccountUpdateRequest.
public class AccountUpdateResponse {
private UpdateResponseMetadata meta;
// Reserved for future use.
public UpdateResponseMetadata getMeta() {
return this.meta;
}
// Reserved for future use.
public void setMeta(UpdateResponseMetadata in) {
this.meta = in;
}
private Account account;
// The updated Account.
public Account getAccount() {
return this.account;
}
// The updated Account.
public void setAccount(Account in) {
this.account = in;
}
private RateLimitMetadata rateLimit;
// Rate limit information.
public RateLimitMetadata getRateLimit() {
return this.rateLimit;
}
// Rate limit information.
public void setRateLimit(RateLimitMetadata in) {
this.rateLimit = in;
}
}
|
3e06dc39118b2b3359972545b6dc0355657dab5d
| 1,374 |
java
|
Java
|
src/main/java/com/smartling/marketo/sdk/domain/landingpagetemplate/LandingPageTemplateContent.java
|
dmitry-cherkas/marketo-rest-sdk-java
|
fdf8f975ecc6e8a7800677d81aeb1aa1d9ab615a
|
[
"Apache-2.0"
] | 9 |
2015-06-29T21:46:19.000Z
|
2018-11-09T07:28:57.000Z
|
src/main/java/com/smartling/marketo/sdk/domain/landingpagetemplate/LandingPageTemplateContent.java
|
dmitry-cherkas/marketo-rest-sdk-java
|
fdf8f975ecc6e8a7800677d81aeb1aa1d9ab615a
|
[
"Apache-2.0"
] | 11 |
2015-06-04T12:56:47.000Z
|
2021-03-09T12:51:26.000Z
|
src/main/java/com/smartling/marketo/sdk/domain/landingpagetemplate/LandingPageTemplateContent.java
|
dmitry-cherkas/marketo-rest-sdk-java
|
fdf8f975ecc6e8a7800677d81aeb1aa1d9ab615a
|
[
"Apache-2.0"
] | 8 |
2016-08-22T17:11:41.000Z
|
2022-03-05T06:37:10.000Z
| 23.288136 | 133 | 0.633916 | 2,912 |
package com.smartling.marketo.sdk.domain.landingpagetemplate;
import com.smartling.marketo.sdk.domain.Asset;
public class LandingPageTemplateContent {
private int id;
private Asset.Status status;
private String content;
private TemplateType templateType;
private Boolean enableMunchkin;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Asset.Status getStatus() {
return status;
}
public void setStatus(Asset.Status status) {
this.status = status;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public TemplateType getTemplateType() {
return templateType;
}
public void setTemplateType(TemplateType templateType) {
this.templateType = templateType;
}
public Boolean getEnableMunchkin() {
return enableMunchkin;
}
public void setEnableMunchkin(Boolean enableMunchkin) {
this.enableMunchkin = enableMunchkin;
}
@Override
public String toString()
{
return "LandingPageTemplateContent{" + "id=" + id + ", status=" + status + ", content='" + content + '\'' + ", templateType="
+ templateType + ", enableMunchkin=" + enableMunchkin + '}';
}
}
|
3e06dc9a92f57a4868cab52019bf704bab8562a5
| 2,085 |
java
|
Java
|
core/src/test/java/org/infinispan/container/offheap/OffHeapBoundedMultiNodeTest.java
|
clara0/infinispan
|
f2cb717bbd51dd8e3e4265679585cd637a55bed5
|
[
"Apache-2.0"
] | 713 |
2015-01-06T02:14:17.000Z
|
2022-03-29T10:22:07.000Z
|
core/src/test/java/org/infinispan/container/offheap/OffHeapBoundedMultiNodeTest.java
|
clara0/infinispan
|
f2cb717bbd51dd8e3e4265679585cd637a55bed5
|
[
"Apache-2.0"
] | 5,732 |
2015-01-01T19:13:35.000Z
|
2022-03-31T16:31:11.000Z
|
core/src/test/java/org/infinispan/container/offheap/OffHeapBoundedMultiNodeTest.java
|
clara0/infinispan
|
f2cb717bbd51dd8e3e4265679585cd637a55bed5
|
[
"Apache-2.0"
] | 402 |
2015-01-05T23:23:42.000Z
|
2022-03-25T08:14:32.000Z
| 33.095238 | 114 | 0.709832 | 2,913 |
package org.infinispan.container.offheap;
import static org.testng.AssertJUnit.fail;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "container.offheap.OffHeapBoundedMultiNodeTest")
public class OffHeapBoundedMultiNodeTest extends OffHeapMultiNodeTest {
static final int EVICTION_SIZE = NUMBER_OF_KEYS + 1;
private TransactionMode transactionMode;
OffHeapBoundedMultiNodeTest transactionMode(TransactionMode mode) {
this.transactionMode = mode;
return this;
}
@Override
protected Object[] parameterValues() {
return concat(super.parameterValues(), transactionMode);
}
@Override
protected String[] parameterNames() {
return concat(super.parameterNames(), "transactionMode");
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
dcc.memory().storageType(StorageType.OFF_HEAP).size(EVICTION_SIZE);
dcc.transaction().transactionMode(transactionMode);
createCluster(dcc, 4);
waitForClusterToForm();
}
@Override
public Object[] factory() {
return new Object[] {
new OffHeapBoundedMultiNodeTest().transactionMode(TransactionMode.TRANSACTIONAL),
new OffHeapBoundedMultiNodeTest().transactionMode(TransactionMode.NON_TRANSACTIONAL)
};
}
public void testEviction() {
for (int i = 0; i < EVICTION_SIZE * 4; ++i) {
cache(0).put("key" + i, "value" + i);
}
for (Cache cache : caches()) {
int size = cache.getAdvancedCache().getDataContainer().size();
if (size > EVICTION_SIZE) {
fail("Container size was: " + size + ", it is supposed to be less than or equal to " + EVICTION_SIZE);
}
}
}
}
|
3e06dd8fa072b2b50ff2f458ef23bb9c8d196a55
| 1,948 |
java
|
Java
|
src/com/arpablue/arpatest/examples/Example1.java
|
augusto-flores-arpablue-com/arpatest_java
|
70ab682e103f8198abe3bfb6de80242a2c1dea6f
|
[
"MIT"
] | null | null | null |
src/com/arpablue/arpatest/examples/Example1.java
|
augusto-flores-arpablue-com/arpatest_java
|
70ab682e103f8198abe3bfb6de80242a2c1dea6f
|
[
"MIT"
] | null | null | null |
src/com/arpablue/arpatest/examples/Example1.java
|
augusto-flores-arpablue-com/arpatest_java
|
70ab682e103f8198abe3bfb6de80242a2c1dea6f
|
[
"MIT"
] | null | null | null | 28.231884 | 79 | 0.629363 | 2,914 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.arpablue.arpatest.examples;
import com.arpablue.arpatest.testlib.TestCase;
import com.arpablue.arpatest.testlib.TestPlan;
import com.arpablue.arpatest.testlib.TestSuit;
/**
* It is an example that show how build a simple test plan
* @author Augusto Flores
*/
public class Example1 {
public static void main(String[] args) {
// Create the test suit
TestSuit testsuit = new TestSuit( "First Suit" );
// Add the test case ojects to the test suit.
testsuit.add( new TestCaseExample1( "Test Case 1" ) );
testsuit.add( new TestCaseExample1( "Test Case 2" ) );
testsuit.add( new TestCaseExample1( "Test Case 3" ) );
// Create the test plan
TestPlan testplan = new TestPlan("Target Test Plan");
// Add the test suit to the test plan.
testplan.add( testsuit );
// execute the test suit.
testplan.execute();
}
}
/**
* Implementation of the Test Case object.
* @author Augusto Flores
*/
class TestCaseExample1 extends TestCase{
public TestCaseExample1(){
super();
}
public TestCaseExample1( String name){
super( name );
}
/**
* It is executed before the execution of the test case.
*/
@Override
protected void before() {
this.msg("It is before the execution of the test case.");
}
/**
* It is executed after the execute the test case.
*/
@Override
protected void after() {
this.msg("It is after the execution of the test case.");
}
/**
* It is the execution of the steps of the test cases.
*/
@Override
protected void testRun() {
this.msg("It is during the execution of the test case.");
}
}
|
3e06ddf176ccfb7472f68dd648bd590290b31283
| 7,101 |
java
|
Java
|
projects/checkstyle/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectReturnAndParameter.java
|
pwr-pbrwio/PBR20M2
|
98904cb265baa7ce6a00455ea6edb8366a51c61b
|
[
"Apache-2.0"
] | 5 |
2018-12-13T17:46:39.000Z
|
2022-03-29T02:07:47.000Z
|
projects/checkstyle/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectReturnAndParameter.java
|
pwr-pbrwio/PBR20M2
|
98904cb265baa7ce6a00455ea6edb8366a51c61b
|
[
"Apache-2.0"
] | 42 |
2019-12-08T18:41:13.000Z
|
2021-08-28T13:08:55.000Z
|
projects/checkstyle/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectReturnAndParameter.java
|
sealuzh/lightweight-effectiveness
|
f6ef4c98b8f572a86e42252686995b771e655f80
|
[
"MIT"
] | 8 |
2018-12-25T04:19:01.000Z
|
2021-03-24T17:02:44.000Z
| 49.657343 | 100 | 0.657091 | 2,915 |
package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0
class FooReturnClass { //indent:0 exp:0
String getString(int someInt, String someString) { //indent:2 exp:2
return "String"; //indent:4 exp:4
} //indent:2 exp:2
boolean fooMethodWithIf() { //indent:2 exp:2
return conditionSecond(10000000000.0, new //indent:4 exp:4
SecondClassLongName("Looooooooooooo" //indent:8 exp:8
+ "oooooooooooong").getString(new FooReturnClass(), //indent:8 exp:8
new SecondClassLongName("loooooooooong"). //indent:8 exp:8
getInteger(new FooReturnClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8
|| conditionThird(2048) || conditionFourth(new //indent:8 exp:8
SecondClassLongName("Looooooooooooooo" //indent:8 exp:8
+ "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:8 exp:8
conditionFifth(true, new SecondClassLongName(getString(2048, "Looo" //indent:8 exp:8
+ "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8
new FooReturnClass(), true)) || conditionSixth(false, new //indent:8 exp:8
SecondClassLongName(getString(100000, "Loooooong" //indent:8 exp:8
+ "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8
|| conditionNoArg() || //indent:8 exp:8
conditionNoArg() || conditionNoArg();//indent:8 exp:8
} //indent:2 exp:2
private boolean conditionFirst(String longString, int //indent:2 exp:2
integer, InnerClassFoo someInstance) { //indent:6 exp:6
return false; //indent:4 exp:4
} //indent:2 exp:2
private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2
String longLongLongString, String secondLongLongString) { //indent:6 exp:6
return false; //indent:4 exp:4
} //indent:2 exp:2
private boolean conditionThird(long veryLongValue) { //indent:2 exp:2
return false; //indent:4 exp:4
} //indent:2 exp:2
private boolean conditionFourth(boolean flag) { //indent:2 exp:2
return false; //indent:4 exp:4
} //indent:2 exp:2
private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2
return false; //indent:4 exp:4
} //indent:2 exp:2
private boolean conditionSixth(boolean flag, //indent:2 exp:2
SecondClassLongName instance) { //indent:6 exp:6
return false; //indent:4 exp:4
} //indent:2 exp:2
private boolean conditionNoArg() { //indent:2 exp:2
return false; //indent:4 exp:4
} //indent:2 exp:2
class InnerClassFoo { //indent:2 exp:2
boolean fooMethodWithIf() { //indent:4 exp:4
return conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6
SecondClassLongName("Loooooooooooooooooog"). //indent:10 exp:10
getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10
new InnerClassFoo()); //indent:14 exp:>=10
} //indent:4 exp:4
boolean fooReturn() { //indent:4 exp:4
return conditionSecond(10000000000.0, new //indent:6 exp:6
SecondClassLongName("Looooooooooooo" //indent:10 exp:10
+ "oooooooooooong").getString(new FooReturnClass(), //indent:10 exp:10
new SecondClassLongName("loooooooooong"). //indent:10 exp:10
getInteger(new FooReturnClass(), "looooooooooong")), "loooooooooooong") //indent:10 exp:10
|| conditionThird(2048) || conditionFourth(new //indent:10 exp:10
SecondClassLongName("Looooooooooooooo" //indent:10 exp:10
+ "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:12 exp:>=10
conditionFifth(true, new SecondClassLongName(getString(2048, "Looo" //indent:12 exp:>=10
+ "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10
new FooReturnClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10
SecondClassLongName(getString(100000, "Loooooong" //indent:14 exp:>=10
+ "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10
|| conditionNoArg() || //indent:14 exp:>=10
conditionNoArg() || conditionNoArg(); //indent:14 exp:>=10
} //indent:4 exp:4
FooReturnClass anonymousClass = new FooReturnClass() { //indent:4 exp:4
boolean fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6
int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10
fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10
return conditionSecond(10000000000.0, new //indent:8 exp:8
SecondClassLongName("Looooooooooooo" //indent:12 exp:12
+ "oooooooooooong").getString(new FooReturnClass(), //indent:12 exp:12
new SecondClassLongName("loooooooooong"). //indent:12 exp:12
getInteger(new FooReturnClass(), "looooooooong")), "loooooooooooong") //indent:12 exp:12
|| conditionThird(2048) || conditionFourth(new //indent:12 exp:12
SecondClassLongName("Looooooooooooooo" //indent:12 exp:12
+ "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:14 exp:>=12
conditionFifth(true, new SecondClassLongName(getString(2048, "Lo" //indent:14 exp:>=12
+ "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12
new FooReturnClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12
SecondClassLongName(getString(100000, "Loooooong" //indent:16 exp:>=12
+ "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12
|| conditionNoArg() || //indent:16 exp:>=12
conditionNoArg() || conditionNoArg() //indent:18 exp:>=12
&& fooooooooobooleanBooleanVeryLongName; //indent:21 exp:>=12
} //indent:6 exp:6
boolean fooReturn() { //indent:6 exp:6
return conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8
SecondClassLongName("Loooooooooooooooooog"). //indent:12 exp:12
getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12
new InnerClassFoo()); //indent:19 exp:>=12
} //indent:6 exp:6
}; //indent:4 exp:4
} //indent:2 exp:2
} //indent:0 exp:0
class SecondClassLongName { //indent:0 exp:0
public SecondClassLongName(String string) { //indent:2 exp:2
} //indent:2 exp:2
String getString(FooReturnClass instance, int integer) { //indent:2 exp:2
return "String"; //indent:4 exp:4
} //indent:2 exp:2
int getInteger(FooReturnClass instance, String string) { //indent:2 exp:2
return -1; //indent:4 exp:4
} //indent:2 exp:2
boolean getBoolean(FooReturnClass instance, boolean flag) { //indent:2 exp:2
return false; //indent:4 exp:4
} //indent:2 exp:2
SecondClassLongName getInstance() { //indent:2 exp:2
return new SecondClassLongName("VeryLoooooooooo" //indent:4 exp:4
+ "oongString"); //indent:8 exp:8
} //indent:2 exp:2
} //indent:0 exp:0
|
3e06de001e901a54c062f6dc3b762636d0ddafb9
| 4,819 |
java
|
Java
|
main/geo/src/boofcv/alg/geo/triangulate/TriangulateLinearDLT.java
|
jooink/BoofCV
|
2b34e3b167f545e5bbc327bc7032adfdb7a1c3a0
|
[
"Apache-2.0"
] | 1 |
2019-08-20T18:34:37.000Z
|
2019-08-20T18:34:37.000Z
|
main/geo/src/boofcv/alg/geo/triangulate/TriangulateLinearDLT.java
|
jooink/BoofCV
|
2b34e3b167f545e5bbc327bc7032adfdb7a1c3a0
|
[
"Apache-2.0"
] | 2 |
2021-05-18T20:53:57.000Z
|
2022-02-01T01:05:11.000Z
|
main/geo/src/boofcv/alg/geo/triangulate/TriangulateLinearDLT.java
|
jooink/BoofCV
|
2b34e3b167f545e5bbc327bc7032adfdb7a1c3a0
|
[
"Apache-2.0"
] | null | null | null | 30.11875 | 122 | 0.673791 | 2,916 |
/*
* Copyright (c) 2011-2014, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.geo.triangulate;
import georegression.struct.point.Point2D_F64;
import georegression.struct.point.Point3D_F64;
import georegression.struct.point.Vector3D_F64;
import georegression.struct.se.Se3_F64;
import org.ejml.data.DenseMatrix64F;
import org.ejml.factory.DecompositionFactory;
import org.ejml.interfaces.decomposition.SingularValueDecomposition;
import org.ejml.ops.SingularOps;
import java.util.List;
/**
* <p>
* Triangulates the location of a 3D point given two or more views of the point using the
* Discrete Linear Transform (DLT).
* </p>
*
* <p>
* [1] Page 312 in R. Hartley, and A. Zisserman, "Multiple View Geometry in Computer Vision", 2nd Ed, Cambridge 2003 </li>
* </p>
*
* @author Peter Abeles
*/
public class TriangulateLinearDLT {
SingularValueDecomposition<DenseMatrix64F> svd = DecompositionFactory.svd(4, 4,true,true,false);
DenseMatrix64F v = new DenseMatrix64F(4,1);
DenseMatrix64F A = new DenseMatrix64F(4,4);
/**
* <p>
* Given N observations of the same point from two views and a known motion between the
* two views, triangulate the point's position in camera 'b' reference frame.
* </p>
* <p>
* Modification of [1] to be less generic and use calibrated cameras.
* </p>
*
* @param observations Observation in each view in normalized coordinates. Not modified.
* @param worldToView Transformations from world to the view. Not modified.
* @param found Output, the found 3D position of the point. Modified.
*/
public void triangulate( List<Point2D_F64> observations ,
List<Se3_F64> worldToView ,
Point3D_F64 found ) {
if( observations.size() != worldToView.size() )
throw new IllegalArgumentException("Number of observations must match the number of motions");
final int N = worldToView.size();
A.reshape(2*N,4,false);
int index = 0;
for( int i = 0; i < N; i++ ) {
index = addView(worldToView.get(i),observations.get(i),index);
}
if( !svd.decompose(A) )
throw new RuntimeException("SVD failed!?!?");
SingularOps.nullVector(svd,true,v);
double w = v.get(3);
found.x = v.get(0)/w;
found.y = v.get(1)/w;
found.z = v.get(2)/w;
}
/**
* <p>
* Given two observations of the same point from two views and a known motion between the
* two views, triangulate the point's position in camera 'b' reference frame.
* </p>
* <p>
* Modification of [1] to be less generic and use calibrated cameras.
* </p>
*
* @param a Observation 'a' in normalized coordinates. Not modified.
* @param b Observation 'b' in normalized coordinates. Not modified.
* @param fromAtoB Transformation from camera view 'a' to 'b' Not modified.
* @param foundInA Output, the found 3D position of the point. Modified.
*/
public void triangulate( Point2D_F64 a , Point2D_F64 b ,
Se3_F64 fromAtoB ,
Point3D_F64 foundInA ) {
A.reshape(4, 4, false);
int index = addView(fromAtoB,b,0);
// third row
A.data[index++] = -1;
A.data[index++] = 0;
A.data[index++] = a.x;
A.data[index++] = 0;
// fourth row
A.data[index++] = 0;
A.data[index++] = -1;
A.data[index++] = a.y;
A.data[index ] = 0;
if( !svd.decompose(A) )
throw new RuntimeException("SVD failed!?!?");
SingularOps.nullVector(svd,true,v);
double w = v.get(3);
foundInA.x = v.get(0)/w;
foundInA.y = v.get(1)/w;
foundInA.z = v.get(2)/w;
}
private int addView( Se3_F64 motion , Point2D_F64 a , int index ) {
DenseMatrix64F R = motion.getR();
Vector3D_F64 T = motion.getT();
double r11 = R.data[0], r12 = R.data[1], r13 = R.data[2];
double r21 = R.data[3], r22 = R.data[4], r23 = R.data[5];
double r31 = R.data[6], r32 = R.data[7], r33 = R.data[8];
// no normalization of observations are needed since they are in normalized coordinates
// first row
A.data[index++] = a.x*r31-r11;
A.data[index++] = a.x*r32-r12;
A.data[index++] = a.x*r33-r13;
A.data[index++] = a.x*T.z-T.x;
// second row
A.data[index++] = a.y*r31-r21;
A.data[index++] = a.y*r32-r22;
A.data[index++] = a.y*r33-r23;
A.data[index++] = a.y*T.z-T.y;
return index;
}
}
|
3e06dec700c96b18c13db45c86b666abfa41ba42
| 1,215 |
java
|
Java
|
src/test/java/ebay/search/SearchCatalogMenu.java
|
s-santhosha/Serenity_Ebay_GUI_Test
|
b5f541cd42cf67bdc1919884fdcb6094e8db3bb5
|
[
"Apache-2.0"
] | 1 |
2019-06-17T21:57:32.000Z
|
2019-06-17T21:57:32.000Z
|
src/test/java/ebay/search/SearchCatalogMenu.java
|
s-santhosha/Serenity_Ebay_GUI_Test
|
b5f541cd42cf67bdc1919884fdcb6094e8db3bb5
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/ebay/search/SearchCatalogMenu.java
|
s-santhosha/Serenity_Ebay_GUI_Test
|
b5f541cd42cf67bdc1919884fdcb6094e8db3bb5
|
[
"Apache-2.0"
] | null | null | null | 29.634146 | 98 | 0.661728 | 2,917 |
package ebay.search;
import net.serenitybdd.core.steps.UIInteractionSteps;
import net.thucydides.core.annotations.Step;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
public class SearchCatalogMenu extends UIInteractionSteps {
static By HOME_ENTERTAINMENT_LINK = By.cssSelector("ul>li>div a[href*='home-entertainment']");
static By SELECT_FIRST_ITEM = By.cssSelector("[id='w7-items\\[0\\]']");
static By ADD_TO_CART = By.cssSelector("#isCartBtn_btn");
static By OVERLAY_CLOSE = By.cssSelector("#ADDON_0 .addonBtn button.addonnothx");
@Step("Click on catalog menu")
public void clickCatalogMenu(String arg1){
$(By.linkText(arg1)).click();
}
@Step("Click on home entertainment")
public void clickSubItem(){
$(HOME_ENTERTAINMENT_LINK).click();
}
@Step("Select the first item from the listing")
public void selectFirstItem(){
$(SELECT_FIRST_ITEM).click();
}
@Step("Click on Add to Cart")
public void clickAddToCart(){
$(ADD_TO_CART).click();
}
@Step("Handle insurance overlay")
public void overlayHandle(){
$(OVERLAY_CLOSE).click();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.